diff --git a/contrib/bkgrnd2d/bkgrnd2d.cpp b/contrib/bkgrnd2d/bkgrnd2d.cpp index b1159525..c53f0169 100644 --- a/contrib/bkgrnd2d/bkgrnd2d.cpp +++ b/contrib/bkgrnd2d/bkgrnd2d.cpp @@ -293,7 +293,7 @@ bool CBackgroundImage::SetExtentsSel(){ } if ( ( (int)mins[m_ix] == (int)maxs[m_ix] ) || - ( (int)mins[m_iy] == (int)maxs[m_iy] ) ) { + ( (int)mins[m_iy] == (int)maxs[m_iy] ) ) { Syn_Printf( MSG_PREFIX "tiny selection\n" ); return false; } diff --git a/contrib/bkgrnd2d/bkgrnd2d.h b/contrib/bkgrnd2d/bkgrnd2d.h index 41ee2713..5f1a3caf 100644 --- a/contrib/bkgrnd2d/bkgrnd2d.h +++ b/contrib/bkgrnd2d/bkgrnd2d.h @@ -30,55 +30,60 @@ class CBackgroundImage { private: -qtexture_t *m_tex; -VIEWTYPE m_vt; + qtexture_t *m_tex; + VIEWTYPE m_vt; // which components of a vec3_t correspond to x and y in the image -unsigned m_ix,m_iy; + unsigned m_ix,m_iy; public: -CBackgroundImage( VIEWTYPE vt ); + CBackgroundImage( VIEWTYPE vt ); // ~CBackgroundImage(); -float m_alpha; // vertex alpha -bool m_bActive; + float m_alpha; // vertex alpha + bool m_bActive; // x and y axis are in relation to the screen, not world, making rendering // the same for each view type. Whoever sets them is responsible for // shuffling. // units are world units. // TODO should be private -float m_xmin,m_ymin,m_xmax,m_ymax; + float m_xmin,m_ymin,m_xmax,m_ymax; // load file, create new tex, cleanup old tex, set new tex -bool Load( const char *filename ); -void Cleanup(); // free texture, free tex, set make tex NULL -bool SetExtentsMM(); // set extents by ET mapcoordsmaxs/mapcoordsmins -bool SetExtentsSel(); // set extents by selection -void Render(); -bool Valid() { return ( m_tex && ( m_xmin != m_xmax ) && ( m_ymin != m_ymax ) ); } + bool Load( const char *filename ); + void Cleanup(); // free texture, free tex, set make tex NULL + bool SetExtentsMM(); // set extents by ET mapcoordsmaxs/mapcoordsmins + bool SetExtentsSel(); // set extents by selection + void Render(); + bool Valid() { + return ( m_tex && ( m_xmin != m_xmax ) && ( m_ymin != m_ymax ) ); + } }; class CBackgroundRender : public IGL2DWindow { public: -CBackgroundRender(); -virtual ~CBackgroundRender(); + CBackgroundRender(); + virtual ~CBackgroundRender(); protected: -int refCount; + int refCount; public: // IGL2DWindow IGL3DWindow interface -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + void IncRef() { + refCount++; } -} -void Draw2D( VIEWTYPE vt ); -void Register(); + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } + } + void Draw2D( VIEWTYPE vt ); + void Register(); }; extern CBackgroundImage backgroundXY,backgroundXZ,backgroundYZ; diff --git a/contrib/bkgrnd2d/dialog.cpp b/contrib/bkgrnd2d/dialog.cpp index 6aeed31a..086f2560 100644 --- a/contrib/bkgrnd2d/dialog.cpp +++ b/contrib/bkgrnd2d/dialog.cpp @@ -40,20 +40,20 @@ static GtkWidget *pNotebook; class CBackgroundDialogPage { private: -GtkWidget *m_pWidget; -GtkWidget *m_pTabLabel; -GtkWidget *m_pFileLabel; -GtkWidget *m_pPosLabel; -VIEWTYPE m_vt; -bool m_bValidFile; + GtkWidget *m_pWidget; + GtkWidget *m_pTabLabel; + GtkWidget *m_pFileLabel; + GtkWidget *m_pPosLabel; + VIEWTYPE m_vt; + bool m_bValidFile; public: -CBackgroundImage *m_pImage; -CBackgroundDialogPage( VIEWTYPE vt ); -void Append( GtkWidget *notebook ); -void Browse(); -void Reload(); -void SetPosLabel(); + CBackgroundImage *m_pImage; + CBackgroundDialogPage( VIEWTYPE vt ); + void Append( GtkWidget *notebook ); + void Browse(); + void Reload(); + void SetPosLabel(); // ~BackgroundDialogPage(); }; @@ -142,7 +142,7 @@ void CBackgroundDialogPage::Browse(){ //TODO patern gets fucked up sometimes if empty //http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=915 newfile = g_FuncTable.m_pfnFileDialog( pDialogWnd,TRUE, - "Load Background Image",browsedir,FILETYPE_KEY ); + "Load Background Image",browsedir,FILETYPE_KEY ); if ( !newfile ) { Syn_Printf( MSG_PREFIX "newfile = NULL\n" ); return; @@ -166,7 +166,7 @@ void CBackgroundDialogPage::SetPosLabel(){ char s[64]; // TODO no snprintf ? sprintf( s, "Size/Position (%d,%d) (%d,%d)",(int)( m_pImage->m_xmin ), - (int)( m_pImage->m_ymin ),(int)( m_pImage->m_xmax ),(int)( m_pImage->m_ymax ) ); + (int)( m_pImage->m_ymin ),(int)( m_pImage->m_xmax ),(int)( m_pImage->m_ymax ) ); gtk_label_set_text( GTK_LABEL( m_pPosLabel ),s ); } @@ -215,14 +215,14 @@ CBackgroundDialogPage::CBackgroundDialogPage( VIEWTYPE vt ){ w = gtk_button_new_with_label( "Browse..." ); g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( browse_callback ), - ( gpointer ) this ); + ( gpointer ) this ); gtk_box_pack_start( GTK_BOX( hbox ),w, FALSE, FALSE, 5 ); gtk_widget_set_tooltip_text( w, "Select a file" ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Reload" ); g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( reload_callback ), - ( gpointer ) this ); + ( gpointer ) this ); // TODO disable until we have file // gtk_widget_set_sensitive(w,FALSE); gtk_widget_set_tooltip_text( w, "Reload current file" ); @@ -248,7 +248,7 @@ CBackgroundDialogPage::CBackgroundDialogPage( VIEWTYPE vt ){ gtk_range_set_value( GTK_RANGE( w ),0.5 ); gtk_scale_set_value_pos( GTK_SCALE( w ),GTK_POS_LEFT ); g_signal_connect( G_OBJECT( w ), "value-changed", - G_CALLBACK( alpha_adjust_callback ), ( gpointer ) this ); + G_CALLBACK( alpha_adjust_callback ), ( gpointer ) this ); gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, TRUE, 5 ); gtk_widget_set_tooltip_text( w, "Set image transparancy" ); gtk_widget_show( w ); @@ -267,7 +267,7 @@ CBackgroundDialogPage::CBackgroundDialogPage( VIEWTYPE vt ){ w = gtk_button_new_with_label( "from selection" ); gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, FALSE, 5 ); g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( size_sel_callback ), - ( gpointer ) this ); + ( gpointer ) this ); gtk_widget_set_tooltip_text( w, "Set the size of the image to the bounding rectangle of all selected brushes and entities" ); gtk_widget_show( w ); @@ -275,7 +275,7 @@ CBackgroundDialogPage::CBackgroundDialogPage( VIEWTYPE vt ){ w = gtk_button_new_with_label( "from map mins/maxs" ); gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, FALSE, 2 ); g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( size_mm_callback ), - ( gpointer ) this ); + ( gpointer ) this ); gtk_widget_set_tooltip_text( w, "Set the size of the image using the mapcoordsmins and mapcoordsmaxs keys of the worldspawn entity" ); gtk_widget_show( w ); } @@ -313,17 +313,17 @@ void InitBackgroundDialog(){ CBackgroundDialogPage *pPage; pDialogWnd = gtk_dialog_new_with_buttons( "Background Images", - GTK_WINDOW( g_pMainWidget ), - (GtkDialogFlags)( GTK_DIALOG_DESTROY_WITH_PARENT ), + GTK_WINDOW( g_pMainWidget ), + (GtkDialogFlags)( GTK_DIALOG_DESTROY_WITH_PARENT ), // TODO dialog with no buttons - // GTK_STOCK_CLOSE, - // GTK_RESPONSE_CLOSE, - NULL ); + // GTK_STOCK_CLOSE, + // GTK_RESPONSE_CLOSE, + NULL ); g_signal_connect( G_OBJECT( pDialogWnd ), "delete_event", - G_CALLBACK( close_callback ), NULL ); + G_CALLBACK( close_callback ), NULL ); g_signal_connect( G_OBJECT( pDialogWnd ), "response", - G_CALLBACK( response_callback ), NULL ); -// g_signal_connect( G_OBJECT (pDialogWnd), "expose_event", G_CALLBACK( ci_expose ), NULL ); + G_CALLBACK( response_callback ), NULL ); +// g_signal_connect( G_OBJECT (pDialogWnd), "expose_event", G_CALLBACK( ci_expose ), NULL ); pNotebook = gtk_notebook_new(); pPage = new CBackgroundDialogPage( XY ); diff --git a/contrib/bkgrnd2d/plugin.cpp b/contrib/bkgrnd2d/plugin.cpp index 35fb0720..29d0deba 100644 --- a/contrib/bkgrnd2d/plugin.cpp +++ b/contrib/bkgrnd2d/plugin.cpp @@ -80,12 +80,11 @@ static const char *PLUGIN_NAME = "2d window background plugin"; //backwards for some reason static const char *PLUGIN_COMMANDS = CMD_ABOUT ";" - CMD_SEP ";" - CMD_CONFIG -; + CMD_SEP ";" + CMD_CONFIG; static const char *PLUGIN_ABOUT = "2d window background v0.25\n\n" - "By reyalP (hellsownpuppy@yahoo.com)"; + "By reyalP (hellsownpuppy@yahoo.com)"; @@ -139,23 +138,23 @@ struct toolbar_button_info_s toolbar_buttons[NUM_TOOLBAR_BUTTONS] = class Bkgrnd2dButton : public IToolbarButton { public: -const toolbar_button_info_s *bi; -virtual const char* getImage() const { - return bi->image; -} -virtual const char* getText() const { - return bi->text; -} -virtual const char* getTooltip() const { - return bi->tip; -} -virtual void activate() const { - bi->func(); - return ; -} -virtual EType getType() const { - return bi->type; -} + const toolbar_button_info_s *bi; + virtual const char* getImage() const { + return bi->image; + } + virtual const char* getText() const { + return bi->text; + } + virtual const char* getTooltip() const { + return bi->tip; + } + virtual void activate() const { + bi->func(); + return ; + } + virtual EType getType() const { + return bi->type; + } }; Bkgrnd2dButton g_bkgrnd2dbuttons[NUM_TOOLBAR_BUTTONS]; diff --git a/contrib/bkgrnd2d/plugin.h b/contrib/bkgrnd2d/plugin.h index 13ca7378..cd548196 100644 --- a/contrib/bkgrnd2d/plugin.h +++ b/contrib/bkgrnd2d/plugin.h @@ -64,12 +64,12 @@ class CSynapseClientBkgrnd2d : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); -const char* GetName(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); + const char* GetName(); -CSynapseClientBkgrnd2d() { } -virtual ~CSynapseClientBkgrnd2d() { } + CSynapseClientBkgrnd2d() { } + virtual ~CSynapseClientBkgrnd2d() { } }; #define MSG_PREFIX "bkgrnd2d: " #define MSG_WARN "bkgrnd2d WARNING: " diff --git a/contrib/bobtoolz/CPortals.h b/contrib/bobtoolz/CPortals.h index fc555531..3633542b 100644 --- a/contrib/bobtoolz/CPortals.h +++ b/contrib/bobtoolz/CPortals.h @@ -19,29 +19,29 @@ class CBspPoint { public: -float p[3]; + float p[3]; }; class CBspPortal { public: -CBspPortal(); -~CBspPortal(); + CBspPortal(); + ~CBspPortal(); -unsigned point_count; -CBspPoint *point; -bool Build( char *def, unsigned int pointCnt, bool bInverse ); + unsigned point_count; + CBspPoint *point; + bool Build( char *def, unsigned int pointCnt, bool bInverse ); }; class CBspNode { public: -CBspPortal *portal; -unsigned int portal_count; + CBspPortal *portal; + unsigned int portal_count; -bool AddPortal( char* def, unsigned int pointCnt, bool bInverse ); -unsigned int portal_next; -CBspNode(); -~CBspNode(); + bool AddPortal( char* def, unsigned int pointCnt, bool bInverse ); + unsigned int portal_next; + CBspNode(); + ~CBspNode(); }; @@ -50,14 +50,14 @@ CBspNode(); class CPortals { public: -CPortals(); -~CPortals(); + CPortals(); + ~CPortals(); -void Load(); // use filename in fn -void Purge(); + void Load(); // use filename in fn + void Purge(); -char fn[NAME_MAX]; -CBspNode *node; + char fn[NAME_MAX]; + CBspNode *node; -unsigned int node_count; + unsigned int node_count; }; diff --git a/contrib/bobtoolz/DBobView.h b/contrib/bobtoolz/DBobView.h index 05c8ad29..e2a94003 100644 --- a/contrib/bobtoolz/DBobView.h +++ b/contrib/bobtoolz/DBobView.h @@ -41,58 +41,58 @@ class Shader; class DBobView : public Renderable, public OpenGLRenderable, public Entity::Observer { -Shader* m_shader_line; -Shader* m_shader_box; + Shader* m_shader_line; + Shader* m_shader_box; public: -DBobView(); -virtual ~DBobView(); + DBobView(); + virtual ~DBobView(); protected: -vec3_t* path; + vec3_t* path; public: -bool m_bShowExtra; -int boundingShow; -DListener* eyes; -float fVarGravity; -float fMultiplier; -int nPathCount; + bool m_bShowExtra; + int boundingShow; + DListener* eyes; + float fVarGravity; + float fMultiplier; + int nPathCount; -Entity* trigger; -Entity* target; + Entity* trigger; + Entity* target; -bool UpdatePath(); -char entTarget[256]; -char entTrigger[256]; -void Begin( const char*, const char*, float, int, float, bool, bool ); -bool CalculateTrajectory( vec3_t, vec3_t, float, int, float ); + bool UpdatePath(); + char entTarget[256]; + char entTrigger[256]; + void Begin( const char*, const char*, float, int, float, bool, bool ); + bool CalculateTrajectory( vec3_t, vec3_t, float, int, float ); -void SetPath( vec3_t* pPath ); + void SetPath( vec3_t* pPath ); -void render( RenderStateFlags state ) const; -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + void render( RenderStateFlags state ) const; + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; -void constructShaders(); -void destroyShaders(); + void constructShaders(); + void destroyShaders(); -void valueChanged( const char* value ){ - UpdatePath(); -} -typedef MemberCaller1 ValueChangedCaller; -void insert( const char* key, EntityKeyValue& value ){ - value.attach( ValueChangedCaller( *this ) ); -} -void erase( const char* key, EntityKeyValue& value ){ - value.detach( ValueChangedCaller( *this ) ); -} -void clear(){ - if ( trigger != 0 ) { - trigger->detach( *this ); - target->detach( *this ); - trigger = 0; - target = 0; + void valueChanged( const char* value ){ + UpdatePath(); + } + typedef MemberCaller1 ValueChangedCaller; + void insert( const char* key, EntityKeyValue& value ){ + value.attach( ValueChangedCaller( *this ) ); + } + void erase( const char* key, EntityKeyValue& value ){ + value.detach( ValueChangedCaller( *this ) ); + } + void clear(){ + if ( trigger != 0 ) { + trigger->detach( *this ); + target->detach( *this ); + trigger = 0; + target = 0; + } } -} }; class Entity; diff --git a/contrib/bobtoolz/DBrush.cpp b/contrib/bobtoolz/DBrush.cpp index 89d80bbb..9cb9d10a 100644 --- a/contrib/bobtoolz/DBrush.cpp +++ b/contrib/bobtoolz/DBrush.cpp @@ -243,7 +243,7 @@ int DBrush::RemoveRedundantPlanes(){ if ( pointList.size() == 0 ) { // if points may not have been built, build them /* if(BuildPoints() == 0) // just let the planes die if they are all bad - return cnt;*/ + return cnt;*/ BuildPoints(); } @@ -704,13 +704,13 @@ void DBrush::SaveToFile( FILE *pFile ){ char buffer[512]; sprintf( buffer, "( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) %s %.0f %.0f %f %f %.0f 0 0 0\n", - ( *pp )->points[0][0], ( *pp )->points[0][1], ( *pp )->points[0][2], - ( *pp )->points[1][0], ( *pp )->points[1][1], ( *pp )->points[1][2], - ( *pp )->points[2][0], ( *pp )->points[2][1], ( *pp )->points[2][2], - ( *pp )->m_shader.c_str(), - ( *pp )->texInfo.m_texdef.shift[0], ( *pp )->texInfo.m_texdef.shift[1], - ( *pp )->texInfo.m_texdef.scale[0], ( *pp )->texInfo.m_texdef.scale[0], - ( *pp )->texInfo.m_texdef.rotate ); + ( *pp )->points[0][0], ( *pp )->points[0][1], ( *pp )->points[0][2], + ( *pp )->points[1][0], ( *pp )->points[1][1], ( *pp )->points[1][2], + ( *pp )->points[2][0], ( *pp )->points[2][1], ( *pp )->points[2][2], + ( *pp )->m_shader.c_str(), + ( *pp )->texInfo.m_texdef.shift[0], ( *pp )->texInfo.m_texdef.shift[1], + ( *pp )->texInfo.m_texdef.scale[0], ( *pp )->texInfo.m_texdef.scale[0], + ( *pp )->texInfo.m_texdef.rotate ); fprintf( pFile, "%s", buffer ); } @@ -740,7 +740,7 @@ void DBrush::RotateAboutCentre( vec3_t vRotation ){ } bool DBrush::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ if ( textureName ) { bool changed = false; for ( std::list::const_iterator resetPlane = faceList.begin(); resetPlane != faceList.end(); resetPlane++ ) diff --git a/contrib/bobtoolz/DBrush.h b/contrib/bobtoolz/DBrush.h index b5e343eb..5fb32848 100644 --- a/contrib/bobtoolz/DBrush.h +++ b/contrib/bobtoolz/DBrush.h @@ -51,63 +51,63 @@ class Instance; class DBrush { public: -DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); -void SaveToFile( FILE* pFile ); + DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); + void SaveToFile( FILE* pFile ); -void Rotate( vec3_t vOrigin, vec3_t vRotation ); -void RotateAboutCentre( vec3_t vRotation ); + void Rotate( vec3_t vOrigin, vec3_t vRotation ); + void RotateAboutCentre( vec3_t vRotation ); -DPlane* HasPlaneInverted( DPlane* chkPlane ); -DPlane* HasPlane( DPlane* chkPlane ); -DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); + DPlane* HasPlaneInverted( DPlane* chkPlane ); + DPlane* HasPlane( DPlane* chkPlane ); + DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); -bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); -bool IsDetail(); -bool HasTexture( const char* textureName ); -bool IntersectsWith( DBrush *chkBrush ); -bool IntersectsWith( DPlane* p1, DPlane* p2, vec3_t v ); -bool IsCutByPlane( DPlane* cuttingPlane ); -bool GetBounds( vec3_t min, vec3_t max ); -bool HasPoint( vec3_t pnt ); -bool BBoxCollision( DBrush* chkBrush ); -bool BBoxTouch( DBrush* chkBrush ); + bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); + bool IsDetail(); + bool HasTexture( const char* textureName ); + bool IntersectsWith( DBrush *chkBrush ); + bool IntersectsWith( DPlane* p1, DPlane* p2, vec3_t v ); + bool IsCutByPlane( DPlane* cuttingPlane ); + bool GetBounds( vec3_t min, vec3_t max ); + bool HasPoint( vec3_t pnt ); + bool BBoxCollision( DBrush* chkBrush ); + bool BBoxTouch( DBrush* chkBrush ); -int BuildPoints(); -void BuildBounds(); -void BuildFromWinding( DWinding* w ); -scene::Node* BuildInRadiant( bool allowDestruction, int* changeCnt, scene::Node* entity = NULL ); + int BuildPoints(); + void BuildBounds(); + void BuildFromWinding( DWinding* w ); + scene::Node* BuildInRadiant( bool allowDestruction, int* changeCnt, scene::Node* entity = NULL ); -void ResetChecks( std::list* exclusionList ); + void ResetChecks( std::list* exclusionList ); -void ClearFaces(); -void ClearPoints(); + void ClearFaces(); + void ClearPoints(); -int RemoveRedundantPlanes( void ); -void RemovePlane( DPlane* plane ); -int PointPosition( vec3_t pnt ); + int RemoveRedundantPlanes( void ); + void RemovePlane( DPlane* plane ); + int PointPosition( vec3_t pnt ); -void CutByPlane( DPlane* cutPlane, DBrush** newBrush1, DBrush** newBrush2 ); + void CutByPlane( DPlane* cutPlane, DBrush** newBrush1, DBrush** newBrush2 ); -void LoadFromBrush( scene::Instance& brush, bool textured ); -void AddPoint( vec3_t pnt ); + void LoadFromBrush( scene::Instance& brush, bool textured ); + void AddPoint( vec3_t pnt ); -DPlane* FindPlaneWithClosestNormal( vec_t* normal ); -int FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ); + DPlane* FindPlaneWithClosestNormal( vec_t* normal ); + int FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ); -DBrush( int ID = -1 ); -virtual ~DBrush(); + DBrush( int ID = -1 ); + virtual ~DBrush(); -bool operator==( DBrush* other ); + bool operator==( DBrush* other ); // members -scene::Node* QER_entity; -scene::Node* QER_brush; -std::list faceList; -std::list pointList; -int m_nBrushID; -vec3_t bbox_min, bbox_max; -bool bBoundsBuilt; + scene::Node* QER_entity; + scene::Node* QER_brush; + std::list faceList; + std::list pointList; + int m_nBrushID; + vec3_t bbox_min, bbox_max; + bool bBoundsBuilt; }; //typedef CList DBrushList; diff --git a/contrib/bobtoolz/DEPair.h b/contrib/bobtoolz/DEPair.h index 3b5ca3ae..cb027a09 100644 --- a/contrib/bobtoolz/DEPair.h +++ b/contrib/bobtoolz/DEPair.h @@ -33,13 +33,13 @@ class DEPair { public: -DEPair(); -virtual ~DEPair(); + DEPair(); + virtual ~DEPair(); -void Build( const char* pKey, const char* pValue ); + void Build( const char* pKey, const char* pValue ); -Str key; -Str value; + Str key; + Str value; }; //typedef CList DEPairList; diff --git a/contrib/bobtoolz/DEntity.cpp b/contrib/bobtoolz/DEntity.cpp index 77989327..aa94d7f5 100644 --- a/contrib/bobtoolz/DEntity.cpp +++ b/contrib/bobtoolz/DEntity.cpp @@ -218,15 +218,15 @@ DBrush* DEntity::GetBrushForID( int ID ){ template class BrushSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -BrushSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - if ( Node_isBrush( instance.path().top() ) ) { - m_functor( instance ); + BrushSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + if ( Node_isBrush( instance.path().top() ) ) { + m_functor( instance ); + } } -} }; template @@ -251,15 +251,15 @@ void DEntity::LoadSelectedBrushes(){ template class PatchSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -PatchSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - if ( Node_isPatch( instance.path().top() ) ) { - m_functor( instance ); + PatchSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + if ( Node_isPatch( instance.path().top() ) ) { + m_functor( instance ); + } } -} }; template @@ -375,29 +375,29 @@ bool DEntity::LoadFromEntity( scene::Node& ent, bool bLoadPatches ) { if ( Node_getTraversable( ent ) ) { class load_brushes_t : public scene::Traversable::Walker { - DEntity* m_entity; - mutable int m_count; -public: - load_brushes_t( DEntity* entity ) - : m_entity( entity ), m_count( 0 ){ - } - bool pre( scene::Node& node ) const { - scene::Path path( NodeReference( GlobalSceneGraph().root() ) ); - path.push( NodeReference( *m_entity->QER_Entity ) ); - path.push( NodeReference( node ) ); - scene::Instance* instance = GlobalSceneGraph().find( path ); - ASSERT_MESSAGE( instance != 0, "" ); + DEntity* m_entity; + mutable int m_count; + public: + load_brushes_t( DEntity* entity ) + : m_entity( entity ), m_count( 0 ){ + } + bool pre( scene::Node& node ) const { + scene::Path path( NodeReference( GlobalSceneGraph().root() ) ); + path.push( NodeReference( *m_entity->QER_Entity ) ); + path.push( NodeReference( node ) ); + scene::Instance* instance = GlobalSceneGraph().find( path ); + ASSERT_MESSAGE( instance != 0, "" ); - if ( Node_isPatch( node ) ) { - DPatch* loadPatch = m_entity->NewPatch(); - loadPatch->LoadFromPatch( *instance ); + if ( Node_isPatch( node ) ) { + DPatch* loadPatch = m_entity->NewPatch(); + loadPatch->LoadFromPatch( *instance ); + } + else if ( Node_isBrush( node ) ) { + DBrush* loadBrush = m_entity->NewBrush( m_count++ ); + loadBrush->LoadFromBrush( *instance, true ); + } + return false; } - else if ( Node_isBrush( node ) ) { - DBrush* loadBrush = m_entity->NewBrush( m_count++ ); - loadBrush->LoadFromBrush( *instance, true ); - } - return false; - } } load_brushes( this ); Node_getTraversable( ent )->traverse( load_brushes ); @@ -543,19 +543,19 @@ void DEntity::AddEPair( const char *key, const char *value ) { void DEntity::LoadEPairList( Entity *epl ){ class load_epairs_t : public Entity::Visitor { - DEntity* m_entity; -public: - load_epairs_t( DEntity* entity ) - : m_entity( entity ){ - } - void visit( const char* key, const char* value ){ - if ( strcmp( key, "classname" ) == 0 ) { - m_entity->SetClassname( value ); + DEntity* m_entity; + public: + load_epairs_t( DEntity* entity ) + : m_entity( entity ){ } - else{ - m_entity->AddEPair( key, value ); + void visit( const char* key, const char* value ){ + if ( strcmp( key, "classname" ) == 0 ) { + m_entity->SetClassname( value ); + } + else{ + m_entity->AddEPair( key, value ); + } } - } } load_epairs( this ); @@ -563,13 +563,13 @@ public: } bool DEntity::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ){ + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ){ bool reset = false; for ( std::list::const_iterator resetBrush = brushList.begin(); resetBrush != brushList.end(); resetBrush++ ) { bool tmp = ( *resetBrush )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation ); + bResetTextureName, bResetScale, bResetShift, bResetRotation ); if ( tmp ) { reset = true; diff --git a/contrib/bobtoolz/DEntity.h b/contrib/bobtoolz/DEntity.h index 415442a2..78685df0 100644 --- a/contrib/bobtoolz/DEntity.h +++ b/contrib/bobtoolz/DEntity.h @@ -47,79 +47,79 @@ class _QERFaceData; class DEntity { public: -void RemoveFromRadiant(); -scene::Node* QER_Entity; -int m_nID; + void RemoveFromRadiant(); + scene::Node* QER_Entity; + int m_nID; // Constrcution/Destruction -DEntity( const char* classname = "worldspawn", int ID = -1 ); // sets classname -virtual ~DEntity(); + DEntity( const char* classname = "worldspawn", int ID = -1 ); // sets classname + virtual ~DEntity(); // --------------------------------------------- // epair functions........ -void LoadEPairList( Entity* epl ); -void AddEPair( const char* key, const char* value ); -void ClearEPairs(); -DEPair* FindEPairByKey( const char* keyname ); + void LoadEPairList( Entity* epl ); + void AddEPair( const char* key, const char* value ); + void ClearEPairs(); + DEPair* FindEPairByKey( const char* keyname ); // --------------------------------------------- // random functions........ -bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ); -void SaveToFile( FILE* pFile ); -void SetClassname( const char* classname ); -int GetIDMax(); + bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ); + void SaveToFile( FILE* pFile ); + void SetClassname( const char* classname ); + int GetIDMax(); -void BuildInRadiant( bool allowDestruction ); -void ResetChecks( std::list* exclusionList ); -void RemoveNonCheckBrushes( std::list* exclusionList, bool useDetail ); + void BuildInRadiant( bool allowDestruction ); + void ResetChecks( std::list* exclusionList ); + void RemoveNonCheckBrushes( std::list* exclusionList, bool useDetail ); -DPlane* AddFaceToBrush( vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID ); // slow, try not to use much -int GetBrushCount( void ); -DBrush* FindBrushByPointer( scene::Node& brush ); + DPlane* AddFaceToBrush( vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID ); // slow, try not to use much + int GetBrushCount( void ); + DBrush* FindBrushByPointer( scene::Node& brush ); // --------------------------------------------- // bool list functions -void SelectBrushes( bool* selectList ); -bool* BuildDuplicateList(); -bool* BuildIntersectList(); + void SelectBrushes( bool* selectList ); + bool* BuildDuplicateList(); + bool* BuildIntersectList(); // --------------------------------------------- // brush operations -void ClearBrushes(); // clears brush list and frees memory for brushes + void ClearBrushes(); // clears brush list and frees memory for brushes -DBrush* GetBrushForID( int ID ); -DBrush* NewBrush( int ID = -1 ); + DBrush* GetBrushForID( int ID ); + DBrush* NewBrush( int ID = -1 ); // --------------------------------------------- // patch operations -void ClearPatches(); + void ClearPatches(); -DPatch* NewPatch(); + DPatch* NewPatch(); // --------------------------------------------- // vars -std::list epairList; -std::list brushList; + std::list epairList; + std::list brushList; // new patches, wahey!!! -std::list patchList; -Str m_Classname; + std::list patchList; + Str m_Classname; // --------------------------------------------- -int FixBrushes(); + int FixBrushes(); -bool LoadFromEntity( scene::Node& ent, bool bLoadPatches = false ); -void LoadSelectedBrushes(); -void LoadSelectedPatches(); + bool LoadFromEntity( scene::Node& ent, bool bLoadPatches = false ); + void LoadSelectedBrushes(); + void LoadSelectedPatches(); -bool LoadFromPrt( char* filename ); + bool LoadFromPrt( char* filename ); // --------------------------------------------- -void SpawnString( const char* key, const char* defaultstring, const char** out ); -void SpawnInt( const char* key, const char* defaultstring, int* out ); -void SpawnFloat( const char* key, const char* defaultstring, float* out ); -void SpawnVector( const char* key, const char* defaultstring, vec_t* out ); + void SpawnString( const char* key, const char* defaultstring, const char** out ); + void SpawnInt( const char* key, const char* defaultstring, int* out ); + void SpawnFloat( const char* key, const char* defaultstring, float* out ); + void SpawnVector( const char* key, const char* defaultstring, vec_t* out ); }; #endif // !defined(AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/DMap.cpp b/contrib/bobtoolz/DMap.cpp index 18edc3b1..27e1f3b8 100644 --- a/contrib/bobtoolz/DMap.cpp +++ b/contrib/bobtoolz/DMap.cpp @@ -116,19 +116,19 @@ void DMap::LoadAll( bool bLoadPatches ){ class load_entities_t : public scene::Traversable::Walker { - DMap* m_map; - bool m_bLoadPatches; -public: - load_entities_t( DMap* map, bool bLoadPatches ) - : m_map( map ), m_bLoadPatches( bLoadPatches ){ - } - bool pre( scene::Node& node ) const { - if ( Node_isEntity( node ) ) { - DEntity* loadEntity = m_map->AddEntity( "", 0 ); - loadEntity->LoadFromEntity( node, m_bLoadPatches ); + DMap* m_map; + bool m_bLoadPatches; + public: + load_entities_t( DMap* map, bool bLoadPatches ) + : m_map( map ), m_bLoadPatches( bLoadPatches ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isEntity( node ) ) { + DEntity* loadEntity = m_map->AddEntity( "", 0 ); + loadEntity->LoadFromEntity( node, m_bLoadPatches ); + } + return false; } - return false; - } } load_entities( this, bLoadPatches ); Node_getTraversable( GlobalSceneGraph().root() )->traverse( load_entities ); @@ -145,17 +145,17 @@ int DMap::FixBrushes(){ } void DMap::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ for ( std::list::const_iterator texEntity = entityList.begin(); texEntity != entityList.end(); texEntity++ ) { if ( string_equal_nocase( "worldspawn", ( *texEntity )->m_Classname ) ) { ( *texEntity )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, true ); + bResetTextureName, bResetScale, bResetShift, bResetRotation, true ); } else { if ( ( *texEntity )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, false ) ) { + bResetTextureName, bResetScale, bResetShift, bResetRotation, false ) ) { RebuildEntity( *texEntity ); } } diff --git a/contrib/bobtoolz/DMap.h b/contrib/bobtoolz/DMap.h index f527d04d..2f122c98 100644 --- a/contrib/bobtoolz/DMap.h +++ b/contrib/bobtoolz/DMap.h @@ -35,24 +35,24 @@ class DEntity; class DMap { public: -static void RebuildEntity( DEntity* ent ); + static void RebuildEntity( DEntity* ent ); -void ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); -void LoadAll( bool bLoadPatches = false ); -void BuildInRadiant( bool bAllowDestruction ); -int m_nNextEntity; -DEntity* GetWorldSpawn(); -void ClearEntities(); + void ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); + void LoadAll( bool bLoadPatches = false ); + void BuildInRadiant( bool bAllowDestruction ); + int m_nNextEntity; + DEntity* GetWorldSpawn(); + void ClearEntities(); -DEntity* GetEntityForID( int ID ); -DEntity* AddEntity( const char* classname = "worldspawn", int ID = -1 ); + DEntity* GetEntityForID( int ID ); + DEntity* AddEntity( const char* classname = "worldspawn", int ID = -1 ); -std::list entityList; + std::list entityList; -DMap(); -virtual ~DMap(); + DMap(); + virtual ~DMap(); -int FixBrushes(); + int FixBrushes(); }; #endif // !defined(AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_) diff --git a/contrib/bobtoolz/DPatch.cpp b/contrib/bobtoolz/DPatch.cpp index 7abc7001..76a85db4 100644 --- a/contrib/bobtoolz/DPatch.cpp +++ b/contrib/bobtoolz/DPatch.cpp @@ -107,22 +107,22 @@ void DPatch::BuildInRadiant( scene::Node* entity ){ CopyDrawVert( &points[x][y], &pm->ctrl[x][y] ); /* if(entity) - { - // strcpy(pm->d_texture->name, texture); + { + // strcpy(pm->d_texture->name, texture); - brush_t* brush = (brush_t*)g_FuncTable.m_pfnCreateBrushHandle(); - brush->patchBrush = true; - brush->pPatch = pm; + brush_t* brush = (brush_t*)g_FuncTable.m_pfnCreateBrushHandle(); + brush->patchBrush = true; + brush->pPatch = pm; - pm->pSymbiot = brush; - pm->bSelected = false; - pm->bOverlay = false; // bleh, f*cks up, just have to wait for a proper function - pm->bDirty = true; // or get my own patch out.... - pm->nListID = -1; + pm->pSymbiot = brush; + pm->bSelected = false; + pm->bOverlay = false; // bleh, f*cks up, just have to wait for a proper function + pm->bDirty = true; // or get my own patch out.... + pm->nListID = -1; - g_FuncTable.m_pfnCommitBrushHandleToEntity(brush, entity); - } - else*/ // patch to entity just plain dont work atm + g_FuncTable.m_pfnCommitBrushHandleToEntity(brush, entity); + } + else*/ // patch to entity just plain dont work atm if ( entity ) { g_FuncTable.m_pfnCommitPatchHandleToEntity( nIndex, pm, texture, entity ); @@ -189,7 +189,7 @@ bool DPatch::ResetTextures( const char *oldTextureName, const char *newTextureNa } void Build1dArray( vec3_t* array, drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT], - int startX, int startY, int number, bool horizontal, bool inverse ){ + int startX, int startY, int number, bool horizontal, bool inverse ){ int x = startX, y = startY, i, step; if ( inverse ) { diff --git a/contrib/bobtoolz/DPatch.h b/contrib/bobtoolz/DPatch.h index 8808daeb..2319515d 100644 --- a/contrib/bobtoolz/DPatch.h +++ b/contrib/bobtoolz/DPatch.h @@ -55,26 +55,26 @@ class Instance; class DPatch { public: -std::list SplitRows(); -std::list SplitCols(); -std::list Split(); -void Transpose(); + std::list SplitRows(); + std::list SplitCols(); + std::list Split(); + void Transpose(); //DPatch* TransposePatch(DPatch* p1); //void DebugPrint(); -void Invert(); -DPatch* MergePatches( patch_merge_t merge_info, DPatch* p1, DPatch* p2 ); -patch_merge_t IsMergable( DPatch* other ); -bool ResetTextures( const char *oldTextureName, const char *newTextureName ); -scene::Node* QER_entity; -scene::Node* QER_brush; -void LoadFromPatch( scene::Instance& patch ); -void BuildInRadiant( scene::Node* entity = NULL ); -void SetTexture( const char* textureName ); -char texture[256]; -int width, height; -drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; -DPatch(); -virtual ~DPatch(); + void Invert(); + DPatch* MergePatches( patch_merge_t merge_info, DPatch* p1, DPatch* p2 ); + patch_merge_t IsMergable( DPatch* other ); + bool ResetTextures( const char *oldTextureName, const char *newTextureName ); + scene::Node* QER_entity; + scene::Node* QER_brush; + void LoadFromPatch( scene::Instance& patch ); + void BuildInRadiant( scene::Node* entity = NULL ); + void SetTexture( const char* textureName ); + char texture[256]; + int width, height; + drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; + DPatch(); + virtual ~DPatch(); }; diff --git a/contrib/bobtoolz/DPlane.h b/contrib/bobtoolz/DPlane.h index 6e840cdb..bf0be941 100644 --- a/contrib/bobtoolz/DPlane.h +++ b/contrib/bobtoolz/DPlane.h @@ -43,31 +43,31 @@ class DWinding; class DPlane { public: -DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); -void ScaleTexture(); -DWinding* BaseWindingForPlane(); + DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); + void ScaleTexture(); + DWinding* BaseWindingForPlane(); -void Rebuild(); + void Rebuild(); -bool AddToBrush( scene::Node& brush ); -bool operator !=( DPlane& other ); -bool operator ==( DPlane& other ); + bool AddToBrush( scene::Node& brush ); + bool operator !=( DPlane& other ); + bool operator ==( DPlane& other ); -bool IsRedundant( std::list& pointList ); -bool PlaneIntersection( DPlane* pl1, DPlane* pl2, vec3_t out );; + bool IsRedundant( std::list& pointList ); + bool PlaneIntersection( DPlane* pl1, DPlane* pl2, vec3_t out );; -vec_t DistanceToPoint( vec3_t pnt ); + vec_t DistanceToPoint( vec3_t pnt ); -DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); -DPlane() { } -virtual ~DPlane(); + DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); + DPlane() { } + virtual ~DPlane(); -bool m_bChkOk; -_QERFaceData texInfo; -CopiedString m_shader; -vec3_t points[3]; // djbob:do we really need these any more? -vec3_t normal; -float _d; + bool m_bChkOk; + _QERFaceData texInfo; + CopiedString m_shader; + vec3_t points[3]; // djbob:do we really need these any more? + vec3_t normal; + float _d; }; //typedef CList DPlaneList; diff --git a/contrib/bobtoolz/DPoint.h b/contrib/bobtoolz/DPoint.h index f7b68396..487c423a 100644 --- a/contrib/bobtoolz/DPoint.h +++ b/contrib/bobtoolz/DPoint.h @@ -33,13 +33,13 @@ class DPoint { public: -DPoint(); -virtual ~DPoint(); + DPoint(); + virtual ~DPoint(); -bool operator ==( vec3_t other ); + bool operator ==( vec3_t other ); -vec3_t _pnt; -unsigned char m_uData; + vec3_t _pnt; + unsigned char m_uData; }; //typedef CList DPointList; diff --git a/contrib/bobtoolz/DShape.h b/contrib/bobtoolz/DShape.h index 1f6c91fc..70c544d9 100644 --- a/contrib/bobtoolz/DShape.h +++ b/contrib/bobtoolz/DShape.h @@ -42,22 +42,22 @@ extern bool bFacesAll[]; class DShape { public: -bool BuildPit( vec3_t min, vec3_t max ); -void BuildBorderedPrism( vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop ); -void BuildInversePrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); -void BuildRegularPrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); + bool BuildPit( vec3_t min, vec3_t max ); + void BuildBorderedPrism( vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop ); + void BuildInversePrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); + void BuildRegularPrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); -int m_nNextBrush; -static DBrush* GetBoundingCube_Ext( vec3_t min, vec3_t max, const char* textureName, bool* bUseFaces = bFacesAll, bool detail = false ); + int m_nNextBrush; + static DBrush* GetBoundingCube_Ext( vec3_t min, vec3_t max, const char* textureName, bool* bUseFaces = bFacesAll, bool detail = false ); -DShape(); -virtual ~DShape(); + DShape(); + virtual ~DShape(); -void Commit(); + void Commit(); private: -DBrush* GetBoundingCube( vec3_t min, vec3_t max, const char* textureName, DEntity* ent = NULL, bool* bUseFaces = bFacesAll ); + DBrush* GetBoundingCube( vec3_t min, vec3_t max, const char* textureName, DEntity* ent = NULL, bool* bUseFaces = bFacesAll ); -DMap m_Container; + DMap m_Container; }; #endif // !defined(AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_) diff --git a/contrib/bobtoolz/DTrainDrawer.cpp b/contrib/bobtoolz/DTrainDrawer.cpp index b31bb777..3566e502 100644 --- a/contrib/bobtoolz/DTrainDrawer.cpp +++ b/contrib/bobtoolz/DTrainDrawer.cpp @@ -168,66 +168,66 @@ void AddSplineControl( const char* control, splinePoint_t* pSP ) { class EntityBuildPaths { -mutable DEntity e; -DTrainDrawer& drawer; + mutable DEntity e; + DTrainDrawer& drawer; public: -EntityBuildPaths( DTrainDrawer& drawer ) : drawer( drawer ){ -} -void operator()( scene::Instance& instance ) const { - e.ClearEPairs(); - e.LoadEPairList( Node_getEntity( instance.path().top() ) ); + EntityBuildPaths( DTrainDrawer& drawer ) : drawer( drawer ){ + } + void operator()( scene::Instance& instance ) const { + e.ClearEPairs(); + e.LoadEPairList( Node_getEntity( instance.path().top() ) ); - const char* classname = e.m_Classname.GetBuffer(); - const char* target; - const char* control; - const char* targetname; - vec3_t vOrigin; + const char* classname = e.m_Classname.GetBuffer(); + const char* target; + const char* control; + const char* targetname; + vec3_t vOrigin; - e.SpawnString( "targetname", NULL, &targetname ); - e.SpawnVector( "origin", "0 0 0", vOrigin ); + e.SpawnString( "targetname", NULL, &targetname ); + e.SpawnVector( "origin", "0 0 0", vOrigin ); - if ( !strcmp( classname, "info_train_spline_main" ) ) { - if ( !targetname ) { - globalWarningStream() << "info_train_spline_main with no targetname"; - return; - } + if ( !strcmp( classname, "info_train_spline_main" ) ) { + if ( !targetname ) { + globalWarningStream() << "info_train_spline_main with no targetname"; + return; + } - e.SpawnString( "target", NULL, &target ); + e.SpawnString( "target", NULL, &target ); - if ( !target ) { - drawer.AddControlPoint( targetname, vOrigin ); - } - else { - splinePoint_t* pSP = drawer.AddSplinePoint( targetname, target, vOrigin ); + if ( !target ) { + drawer.AddControlPoint( targetname, vOrigin ); + } + else { + splinePoint_t* pSP = drawer.AddSplinePoint( targetname, target, vOrigin ); - e.SpawnString( "control", NULL, &control ); - - if ( control ) { - AddSplineControl( control, pSP ); - - for ( int j = 2;; j++ ) { - char buffer[32]; - sprintf( buffer, "control%i", j ); - - e.SpawnString( buffer, NULL, &control ); - if ( !control ) { - break; - } + e.SpawnString( "control", NULL, &control ); + if ( control ) { AddSplineControl( control, pSP ); + + for ( int j = 2;; j++ ) { + char buffer[32]; + sprintf( buffer, "control%i", j ); + + e.SpawnString( buffer, NULL, &control ); + if ( !control ) { + break; + } + + AddSplineControl( control, pSP ); + } } } } - } - else if ( !strcmp( classname, "info_train_spline_control" ) ) { - if ( !targetname ) { - globalWarningStream() << "info_train_spline_control with no targetname"; - return; - } + else if ( !strcmp( classname, "info_train_spline_control" ) ) { + if ( !targetname ) { + globalWarningStream() << "info_train_spline_control with no targetname"; + return; + } - drawer.AddControlPoint( targetname, vOrigin ); + drawer.AddControlPoint( targetname, vOrigin ); + } } -} }; void DTrainDrawer::BuildPaths() { diff --git a/contrib/bobtoolz/DTrainDrawer.h b/contrib/bobtoolz/DTrainDrawer.h index 2b79f674..8db73adf 100644 --- a/contrib/bobtoolz/DTrainDrawer.h +++ b/contrib/bobtoolz/DTrainDrawer.h @@ -59,30 +59,30 @@ typedef struct { class DTrainDrawer : public Renderable, public OpenGLRenderable { private: -std::list m_splineList; -std::list m_pointList; + std::list m_splineList; + std::list m_pointList; -bool m_bDisplay; -Shader* m_shader_wireframe; -Shader* m_shader_solid; + bool m_bDisplay; + Shader* m_shader_wireframe; + Shader* m_shader_solid; public: -DTrainDrawer(); -virtual ~DTrainDrawer( void ); + DTrainDrawer(); + virtual ~DTrainDrawer( void ); -void render( RenderStateFlags state ) const; -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + void render( RenderStateFlags state ) const; + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; -void constructShaders(); -void destroyShaders(); + void constructShaders(); + void destroyShaders(); -void ClearSplines(); -void ClearPoints(); -void BuildPaths(); -void AddControlPoint( const char* name, vec_t* origin ); -splinePoint_t* AddSplinePoint( const char* name, const char* target, vec_t* origin ); -controlPoint_t* FindControlPoint( const char* name ); + void ClearSplines(); + void ClearPoints(); + void BuildPaths(); + void AddControlPoint( const char* name, vec_t* origin ); + splinePoint_t* AddSplinePoint( const char* name, const char* target, vec_t* origin ); + controlPoint_t* FindControlPoint( const char* name ); }; #endif // !defined(AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/DTreePlanter.cpp b/contrib/bobtoolz/DTreePlanter.cpp index 5e61ea1e..354a23fb 100644 --- a/contrib/bobtoolz/DTreePlanter.cpp +++ b/contrib/bobtoolz/DTreePlanter.cpp @@ -170,33 +170,33 @@ bool DTreePlanter::FindDropPoint( vec3_t in, vec3_t out ) { class TreePlanterDropEntityIfSelected { -mutable DEntity ent; -DTreePlanter& planter; + mutable DEntity ent; + DTreePlanter& planter; public: -TreePlanterDropEntityIfSelected( DTreePlanter& planter ) : planter( planter ){ -} -void operator()( scene::Instance& instance ) const { - if ( !instance.isSelected() ) { - return; + TreePlanterDropEntityIfSelected( DTreePlanter& planter ) : planter( planter ){ } - ent.LoadFromEntity( instance.path().top() ); + void operator()( scene::Instance& instance ) const { + if ( !instance.isSelected() ) { + return; + } + ent.LoadFromEntity( instance.path().top() ); - DEPair* pEpair = ent.FindEPairByKey( "origin" ); - if ( !pEpair ) { - return; + DEPair* pEpair = ent.FindEPairByKey( "origin" ); + if ( !pEpair ) { + return; + } + + vec3_t vec, out; + sscanf( pEpair->value.GetBuffer(), "%f %f %f", &vec[0], &vec[1], &vec[2] ); + + planter.FindDropPoint( vec, out ); + + char buffer[256]; + sprintf( buffer, "%f %f %f", out[0], out[1], out[2] ); + ent.AddEPair( "origin", buffer ); + ent.RemoveFromRadiant(); + ent.BuildInRadiant( false ); } - - vec3_t vec, out; - sscanf( pEpair->value.GetBuffer(), "%f %f %f", &vec[0], &vec[1], &vec[2] ); - - planter.FindDropPoint( vec, out ); - - char buffer[256]; - sprintf( buffer, "%f %f %f", out[0], out[1], out[2] ); - ent.AddEPair( "origin", buffer ); - ent.RemoveFromRadiant(); - ent.BuildInRadiant( false ); -} }; void DTreePlanter::DropEntsToGround( void ) { @@ -241,35 +241,35 @@ void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { void DTreePlanter::SelectChain( void ) { /* char buffer[256]; - for(int i = 0; i < m_linkNum; i++) { - DEntity e("info_train_spline_main"); + for(int i = 0; i < m_linkNum; i++) { + DEntity e("info_train_spline_main"); - sprintf( buffer, "%s_pt%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); + sprintf( buffer, "%s_pt%i", m_linkName, i ); + e.AddEPair( "targetname", buffer ); - sprintf( buffer, "0 %i 0", i * 64 ); - e.AddEPair( "origin", buffer ); + sprintf( buffer, "0 %i 0", i * 64 ); + e.AddEPair( "origin", buffer ); - if(i != m_linkNum-1) { - sprintf( buffer, "%s_pt%i", m_linkName, i+1 ); - e.AddEPair( "target", buffer ); + if(i != m_linkNum-1) { + sprintf( buffer, "%s_pt%i", m_linkName, i+1 ); + e.AddEPair( "target", buffer ); - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "control", buffer ); - } + sprintf( buffer, "%s_ctl%i", m_linkName, i ); + e.AddEPair( "control", buffer ); + } - e.BuildInRadiant( false ); - } + e.BuildInRadiant( false ); + } - for(int i = 0; i < m_linkNum-1; i++) { - DEntity e("info_train_spline_control"); + for(int i = 0; i < m_linkNum-1; i++) { + DEntity e("info_train_spline_control"); - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); + sprintf( buffer, "%s_ctl%i", m_linkName, i ); + e.AddEPair( "targetname", buffer ); - sprintf( buffer, "0 %i 0", (i * 64) + 32); - e.AddEPair( "origin", buffer ); + sprintf( buffer, "0 %i 0", (i * 64) + 32); + e.AddEPair( "origin", buffer ); - e.BuildInRadiant( false ); - }*/ + e.BuildInRadiant( false ); + }*/ } diff --git a/contrib/bobtoolz/DTreePlanter.h b/contrib/bobtoolz/DTreePlanter.h index 536bed19..66c25884 100644 --- a/contrib/bobtoolz/DTreePlanter.h +++ b/contrib/bobtoolz/DTreePlanter.h @@ -38,180 +38,191 @@ typedef struct treeModel_s { #define MAX_TP_MODELS 256 class DTreePlanter { -MouseEventHandlerId m_mouseDown; -SignalHandlerId m_destroyed; + MouseEventHandlerId m_mouseDown; + SignalHandlerId m_destroyed; public: -SignalHandlerResult mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ); -typedef Member3 MouseDownCaller; -void destroyed(){ - m_mouseDown = MouseEventHandlerId(); - m_destroyed = SignalHandlerId(); -} -typedef Member DestroyedCaller; + SignalHandlerResult mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ); + typedef Member3 MouseDownCaller; + void destroyed(){ + m_mouseDown = MouseEventHandlerId(); + m_destroyed = SignalHandlerId(); + } + typedef Member DestroyedCaller; -DTreePlanter() { - m_numModels = 0; - m_offset = 0; - m_maxPitch = 0; - m_minPitch = 0; - m_maxYaw = 0; - m_minYaw = 0; - m_setAngles = false; - m_useScale = false; - m_autoLink = false; - m_linkNum = 0; + DTreePlanter() { + m_numModels = 0; + m_offset = 0; + m_maxPitch = 0; + m_minPitch = 0; + m_maxYaw = 0; + m_minYaw = 0; + m_setAngles = false; + m_useScale = false; + m_autoLink = false; + m_linkNum = 0; - m_world.LoadSelectedBrushes(); + m_world.LoadSelectedBrushes(); - char buffer[256]; - GetFilename( buffer, "bt/tp_ent.txt" ); + char buffer[256]; + GetFilename( buffer, "bt/tp_ent.txt" ); - FILE* file = fopen( buffer, "rb" ); - if ( file ) { - fseek( file, 0, SEEK_END ); - int len = ftell( file ); - fseek( file, 0, SEEK_SET ); + FILE* file = fopen( buffer, "rb" ); + if ( file ) { + fseek( file, 0, SEEK_END ); + int len = ftell( file ); + fseek( file, 0, SEEK_SET ); - if ( len ) { - char* buf = new char[len + 1]; - buf[len] = '\0'; - // parser will do the cleanup, dont delete. + if ( len ) { + char* buf = new char[len + 1]; + buf[len] = '\0'; + // parser will do the cleanup, dont delete. - fread( buf, len, 1, file ); + fread( buf, len, 1, file ); - CScriptParser parser; - parser.SetScript( buf ); + CScriptParser parser; + parser.SetScript( buf ); - ReadConfig( &parser ); + ReadConfig( &parser ); + } + + fclose( file ); } - fclose( file ); + m_mouseDown = GlobalRadiant().XYWindowMouseDown_connect( makeSignalHandler3( MouseDownCaller(), *this ) ); + m_destroyed = GlobalRadiant().XYWindowDestroyed_connect( makeSignalHandler( DestroyedCaller(), *this ) ); } - m_mouseDown = GlobalRadiant().XYWindowMouseDown_connect( makeSignalHandler3( MouseDownCaller(), *this ) ); - m_destroyed = GlobalRadiant().XYWindowDestroyed_connect( makeSignalHandler( DestroyedCaller(), *this ) ); -} - -virtual ~DTreePlanter(){ - if ( !m_mouseDown.isNull() ) { - GlobalRadiant().XYWindowMouseDown_disconnect( m_mouseDown ); + virtual ~DTreePlanter(){ + if ( !m_mouseDown.isNull() ) { + GlobalRadiant().XYWindowMouseDown_disconnect( m_mouseDown ); + } + if ( !m_destroyed.isNull() ) { + GlobalRadiant().XYWindowDestroyed_disconnect( m_destroyed ); + } } - if ( !m_destroyed.isNull() ) { - GlobalRadiant().XYWindowDestroyed_disconnect( m_destroyed ); - } -} #define MT( t ) string_equal_nocase( pToken, t ) #define GT pToken = pScriptParser->GetToken( true ) #define CT if ( !*pToken ) { return; } -void ReadConfig( CScriptParser* pScriptParser ) { - const char* GT; - CT; + void ReadConfig( CScriptParser* pScriptParser ) { + const char* GT; + CT; - do { - GT; - if ( *pToken == '}' ) { - break; - } - - if ( MT( "model" ) ) { - if ( m_numModels >= MAX_TP_MODELS ) { - return; + do { + GT; + if ( *pToken == '}' ) { + break; } - GT; CT; + if ( MT( "model" ) ) { + if ( m_numModels >= MAX_TP_MODELS ) { + return; + } - strncpy( m_trees[m_numModels++].name, pToken, sizeof( m_trees[m_numModels].name ) - 1 ); - m_trees[m_numModels].name[ sizeof( m_trees[m_numModels].name ) - 1 ] = '\0'; - } - else if ( MT( "link" ) ) { - GT; CT; + GT; + CT; - strncpy( m_linkName, pToken, sizeof( m_linkName ) - 1 ); - m_linkName[ sizeof( m_linkName ) - 1 ] = '\0'; + strncpy( m_trees[m_numModels++].name, pToken, sizeof( m_trees[m_numModels].name ) - 1 ); + m_trees[m_numModels].name[ sizeof( m_trees[m_numModels].name ) - 1 ] = '\0'; + } + else if ( MT( "link" ) ) { + GT; + CT; - m_autoLink = true; - } - else if ( MT( "entity" ) ) { - GT; CT; + strncpy( m_linkName, pToken, sizeof( m_linkName ) - 1 ); + m_linkName[ sizeof( m_linkName ) - 1 ] = '\0'; - strncpy( m_entType, pToken, sizeof( m_entType ) - 1 ); - m_entType[ sizeof( m_entType ) - 1 ] = '\0'; - } - else if ( MT( "offset" ) ) { - GT; CT; + m_autoLink = true; + } + else if ( MT( "entity" ) ) { + GT; + CT; - m_offset = atoi( pToken ); - } - else if ( MT( "pitch" ) ) { - GT; CT; + strncpy( m_entType, pToken, sizeof( m_entType ) - 1 ); + m_entType[ sizeof( m_entType ) - 1 ] = '\0'; + } + else if ( MT( "offset" ) ) { + GT; + CT; - m_minPitch = atoi( pToken ); + m_offset = atoi( pToken ); + } + else if ( MT( "pitch" ) ) { + GT; + CT; - GT; CT; + m_minPitch = atoi( pToken ); - m_maxPitch = atoi( pToken ); + GT; + CT; - m_setAngles = true; - } - else if ( MT( "yaw" ) ) { - GT; CT; + m_maxPitch = atoi( pToken ); - m_minYaw = atoi( pToken ); + m_setAngles = true; + } + else if ( MT( "yaw" ) ) { + GT; + CT; - GT; CT; + m_minYaw = atoi( pToken ); - m_maxYaw = atoi( pToken ); + GT; + CT; - m_setAngles = true; - } - else if ( MT( "scale" ) ) { - GT; CT; + m_maxYaw = atoi( pToken ); - m_minScale = static_cast( atof( pToken ) ); + m_setAngles = true; + } + else if ( MT( "scale" ) ) { + GT; + CT; - GT; CT; + m_minScale = static_cast( atof( pToken ) ); - m_maxScale = static_cast( atof( pToken ) ); + GT; + CT; - m_useScale = true; - } - else if ( MT( "numlinks" ) ) { - GT; CT; + m_maxScale = static_cast( atof( pToken ) ); - m_linkNum = atoi( pToken ); - } - } while ( true ); -} + m_useScale = true; + } + else if ( MT( "numlinks" ) ) { + GT; + CT; -bool FindDropPoint( vec3_t in, vec3_t out ); -void DropEntsToGround( void ); -void MakeChain( int linkNum, const char* linkName ); -void SelectChain( void ); + m_linkNum = atoi( pToken ); + } + } while ( true ); + } + + bool FindDropPoint( vec3_t in, vec3_t out ); + void DropEntsToGround( void ); + void MakeChain( int linkNum, const char* linkName ); + void SelectChain( void ); private: -DEntity m_world; + DEntity m_world; -treeModel_t m_trees[MAX_TP_MODELS]; + treeModel_t m_trees[MAX_TP_MODELS]; -int m_numModels; -int m_offset; -int m_maxPitch; -int m_minPitch; -int m_maxYaw; -int m_minYaw; + int m_numModels; + int m_offset; + int m_maxPitch; + int m_minPitch; + int m_maxYaw; + int m_minYaw; -char m_entType[MAX_QPATH]; -char m_linkName[MAX_QPATH]; -int m_linkNum; + char m_entType[MAX_QPATH]; + char m_linkName[MAX_QPATH]; + int m_linkNum; -float m_minScale; -float m_maxScale; + float m_minScale; + float m_maxScale; -bool m_useScale; -bool m_setAngles; -bool m_autoLink; + bool m_useScale; + bool m_setAngles; + bool m_autoLink; }; #endif diff --git a/contrib/bobtoolz/DVisDrawer.h b/contrib/bobtoolz/DVisDrawer.h index c17b3a8f..f04653b4 100644 --- a/contrib/bobtoolz/DVisDrawer.h +++ b/contrib/bobtoolz/DVisDrawer.h @@ -57,25 +57,25 @@ typedef std::list DMetaSurfaces; class DVisDrawer : public Renderable, public OpenGLRenderable { -Shader* m_shader_solid; -Shader* m_shader_wireframe; + Shader* m_shader_solid; + Shader* m_shader_wireframe; public: -DVisDrawer(); -virtual ~DVisDrawer(); + DVisDrawer(); + virtual ~DVisDrawer(); protected: -DMetaSurfaces* m_list; -int refCount; + DMetaSurfaces* m_list; + int refCount; public: -void ClearPoints(); -void SetList( DMetaSurfaces* pointList ); + void ClearPoints(); + void SetList( DMetaSurfaces* pointList ); -void render( RenderStateFlags state ) const; -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + void render( RenderStateFlags state ) const; + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; -void constructShaders(); -void destroyShaders(); + void constructShaders(); + void destroyShaders(); }; diff --git a/contrib/bobtoolz/DWinding.h b/contrib/bobtoolz/DWinding.h index 94a28096..d0214bb1 100644 --- a/contrib/bobtoolz/DWinding.h +++ b/contrib/bobtoolz/DWinding.h @@ -35,32 +35,32 @@ class DPlane; class DWinding { public: -DWinding(); -virtual ~DWinding(); + DWinding(); + virtual ~DWinding(); -void AllocWinding( int points ); + void AllocWinding( int points ); -bool ChopWinding( DPlane* chopPlane ); -bool ChopWindingInPlace( DPlane* chopPlane, vec_t ON_EPSILON ); -void ClipWindingEpsilon( DPlane* chopPlane, vec_t epsilon, DWinding** front, DWinding** back ); + bool ChopWinding( DPlane* chopPlane ); + bool ChopWindingInPlace( DPlane* chopPlane, vec_t ON_EPSILON ); + void ClipWindingEpsilon( DPlane* chopPlane, vec_t epsilon, DWinding** front, DWinding** back ); -void CheckWinding(); -void WindingCentre( vec3_t centre ); -void WindingBounds( vec3_t mins, vec3_t maxs ); -void RemoveColinearPoints(); + void CheckWinding(); + void WindingCentre( vec3_t centre ); + void WindingBounds( vec3_t mins, vec3_t maxs ); + void RemoveColinearPoints(); -DWinding* ReverseWinding(); -DWinding* CopyWinding(); -DPlane* WindingPlane(); + DWinding* ReverseWinding(); + DWinding* CopyWinding(); + DPlane* WindingPlane(); -int WindingOnPlaneSide( vec3_t normal, vec_t dist ); + int WindingOnPlaneSide( vec3_t normal, vec_t dist ); -vec_t WindingArea(); + vec_t WindingArea(); // members -int numpoints; -vec3_t* p; -vec3_t clr; + int numpoints; + vec3_t* p; + vec3_t clr; }; #define MAX_POINTS_ON_WINDING 64 diff --git a/contrib/bobtoolz/ScriptParser.h b/contrib/bobtoolz/ScriptParser.h index b9ec823d..4c17eae9 100644 --- a/contrib/bobtoolz/ScriptParser.h +++ b/contrib/bobtoolz/ScriptParser.h @@ -28,33 +28,33 @@ class CScriptParser //: public IScriptParser { public: -CScriptParser( void ); -~CScriptParser( void ); + CScriptParser( void ); + ~CScriptParser( void ); private: -char m_breakChars[SP_MAX_BREAKCHARS]; -char* m_pScript; -char* m_pScriptSection; -char* m_pLastScriptSection; -char* m_pToken; + char m_breakChars[SP_MAX_BREAKCHARS]; + char* m_pScript; + char* m_pScriptSection; + char* m_pLastScriptSection; + char* m_pToken; -void SkipWhitespace( bool* pbNewLines ); -void ClearBuffer( void ); -const char* MakeToken( const char* pToken ); -bool IsBreakChar( char c ); + void SkipWhitespace( bool* pbNewLines ); + void ClearBuffer( void ); + const char* MakeToken( const char* pToken ); + bool IsBreakChar( char c ); public: -const char* GetToken( bool bAllowLinebreaks ); -void SkipBracedSection( void ); -void SkipRestOfLine( void ); -void UndoGetToken( void ); -void ResetParseSession( void ); + const char* GetToken( bool bAllowLinebreaks ); + void SkipBracedSection( void ); + void SkipRestOfLine( void ); + void UndoGetToken( void ); + void ResetParseSession( void ); -char* GetBufferCopy( void ); -int GetTokenOffset( void ); + char* GetBufferCopy( void ); + int GetTokenOffset( void ); -void LoadScript( const char* pScript ); -void SetScript( char* pScript ); + void LoadScript( const char* pScript ); + void SetScript( char* pScript ); -void AddBreakChar( char c ); + void AddBreakChar( char c ); private: }; diff --git a/contrib/bobtoolz/bobToolz-GTK.cpp b/contrib/bobtoolz/bobToolz-GTK.cpp index 7ef3a727..a3d6b3a0 100644 --- a/contrib/bobtoolz/bobToolz-GTK.cpp +++ b/contrib/bobtoolz/bobToolz-GTK.cpp @@ -68,10 +68,10 @@ static const char* PLUGIN_COMMANDS = "About...,-,Reset Textures...,PitOMatic,-,V GtkWidget *g_pRadiantWnd = NULL; static const char *PLUGIN_ABOUT = "bobToolz for SDRadiant\n" - "by digibob (digibob@splashdamage.com)\n" - "http://www.splashdamage.com\n\n" - "Additional Contributors:\n" - "MarsMattel, RR2DO2\n"; + "by digibob (digibob@splashdamage.com)\n" + "http://www.splashdamage.com\n\n" + "Additional Contributors:\n" + "MarsMattel, RR2DO2\n"; extern "C" const char* QERPlug_Init( void* hApp, void* pMainWidget ) { g_pRadiantWnd = (GtkWidget*)pMainWidget; @@ -166,86 +166,86 @@ std::size_t ToolbarButtonCount( void ) { class CBobtoolzToolbarButton : public IToolbarButton { public: -virtual const char* getImage() const { - switch ( mIndex ) { - case 0: return "bobtoolz_cleanup.png"; - case 1: return "bobtoolz_poly.png"; -// case 2: return "bobtoolz_caulk.png"; - case 2: return ""; - case 3: return "bobtoolz_treeplanter.png"; - case 4: return "bobtoolz_trainpathplot.png"; - case 5: return "bobtoolz_dropent.png"; - case 6: return ""; - case 7: return "bobtoolz_merge.png"; - case 8: return "bobtoolz_split.png"; - case 9: return "bobtoolz_splitrow.png"; - case 10: return "bobtoolz_splitcol.png"; - case 11: return ""; - case 12: return "bobtoolz_turnedge.png"; + virtual const char* getImage() const { + switch ( mIndex ) { + case 0: return "bobtoolz_cleanup.png"; + case 1: return "bobtoolz_poly.png"; + // case 2: return "bobtoolz_caulk.png"; + case 2: return ""; + case 3: return "bobtoolz_treeplanter.png"; + case 4: return "bobtoolz_trainpathplot.png"; + case 5: return "bobtoolz_dropent.png"; + case 6: return ""; + case 7: return "bobtoolz_merge.png"; + case 8: return "bobtoolz_split.png"; + case 9: return "bobtoolz_splitrow.png"; + case 10: return "bobtoolz_splitcol.png"; + case 11: return ""; + case 12: return "bobtoolz_turnedge.png"; + } + return NULL; } - return NULL; -} -virtual EType getType() const { - switch ( mIndex ) { - case 2: return eSpace; - case 3: return eToggleButton; - case 6: return eSpace; - case 11: return eSpace; - default: return eButton; + virtual EType getType() const { + switch ( mIndex ) { + case 2: return eSpace; + case 3: return eToggleButton; + case 6: return eSpace; + case 11: return eSpace; + default: return eButton; + } } -} -virtual const char* getText() const { - switch ( mIndex ) { - case 0: return "Cleanup"; - case 1: return "Polygons"; -// case 2: return "Caulk"; - case 3: return "Tree Planter"; - case 4: return "Plot Splines"; - case 5: return "Drop Entity"; - case 7: return "Merge 2 Patches"; - case 8: return "Split Patch"; - case 9: return "Split Patch Rows"; - case 10: return "Split Patch Columns"; - case 12: return "Flip Terrain"; + virtual const char* getText() const { + switch ( mIndex ) { + case 0: return "Cleanup"; + case 1: return "Polygons"; + // case 2: return "Caulk"; + case 3: return "Tree Planter"; + case 4: return "Plot Splines"; + case 5: return "Drop Entity"; + case 7: return "Merge 2 Patches"; + case 8: return "Split Patch"; + case 9: return "Split Patch Rows"; + case 10: return "Split Patch Columns"; + case 12: return "Flip Terrain"; + } + return NULL; } - return NULL; -} -virtual const char* getTooltip() const { - switch ( mIndex ) { - case 0: return "Brush Cleanup"; - case 1: return "Polygons"; -// case 2: return "Caulk selection"; - case 3: return "Tree Planter"; - case 4: return "Plot Splines"; - case 5: return "Drop Entity"; - case 7: return "Merge 2 Patches"; - case 8: return "Split Patch"; - case 9: return "Split Patch Rows"; - case 10: return "Split Patch Columns"; - case 12: return "Flip Terrain (Turn Edge)"; + virtual const char* getTooltip() const { + switch ( mIndex ) { + case 0: return "Brush Cleanup"; + case 1: return "Polygons"; + // case 2: return "Caulk selection"; + case 3: return "Tree Planter"; + case 4: return "Plot Splines"; + case 5: return "Drop Entity"; + case 7: return "Merge 2 Patches"; + case 8: return "Split Patch"; + case 9: return "Split Patch Rows"; + case 10: return "Split Patch Columns"; + case 12: return "Flip Terrain (Turn Edge)"; + } + return NULL; } - return NULL; -} -virtual void activate() const { - LoadLists(); + virtual void activate() const { + LoadLists(); - switch ( mIndex ) { - case 0: DoFixBrushes(); break; - case 1: DoPolygonsTB(); break; -// case 2: DoCaulkSelection(); break; - case 3: DoTreePlanter(); break; - case 4: DoTrainPathPlot(); break; - case 5: DoDropEnts(); break; - case 7: DoMergePatches(); break; - case 8: DoSplitPatch(); break; - case 9: DoSplitPatchRows(); break; - case 10: DoSplitPatchCols(); break; - case 12: DoFlipTerrain(); break; + switch ( mIndex ) { + case 0: DoFixBrushes(); break; + case 1: DoPolygonsTB(); break; + // case 2: DoCaulkSelection(); break; + case 3: DoTreePlanter(); break; + case 4: DoTrainPathPlot(); break; + case 5: DoDropEnts(); break; + case 7: DoMergePatches(); break; + case 8: DoSplitPatch(); break; + case 9: DoSplitPatchRows(); break; + case 10: DoSplitPatchCols(); break; + case 12: DoFlipTerrain(); break; + } } -} -std::size_t mIndex; + std::size_t mIndex; }; CBobtoolzToolbarButton g_bobtoolzToolbarButtons[NUM_TOOLBARBUTTONS]; @@ -284,37 +284,37 @@ class BobToolzPluginDependencies : public GlobalOpenGLStateLibraryModuleRef { public: -BobToolzPluginDependencies() : - GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), - GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ), - GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), - GlobalPatchModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "patchtypes" ) ){ -} + BobToolzPluginDependencies() : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ), + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + GlobalPatchModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "patchtypes" ) ){ + } }; class BobToolzPluginModule : public TypeSystemRef { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "bobToolz" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "bobToolz" ); -BobToolzPluginModule(){ - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + BobToolzPluginModule(){ + m_plugin.m_pfnQERPlug_Init = QERPlug_Init; + m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; + m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - BobToolz_construct(); -} -~BobToolzPluginModule(){ - BobToolz_destroy(); -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + BobToolz_construct(); + } + ~BobToolzPluginModule(){ + BobToolz_destroy(); + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonBobToolzPluginModule; @@ -326,25 +326,25 @@ class BobToolzToolbarDependencies : public ModuleRef<_QERPluginTable> { public: -BobToolzToolbarDependencies() : - ModuleRef<_QERPluginTable>( "bobToolz" ){ -} + BobToolzToolbarDependencies() : + ModuleRef<_QERPluginTable>( "bobToolz" ){ + } }; class BobToolzToolbarModule : public TypeSystemRef { -_QERPlugToolbarTable m_table; + _QERPlugToolbarTable m_table; public: -typedef _QERPlugToolbarTable Type; -STRING_CONSTANT( Name, "bobToolz" ); + typedef _QERPlugToolbarTable Type; + STRING_CONSTANT( Name, "bobToolz" ); -BobToolzToolbarModule(){ - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; -} -_QERPlugToolbarTable* getTable(){ - return &m_table; -} + BobToolzToolbarModule(){ + m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; + m_table.m_pfnGetToolbarButton = GetToolbarButton; + } + _QERPlugToolbarTable* getTable(){ + return &m_table; + } }; typedef SingletonModule SingletonBobToolzToolbarModule; diff --git a/contrib/bobtoolz/bobToolz.h b/contrib/bobtoolz/bobToolz.h index 4b80ee73..ed8d59e6 100644 --- a/contrib/bobtoolz/bobToolz.h +++ b/contrib/bobtoolz/bobToolz.h @@ -41,7 +41,7 @@ class CPluginApp : public CWinApp { public: -CPluginApp(); + CPluginApp(); // Overrides // ClassWizard generated virtual function overrides @@ -52,7 +52,7 @@ CPluginApp(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; diff --git a/contrib/bobtoolz/bsploader.cpp b/contrib/bobtoolz/bsploader.cpp index 12d17928..468ca147 100644 --- a/contrib/bobtoolz/bsploader.cpp +++ b/contrib/bobtoolz/bsploader.cpp @@ -215,7 +215,7 @@ bool LoadBSPFile( const char *filename ) { return false; } if ( ( header->version != Q3_BSP_VERSION ) && - ( header->version != WOLF_BSP_VERSION ) ) { + ( header->version != WOLF_BSP_VERSION ) ) { DoMessageBox( "File is incorrect version", "Error", eMB_OK ); return false; } @@ -241,7 +241,7 @@ bool LoadBSPFile( const char *filename ) { } void FreeBSPData(){ - #define DEL( a ) delete[] a; a = 0; +#define DEL( a ) delete[] a; a = 0; DEL( visBytes ); DEL( dnodes ); DEL( dplanes ); diff --git a/contrib/bobtoolz/ctfToolz-GTK.cpp b/contrib/bobtoolz/ctfToolz-GTK.cpp index 4e5231d1..bfeae5c5 100644 --- a/contrib/bobtoolz/ctfToolz-GTK.cpp +++ b/contrib/bobtoolz/ctfToolz-GTK.cpp @@ -40,8 +40,8 @@ static const char *PLUGIN_COMMANDS = "About...,Colour Changer...,Swap Light Colo GtkWidget *g_pRadiantWnd = NULL; static const char *PLUGIN_ABOUT = "ctfToolz for NetRadiant\n" - "by djbob\n" - "http://www.planetquake.com/toolz\n\n"; + "by djbob\n" + "http://www.planetquake.com/toolz\n\n"; extern "C" LPVOID WINAPI QERPlug_GetFuncTable(){ return &g_FuncTable; diff --git a/contrib/bobtoolz/dialogs/AboutDialog.h b/contrib/bobtoolz/dialogs/AboutDialog.h index 64b4eb2c..fd3c5a80 100644 --- a/contrib/bobtoolz/dialogs/AboutDialog.h +++ b/contrib/bobtoolz/dialogs/AboutDialog.h @@ -33,11 +33,11 @@ class CAboutDialog : public CDialog { // Construction public: -CAboutDialog( CWnd* pParent = NULL ); // standard constructor + CAboutDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CAboutDialog) -enum { IDD = IDD_ABOUT }; + enum { IDD = IDD_ABOUT }; //}}AFX_DATA @@ -45,7 +45,7 @@ enum { IDD = IDD_ABOUT }; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -55,7 +55,7 @@ protected: //{{AFX_MSG(CAboutDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/AutoCaulkDialog.h b/contrib/bobtoolz/dialogs/AutoCaulkDialog.h index 30ca2e75..41f18daa 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkDialog.h +++ b/contrib/bobtoolz/dialogs/AutoCaulkDialog.h @@ -33,13 +33,13 @@ class CAutoCaulkDialog : public CDialog { // Construction public: -CAutoCaulkDialog( CWnd* pParent = NULL ); // standard constructor + CAutoCaulkDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CAutoCaulkDialog) -enum { IDD = IDD_AUTOCAULK_DIALOG }; -CProgressCtrl m_prog2; -CProgressCtrl m_prog1; + enum { IDD = IDD_AUTOCAULK_DIALOG }; + CProgressCtrl m_prog2; + CProgressCtrl m_prog1; //}}AFX_DATA @@ -47,7 +47,7 @@ CProgressCtrl m_prog1; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAutoCaulkDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -57,7 +57,7 @@ protected: //{{AFX_MSG(CAutoCaulkDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h index 5c2f4297..d9da6d8e 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h +++ b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h @@ -37,14 +37,14 @@ class CAutoCaulkStartDialog : public CDialog { // Construction public: -CAutoCaulkStartDialog( CWnd* pParent = NULL ); // standard constructor + CAutoCaulkStartDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CAutoCaulkStartDialog) -enum { IDD = IDD_AUTOCAULKSTART_DIALOG }; -BOOL m_bAllowDestruction; -CString m_Warning1; -int m_nMode; + enum { IDD = IDD_AUTOCAULKSTART_DIALOG }; + BOOL m_bAllowDestruction; + CString m_Warning1; + int m_nMode; //}}AFX_DATA @@ -52,7 +52,7 @@ int m_nMode; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAutoCaulkStartDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -62,7 +62,7 @@ protected: //{{AFX_MSG(CAutoCaulkStartDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/BrushCheckDialog.h b/contrib/bobtoolz/dialogs/BrushCheckDialog.h index c232657b..8f7f5d65 100644 --- a/contrib/bobtoolz/dialogs/BrushCheckDialog.h +++ b/contrib/bobtoolz/dialogs/BrushCheckDialog.h @@ -33,12 +33,12 @@ class CBrushCheckDialog : public CDialog { // Construction public: -CBrushCheckDialog( CWnd* pParent = NULL ); // standard constructor + CBrushCheckDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CBrushCheckDialog) -enum { IDD = IDD_BRUSHCHECKER_DIALOG }; -CProgressCtrl m_prog1; + enum { IDD = IDD_BRUSHCHECKER_DIALOG }; + CProgressCtrl m_prog1; //}}AFX_DATA @@ -46,7 +46,7 @@ CProgressCtrl m_prog1; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBrushCheckDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -56,7 +56,7 @@ protected: //{{AFX_MSG(CBrushCheckDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/DoorDialog.h b/contrib/bobtoolz/dialogs/DoorDialog.h index 94242aff..17067859 100644 --- a/contrib/bobtoolz/dialogs/DoorDialog.h +++ b/contrib/bobtoolz/dialogs/DoorDialog.h @@ -33,20 +33,20 @@ class CDoorDialog : public CDialog { // Construction public: -CDoorDialog( CWnd* pParent = NULL ); // standard constructor + CDoorDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CDoorDialog) -enum { IDD = IDD_DOOR_DIALOG }; -CString m_fbTextureName; -BOOL m_bSclMainHor; -BOOL m_bSclMainVert; -BOOL m_bSclTrimHor; -BOOL m_bSclTrimVert; -CString m_trimTextureName; -CString m_trimTexSetBox; -CString m_mainTexSetBox; -int m_doorDirection; + enum { IDD = IDD_DOOR_DIALOG }; + CString m_fbTextureName; + BOOL m_bSclMainHor; + BOOL m_bSclMainVert; + BOOL m_bSclTrimHor; + BOOL m_bSclTrimVert; + CString m_trimTextureName; + CString m_trimTexSetBox; + CString m_mainTexSetBox; + int m_doorDirection; //}}AFX_DATA @@ -54,7 +54,7 @@ int m_doorDirection; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDoorDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -62,10 +62,10 @@ protected: // Generated message map functions //{{AFX_MSG(CDoorDialog) -afx_msg void OnSetMaintexBtn(); -afx_msg void OnSetTrimtexBtn(); + afx_msg void OnSetMaintexBtn(); + afx_msg void OnSetTrimtexBtn(); //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/IntersectDialog.h b/contrib/bobtoolz/dialogs/IntersectDialog.h index d8d64c3e..cab06420 100644 --- a/contrib/bobtoolz/dialogs/IntersectDialog.h +++ b/contrib/bobtoolz/dialogs/IntersectDialog.h @@ -36,14 +36,14 @@ class CIntersectDialog : public CDialog { // Construction public: -CIntersectDialog( CWnd* pParent = NULL ); // standard constructor + CIntersectDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CIntersectDialog) -enum { IDD = IDD_INTERSECT_DIALOG }; -int m_nBrushOptions; -BOOL m_bUseDetail; -BOOL m_bDuplicateOnly; + enum { IDD = IDD_INTERSECT_DIALOG }; + int m_nBrushOptions; + BOOL m_bUseDetail; + BOOL m_bDuplicateOnly; //}}AFX_DATA @@ -51,7 +51,7 @@ BOOL m_bDuplicateOnly; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CIntersectDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -61,7 +61,7 @@ protected: //{{AFX_MSG(CIntersectDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/IntersectInfoDialog.h b/contrib/bobtoolz/dialogs/IntersectInfoDialog.h index 58553d1e..8053e263 100644 --- a/contrib/bobtoolz/dialogs/IntersectInfoDialog.h +++ b/contrib/bobtoolz/dialogs/IntersectInfoDialog.h @@ -33,12 +33,12 @@ class CIntersectInfoDialog : public CDialog { // Construction public: -CIntersectInfoDialog( CWnd* pParent = NULL ); // standard constructor + CIntersectInfoDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CIntersectInfoDialog) -enum { IDD = IDD_INTERSECT_INFO_DIALOG }; -CProgressCtrl m_prog1; + enum { IDD = IDD_INTERSECT_INFO_DIALOG }; + CProgressCtrl m_prog1; //}}AFX_DATA @@ -46,7 +46,7 @@ CProgressCtrl m_prog1; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CIntersectInfoDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -56,7 +56,7 @@ protected: //{{AFX_MSG(CIntersectInfoDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/PolygonDialog.h b/contrib/bobtoolz/dialogs/PolygonDialog.h index 8774e1f0..69eec497 100644 --- a/contrib/bobtoolz/dialogs/PolygonDialog.h +++ b/contrib/bobtoolz/dialogs/PolygonDialog.h @@ -33,19 +33,19 @@ class CPolygonDialog : public CDialog { // Construction public: -BOOL GetChkBool( int nID ); -void EnableBorderEdit( BOOL bEnable ); -void EnableBordered( BOOL bEnable ); -CPolygonDialog( CWnd* pParent = NULL ); // standard constructor + BOOL GetChkBool( int nID ); + void EnableBorderEdit( BOOL bEnable ); + void EnableBordered( BOOL bEnable ); + CPolygonDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CPolygonDialog) -enum { IDD = IDD_POLYGON_DIALOG }; -UINT m_nSideCount; -BOOL m_bInverse; -BOOL m_bBorder; -UINT m_nBorderSize; -BOOL m_bAlignTop; + enum { IDD = IDD_POLYGON_DIALOG }; + UINT m_nSideCount; + BOOL m_bInverse; + BOOL m_bBorder; + UINT m_nBorderSize; + BOOL m_bAlignTop; //}}AFX_DATA @@ -53,7 +53,7 @@ BOOL m_bAlignTop; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPolygonDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -61,11 +61,11 @@ protected: // Generated message map functions //{{AFX_MSG(CPolygonDialog) -virtual BOOL OnInitDialog(); -afx_msg void OnBorderChkClicked(); -afx_msg void OnInverseChkClickrd(); + virtual BOOL OnInitDialog(); + afx_msg void OnBorderChkClicked(); + afx_msg void OnInverseChkClickrd(); //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/StairDialog.h b/contrib/bobtoolz/dialogs/StairDialog.h index 0be13e67..bfaff872 100644 --- a/contrib/bobtoolz/dialogs/StairDialog.h +++ b/contrib/bobtoolz/dialogs/StairDialog.h @@ -33,16 +33,16 @@ class CStairDialog : public CDialog { // Construction public: -CStairDialog( CWnd* pParent = NULL ); // standard constructor + CStairDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CStairDialog) -enum { IDD = IDD_STAIR_DIALOG }; -UINT m_nStairHeight; -int m_StairDir; -int m_StairStyle; -CString m_riserTexture; -BOOL m_bDetail; + enum { IDD = IDD_STAIR_DIALOG }; + UINT m_nStairHeight; + int m_StairDir; + int m_StairStyle; + CString m_riserTexture; + BOOL m_bDetail; //}}AFX_DATA @@ -50,7 +50,7 @@ BOOL m_bDetail; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CStairDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -58,14 +58,14 @@ protected: // Generated message map functions //{{AFX_MSG(CStairDialog) -afx_msg void OnStyleBobClicked(); -afx_msg void OnStyleOrigClicked(); -virtual BOOL OnInitDialog(); -afx_msg void OnStyleCornerClicked(); + afx_msg void OnStyleBobClicked(); + afx_msg void OnStyleOrigClicked(); + virtual BOOL OnInitDialog(); + afx_msg void OnStyleCornerClicked(); //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() private: -void EnableDetail( BOOL bEnable ); + void EnableDetail( BOOL bEnable ); }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/TextureResetDialog.h b/contrib/bobtoolz/dialogs/TextureResetDialog.h index 40260735..77f35d8f 100644 --- a/contrib/bobtoolz/dialogs/TextureResetDialog.h +++ b/contrib/bobtoolz/dialogs/TextureResetDialog.h @@ -33,20 +33,20 @@ class CTextureResetDialog : public CDialog { // Construction public: -CTextureResetDialog( CWnd* pParent = NULL ); // standard constructor + CTextureResetDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CTextureResetDialog) -enum { IDD = IDD_TEXTURE_RESET_DIALOG }; -BOOL m_bAllTextures; -CString m_TextureName; -int m_nRotation; -float m_fScaleHorizontal; -float m_fScaleVertical; -int m_nShiftHorizontal; -int m_nShiftVertical; -BOOL m_bOnlyTexture; -CString m_NewTextureName; + enum { IDD = IDD_TEXTURE_RESET_DIALOG }; + BOOL m_bAllTextures; + CString m_TextureName; + int m_nRotation; + float m_fScaleHorizontal; + float m_fScaleVertical; + int m_nShiftHorizontal; + int m_nShiftVertical; + BOOL m_bOnlyTexture; + CString m_NewTextureName; //}}AFX_DATA @@ -54,7 +54,7 @@ CString m_NewTextureName; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTextureResetDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -64,7 +64,7 @@ protected: //{{AFX_MSG(CTextureResetDialog) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/dialogs-gtk.cpp b/contrib/bobtoolz/dialogs/dialogs-gtk.cpp index bafe1f98..4c230c34 100644 --- a/contrib/bobtoolz/dialogs/dialogs-gtk.cpp +++ b/contrib/bobtoolz/dialogs/dialogs-gtk.cpp @@ -47,7 +47,7 @@ typedef struct { GtkWidget *cbRotation; GtkWidget *editRotation; -}dlg_texReset_t; +} dlg_texReset_t; dlg_texReset_t dlgTexReset; @@ -221,9 +221,9 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pRadiantWnd ) ); gtk_window_set_modal( GTK_WINDOW( window ), TRUE ); g_signal_connect( G_OBJECT( window ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( window ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), lpCaption ); gtk_container_set_border_width( GTK_CONTAINER( window ), 10 ); g_object_set_data( G_OBJECT( window ), "loop", &loop ); @@ -251,7 +251,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -261,7 +261,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -269,7 +269,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); gtk_widget_show( w ); ret = eIDCANCEL; } @@ -277,7 +277,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -285,13 +285,13 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); gtk_widget_show( w ); ret = eIDCANCEL; } @@ -300,7 +300,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -308,7 +308,7 @@ EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMess w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); gtk_widget_show( w ); ret = eIDNO; } @@ -1355,33 +1355,33 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ g_signal_connect( G_OBJECT( dlgTexReset.cbTexChange ), "toggled", G_CALLBACK( dialog_button_callback_texreset_update ), NULL ); gtk_widget_show( dlgTexReset.cbTexChange ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbTexChange, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "Old Name: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editTexOld = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editTexOld ), rs->textureName ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editTexOld, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editTexOld ); w = gtk_label_new( "New Name: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editTexNew = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editTexNew ), rs->textureName ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editTexNew, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editTexNew ); // ---- /frame ---- @@ -1403,20 +1403,20 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ g_signal_connect( G_OBJECT( dlgTexReset.cbScaleHor ), "toggled", G_CALLBACK( dialog_button_callback_texreset_update ), NULL ); gtk_widget_show( dlgTexReset.cbScaleHor ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbScaleHor, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "New Horizontal Scale: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editScaleHor = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editScaleHor ), "0.5" ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editScaleHor, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editScaleHor ); @@ -1424,20 +1424,20 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ g_signal_connect( G_OBJECT( dlgTexReset.cbScaleVert ), "toggled", G_CALLBACK( dialog_button_callback_texreset_update ), NULL ); gtk_widget_show( dlgTexReset.cbScaleVert ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbScaleVert, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "New Vertical Scale: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editScaleVert = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editScaleVert ), "0.5" ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editScaleVert, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editScaleVert ); // ---- /frame ---- @@ -1459,20 +1459,20 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ g_signal_connect( G_OBJECT( dlgTexReset.cbShiftHor ), "toggled", G_CALLBACK( dialog_button_callback_texreset_update ), NULL ); gtk_widget_show( dlgTexReset.cbShiftHor ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbShiftHor, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "New Horizontal Shift: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editShiftHor = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editShiftHor ), "0" ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editShiftHor, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editShiftHor ); @@ -1480,20 +1480,20 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ g_signal_connect( G_OBJECT( dlgTexReset.cbShiftVert ), "toggled", G_CALLBACK( dialog_button_callback_texreset_update ), NULL ); gtk_widget_show( dlgTexReset.cbShiftVert ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbShiftVert, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "New Vertical Shift: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editShiftVert = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editShiftVert ), "0" ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editShiftVert, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editShiftVert ); // ---- /frame ---- @@ -1514,20 +1514,20 @@ EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ dlgTexReset.cbRotation = gtk_check_button_new_with_label( "Enabled" ); gtk_widget_show( dlgTexReset.cbRotation ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbRotation, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); w = gtk_label_new( "New Rotation Value: " ); gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); dlgTexReset.editRotation = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editRotation ), "0" ); gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editRotation, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( dlgTexReset.editRotation ); // ---- /frame ---- @@ -1677,30 +1677,30 @@ EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ){ w = gtk_label_new( "X: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); radiusX = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( radiusX ), "100" ); gtk_table_attach( GTK_TABLE( table ), radiusX, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( radiusX ); w = gtk_label_new( "Y: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); radiusY = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( radiusY ), "100" ); gtk_table_attach( GTK_TABLE( table ), radiusY, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( radiusY ); @@ -1720,30 +1720,30 @@ EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ){ w = gtk_label_new( "Start: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); angleStart = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( angleStart ), "0" ); gtk_table_attach( GTK_TABLE( table ), angleStart, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( angleStart ); w = gtk_label_new( "End: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); angleEnd = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( angleEnd ), "90" ); gtk_table_attach( GTK_TABLE( table ), angleEnd, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( angleEnd ); @@ -1762,30 +1762,30 @@ EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ){ w = gtk_label_new( "Start: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); heightStart = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( heightStart ), "0" ); gtk_table_attach( GTK_TABLE( table ), heightStart, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( heightStart ); w = gtk_label_new( "End: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); heightEnd = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( heightEnd ), "0" ); gtk_table_attach( GTK_TABLE( table ), heightEnd, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( heightEnd ); @@ -1805,15 +1805,15 @@ EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ){ w = gtk_label_new( "Number: " ); gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( w ); numPoints = entry_new_with_max_length( 256 ); gtk_entry_set_text( GTK_ENTRY( numPoints ), "0" ); gtk_table_attach( GTK_TABLE( table ), numPoints, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( numPoints ); diff --git a/contrib/bobtoolz/dialogs/pathplotterdialog.h b/contrib/bobtoolz/dialogs/pathplotterdialog.h index 03e50873..4764a4e7 100644 --- a/contrib/bobtoolz/dialogs/pathplotterdialog.h +++ b/contrib/bobtoolz/dialogs/pathplotterdialog.h @@ -33,16 +33,16 @@ class CPathPlotterDialog : public CDialog { // Construction public: -CPathPlotterDialog( CWnd* pParent = NULL ); // standard constructor + CPathPlotterDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data //{{AFX_DATA(CPathPlotterDialog) -enum { IDD = IDD_PATHPLOTTER_DIALOG }; -float m_fGravity; -float m_fMultiplier; -BOOL m_bNoUpdate; -int m_nPoints; -BOOL m_bShowExtra; + enum { IDD = IDD_PATHPLOTTER_DIALOG }; + float m_fGravity; + float m_fMultiplier; + BOOL m_bNoUpdate; + int m_nPoints; + BOOL m_bShowExtra; //}}AFX_DATA @@ -50,7 +50,7 @@ BOOL m_bShowExtra; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPathPlotterDialog) protected: -virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support + virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support //}}AFX_VIRTUAL // Implementation @@ -58,10 +58,10 @@ protected: // Generated message map functions //{{AFX_MSG(CPathPlotterDialog) -afx_msg void OnYes(); -afx_msg void OnNo(); + afx_msg void OnYes(); + afx_msg void OnNo(); //}}AFX_MSG -DECLARE_MESSAGE_MAP() + DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/funchandlers-GTK.cpp b/contrib/bobtoolz/funchandlers-GTK.cpp index dcba269b..84eb94eb 100644 --- a/contrib/bobtoolz/funchandlers-GTK.cpp +++ b/contrib/bobtoolz/funchandlers-GTK.cpp @@ -224,14 +224,14 @@ void DoResetTextures(){ DEntity world; world.LoadSelectedBrushes(); world.ResetTextures( texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation, true ); + rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation, true ); } else { DMap world; world.LoadAll( true ); world.ResetTextures( texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation ); + rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation ); } } @@ -350,10 +350,10 @@ void DoBuildDoors(){ } BuildDoorsX2( vMin, vMax, - rs.bScaleMainH, rs.bScaleMainV, - rs.bScaleTrimH, rs.bScaleTrimV, - rs.mainTexture, rs.trimTexture, - rs.nOrientation ); // shapes.cpp + rs.bScaleMainH, rs.bScaleMainV, + rs.bScaleTrimH, rs.bScaleTrimV, + rs.mainTexture, rs.trimTexture, + rs.nOrientation ); // shapes.cpp } } @@ -483,7 +483,7 @@ void DoMergePatches(){ Path_deleteTop( patches[1]->path() ); Entity* entity = Node_getEntity( parent.path().top() ); if ( entity != 0 - && Node_getTraversable( parent.path().top() )->empty() ) { + && Node_getTraversable( parent.path().top() )->empty() ) { Path_deleteTop( parent.path() ); } diff --git a/contrib/bobtoolz/funchandlers-ctf-GTK.cpp b/contrib/bobtoolz/funchandlers-ctf-GTK.cpp index 637cf5a2..d6cc80c0 100644 --- a/contrib/bobtoolz/funchandlers-ctf-GTK.cpp +++ b/contrib/bobtoolz/funchandlers-ctf-GTK.cpp @@ -103,20 +103,20 @@ void DoCTFColourChanger(){ void DoSwapLights(){ /* DMap world; - world.LoadAll(); + world.LoadAll(); - for(list::const_iterator loopEnt = world.entityList.begin(); loopEnt != world.entityList.end(); loopEnt++) - { - DEntity* e = (*loopEnt); - DEPair* epLightColour = e->FindEPairByKey("_color"); - if(epLightColour) - { - float r, g, b; - sscanf(epLightColour->value, "%f %f %f", &r, &g, &b); - sprintf(epLightColour->value, "%f %f %f", b, g, r); - DMap::RebuildEntity(e); - } - }*/ + for(list::const_iterator loopEnt = world.entityList.begin(); loopEnt != world.entityList.end(); loopEnt++) + { + DEntity* e = (*loopEnt); + DEPair* epLightColour = e->FindEPairByKey("_color"); + if(epLightColour) + { + float r, g, b; + sscanf(epLightColour->value, "%f %f %f", &r, &g, &b); + sprintf(epLightColour->value, "%f %f %f", b, g, r); + DMap::RebuildEntity(e); + } + }*/ int cnt = g_FuncTable.m_pfnGetEntityCount(); diff --git a/contrib/bobtoolz/funchandlers.cpp b/contrib/bobtoolz/funchandlers.cpp index 2a404211..a49a2aad 100644 --- a/contrib/bobtoolz/funchandlers.cpp +++ b/contrib/bobtoolz/funchandlers.cpp @@ -275,11 +275,11 @@ void DoorBuilder( vec3_t vMin, vec3_t vMax ){ g_FuncTable.m_pfnDeleteBrushHandle( brush ); BuildDoorsX2( vMin, vMax, - doorDlg.m_bSclMainHor, doorDlg.m_bSclMainVert, - doorDlg.m_bSclTrimHor, doorDlg.m_bSclTrimVert, - (LPCTSTR)doorDlg.m_fbTextureName, - (LPCTSTR)doorDlg.m_trimTextureName, - doorDlg.m_doorDirection ); + doorDlg.m_bSclMainHor, doorDlg.m_bSclMainVert, + doorDlg.m_bSclTrimHor, doorDlg.m_bSclTrimVert, + (LPCTSTR)doorDlg.m_fbTextureName, + (LPCTSTR)doorDlg.m_trimTextureName, + doorDlg.m_doorDirection ); } g_FuncTable.m_pfnReleaseSelectedBrushHandles(); diff --git a/contrib/bobtoolz/misc.cpp b/contrib/bobtoolz/misc.cpp index 3480efb5..e31f5adc 100644 --- a/contrib/bobtoolz/misc.cpp +++ b/contrib/bobtoolz/misc.cpp @@ -204,28 +204,28 @@ void StartBSP(){ class EntityWriteMiniPrt { -mutable DEntity world; -FILE* pFile; -std::list* exclusionList; + mutable DEntity world; + FILE* pFile; + std::list* exclusionList; public: -EntityWriteMiniPrt( FILE* pFile, std::list* exclusionList ) - : pFile( pFile ), exclusionList( exclusionList ){ -} -void operator()( scene::Instance& instance ) const { - const char* classname = Node_getEntity( instance.path().top() )->getKeyValue( "classname" ); + EntityWriteMiniPrt( FILE* pFile, std::list* exclusionList ) + : pFile( pFile ), exclusionList( exclusionList ){ + } + void operator()( scene::Instance& instance ) const { + const char* classname = Node_getEntity( instance.path().top() )->getKeyValue( "classname" ); - if ( !strcmp( classname, "worldspawn" ) ) { - world.LoadFromEntity( instance.path().top(), false ); - world.RemoveNonCheckBrushes( exclusionList, true ); - world.SaveToFile( pFile ); + if ( !strcmp( classname, "worldspawn" ) ) { + world.LoadFromEntity( instance.path().top(), false ); + world.RemoveNonCheckBrushes( exclusionList, true ); + world.SaveToFile( pFile ); + } + else if ( strstr( classname, "info_" ) ) { + world.ClearBrushes(); + world.ClearEPairs(); + world.LoadEPairList( Node_getEntity( instance.path().top() ) ); + world.SaveToFile( pFile ); + } } - else if ( strstr( classname, "info_" ) ) { - world.ClearBrushes(); - world.ClearEPairs(); - world.LoadEPairList( Node_getEntity( instance.path().top() ) ); - world.SaveToFile( pFile ); - } -} }; void BuildMiniPrt( std::list* exclusionList ){ @@ -256,21 +256,21 @@ void BuildMiniPrt( std::list* exclusionList ){ class EntityFindByTargetName { -const char* targetname; + const char* targetname; public: -mutable const scene::Path* result; -EntityFindByTargetName( const char* targetname ) - : targetname( targetname ), result( 0 ){ -} -void operator()( scene::Instance& instance ) const { - if ( result == 0 ) { - const char* value = Node_getEntity( instance.path().top() )->getKeyValue( "targetname" ); + mutable const scene::Path* result; + EntityFindByTargetName( const char* targetname ) + : targetname( targetname ), result( 0 ){ + } + void operator()( scene::Instance& instance ) const { + if ( result == 0 ) { + const char* value = Node_getEntity( instance.path().top() )->getKeyValue( "targetname" ); - if ( !strcmp( value, targetname ) ) { - result = &instance.path(); + if ( !strcmp( value, targetname ) ) { + result = &instance.path(); + } } } -} }; const scene::Path* FindEntityFromTargetname( const char* targetname ){ @@ -298,8 +298,8 @@ void FillDefaultTexture( _QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc } float Determinant3x3( float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3 ){ + float b1, float b2, float b3, + float c1, float c2, float c3 ){ return a1 * ( b2 * c3 - b3 * c2 ) - a2 * ( b1 * c3 - b3 * c1 ) + a3 * ( b1 * c2 - b2 * c1 ); } diff --git a/contrib/bobtoolz/misc.h b/contrib/bobtoolz/misc.h index 02ca174b..0b51176c 100644 --- a/contrib/bobtoolz/misc.h +++ b/contrib/bobtoolz/misc.h @@ -48,8 +48,8 @@ char* GetFilename( char* buffer, const char* filename ); char* GetGameFilename( char* buffer, const char* filename ); float Determinant3x3( float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3 ); + float b1, float b2, float b3, + float c1, float c2, float c3 ); bool GetEntityCentre( const char* entity, vec3_t centre ); void MakeNormal( const vec_t* va, const vec_t* vb, const vec_t* vc, vec_t* out ); diff --git a/contrib/bobtoolz/shapes.cpp b/contrib/bobtoolz/shapes.cpp index 04746469..06e90bda 100644 --- a/contrib/bobtoolz/shapes.cpp +++ b/contrib/bobtoolz/shapes.cpp @@ -92,8 +92,8 @@ void AddFaceWithTexture( scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, co } void AddFaceWithTextureScaled( scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, - const char* texture, bool bVertScale, bool bHorScale, - float minX, float minY, float maxX, float maxY ){ + const char* texture, bool bVertScale, bool bHorScale, + float minX, float minY, float maxX, float maxY ){ qtexture_t* pqtTexInfo; // TTimo: there used to be a call to pfnHasShader here @@ -454,10 +454,10 @@ void Build_StairStep( vec3_t min, vec3_t max, const char* mainTexture, const cha //----------------------------------------------------------------------------------- void BuildDoorsX2( vec3_t min, vec3_t max, - bool bSclMainHor, bool bSclMainVert, - bool bSclTrimHor, bool bSclTrimVert, - const char* mainTexture, const char* trimTexture, - int direction ){ + bool bSclMainHor, bool bSclMainVert, + bool bSclTrimHor, bool bSclTrimVert, + const char* mainTexture, const char* trimTexture, + int direction ){ int xy; if ( direction == 0 ) { xy = 0; @@ -523,43 +523,43 @@ void BuildDoorsX2( vec3_t min, vec3_t max, if ( direction == 0 ) { AddFaceWithTextureScaled( newBrush1, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2] ); + min[0], min[2], max[0], max[2] ); AddFaceWithTextureScaled( newBrush1, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2] ); + max[0], min[2], min[0], max[2] ); AddFaceWithTextureScaled( newBrush2, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2] ); + min[0], min[2], max[0], max[2] ); AddFaceWithTextureScaled( newBrush2, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2] ); // flip max/min to reverse tex dir + max[0], min[2], min[0], max[2] ); // flip max/min to reverse tex dir AddFaceWithTextureScaled( newBrush1, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - min[1], min[2], max[1], max[2] ); + min[1], min[2], max[1], max[2] ); AddFaceWithTextureScaled( newBrush2, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - max[1], min[2], min[1], max[2] ); + max[1], min[2], min[1], max[2] ); } else { AddFaceWithTextureScaled( newBrush1, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2] ); + min[1], min[2], max[1], max[2] ); AddFaceWithTextureScaled( newBrush1, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2] ); + max[1], min[2], min[1], max[2] ); AddFaceWithTextureScaled( newBrush2, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2] ); + min[1], min[2], max[1], max[2] ); AddFaceWithTextureScaled( newBrush2, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2] ); // flip max/min to reverse tex dir + max[1], min[2], min[1], max[2] ); // flip max/min to reverse tex dir AddFaceWithTextureScaled( newBrush1, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - min[0], min[2], max[0], max[2] ); + min[0], min[2], max[0], max[2] ); AddFaceWithTextureScaled( newBrush2, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - max[0], min[2], min[0], max[2] ); + max[0], min[2], min[0], max[2] ); } //---------------------------------- @@ -604,8 +604,8 @@ void MakeBevel( vec3_t vMin, vec3_t vMax ){ GlobalPatchCreator().Patch_setShader( patch, "textures/common/caulk" ); PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints( patch ); vec3_t x_3, y_3, z_3; - x_3[0] = vMin[0]; x_3[1] = vMin[0]; x_3[2] = vMax[0]; - y_3[0] = vMin[1]; y_3[1] = vMax[1]; y_3[2] = vMax[1]; + x_3[0] = vMin[0]; x_3[1] = vMin[0]; x_3[2] = vMax[0]; + y_3[0] = vMin[1]; y_3[1] = vMax[1]; y_3[2] = vMax[1]; z_3[0] = vMin[2]; z_3[1] = ( vMax[2] + vMin[2] ) / 2; z_3[2] = vMax[2]; /* x_3[0] = 0; x_3[1] = 0; x_3[2] = 64; diff --git a/contrib/bobtoolz/visfind.cpp b/contrib/bobtoolz/visfind.cpp index 4c23d314..6d1cd7a2 100644 --- a/contrib/bobtoolz/visfind.cpp +++ b/contrib/bobtoolz/visfind.cpp @@ -49,8 +49,7 @@ int bsp_leafnumfororigin( vec3_t origin ){ node = &dnodes[node->children[0]]; } } - else - if ( node->children[1] < 0 ) { + else if ( node->children[1] < 0 ) { return -( node->children[1] + 1 ); } else{ @@ -191,11 +190,11 @@ DMetaSurfaces *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byte *visd vec3_t clr; do { VectorSet( clr, - ( rand() % 256 ) / 255.f, - ( rand() % 256 ) / 255.f, - ( rand() % 256 ) / 255.f ); - }while( ( clr[0] + clr[2] < clr[1] * 1.5f ) || //too green - ( clr[0] < .3 && clr[1] < .3 && clr[2] < .3 ) ); //too dark + ( rand() % 256 ) / 255.f, + ( rand() % 256 ) / 255.f, + ( rand() % 256 ) / 255.f ); + } while( ( clr[0] + clr[2] < clr[1] * 1.5f ) || //too green + ( clr[0] < .3 && clr[1] < .3 && clr[2] < .3 ) ); //too dark AddCluster( pointlist, cl, repeatlist, clr ); } diff --git a/contrib/brushexport/callbacks.cpp b/contrib/brushexport/callbacks.cpp index 4a262ab5..7aca1300 100644 --- a/contrib/brushexport/callbacks.cpp +++ b/contrib/brushexport/callbacks.cpp @@ -55,9 +55,9 @@ void OnExportClicked( GtkButton* button, gpointer choose_path ){ // get ignore list from ui StringSetWithLambda ignore - ( []( const std::string& lhs, const std::string& rhs )->bool{ - return string_less_nocase( lhs.c_str(), rhs.c_str() ); - } ); + ( []( const std::string& lhs, const std::string& rhs )->bool{ + return string_less_nocase( lhs.c_str(), rhs.c_str() ); + } ); GtkTreeView* view = GTK_TREE_VIEW( lookup_widget( GTK_WIDGET( button ), "t_materialist" ) ); GtkListStore* list = GTK_LIST_STORE( gtk_tree_view_get_model( view ) ); diff --git a/contrib/brushexport/export.cpp b/contrib/brushexport/export.cpp index 46764868..e14d1e7d 100644 --- a/contrib/brushexport/export.cpp +++ b/contrib/brushexport/export.cpp @@ -22,39 +22,39 @@ class ExportData { public: -ExportData( const StringSetWithLambda& ignorelist, collapsemode mode ); -virtual ~ExportData( void ); + ExportData( const StringSetWithLambda& ignorelist, collapsemode mode ); + virtual ~ExportData( void ); -virtual void BeginBrush( Brush& b ); -virtual void AddBrushFace( Face& f ); -virtual void EndBrush( void ); + virtual void BeginBrush( Brush& b ); + virtual void AddBrushFace( Face& f ); + virtual void EndBrush( void ); -virtual bool WriteToFile( const std::string& path, collapsemode mode ) const = 0; + virtual bool WriteToFile( const std::string& path, collapsemode mode ) const = 0; protected: // a group of faces -class group -{ -public: -std::string name; -std::list faces; -}; + class group + { + public: + std::string name; + std::list faces; + }; -std::list groups; + std::list groups; private: // "textures/common/caulk" -> "caulk" -void GetShaderNameFromShaderPath( const char* path, std::string& name ); + void GetShaderNameFromShaderPath( const char* path, std::string& name ); -group* current; -const collapsemode mode; -const StringSetWithLambda& ignorelist; + group* current; + const collapsemode mode; + const StringSetWithLambda& ignorelist; }; -ExportData::ExportData( const StringSetWithLambda& _ignorelist, collapsemode _mode ) - : mode( _mode ), +ExportData::ExportData( const StringSetWithLambda& _ignorelist, collapsemode _mode ) : + mode( _mode ), ignorelist( _ignorelist ){ current = 0; @@ -154,21 +154,21 @@ void ExportData::GetShaderNameFromShaderPath( const char* path, std::string& nam class ExportDataAsWavefront : public ExportData { private: -const bool expmat; -const bool limNames; -const bool objs; -const bool weld; + const bool expmat; + const bool limNames; + const bool objs; + const bool weld; public: -ExportDataAsWavefront( const StringSetWithLambda& _ignorelist, collapsemode _mode, bool _expmat, bool _limNames, bool _objs, bool _weld ) - : ExportData( _ignorelist, _mode ), - expmat( _expmat ), - limNames( _limNames ), - objs( _objs ), - weld( _weld ){ -} + ExportDataAsWavefront( const StringSetWithLambda& _ignorelist, collapsemode _mode, bool _expmat, bool _limNames, bool _objs, bool _weld ) + : ExportData( _ignorelist, _mode ), + expmat( _expmat ), + limNames( _limNames ), + objs( _objs ), + weld( _weld ){ + } -bool WriteToFile( const std::string& path, collapsemode mode ) const; + bool WriteToFile( const std::string& path, collapsemode mode ) const; }; bool ExportDataAsWavefront::WriteToFile( const std::string& path, collapsemode mode ) const { @@ -241,8 +241,8 @@ bool ExportDataAsWavefront::WriteToFile( const std::string& path, collapsemode m const Vector3& vertex = w[i].vertex; if( weld ){ auto found = std::find_if( vertices.begin(), vertices.end(), [&vertex]( const Vector3& othervertex ){ - return Edge_isDegenerate( vertex, othervertex ); - } ); + return Edge_isDegenerate( vertex, othervertex ); + } ); if( found == vertices.end() ){ // unique vertex, add to the list vertices.emplace_back( vertex ); } @@ -336,40 +336,40 @@ bool ExportDataAsWavefront::WriteToFile( const std::string& path, collapsemode m class ForEachFace : public BrushVisitor { public: -ForEachFace( ExportData& _exporter ) - : exporter( _exporter ) -{} + ForEachFace( ExportData& _exporter ) + : exporter( _exporter ) + {} -void visit( Face& face ) const { - if( face.contributes() ) - exporter.AddBrushFace( face ); -} + void visit( Face& face ) const { + if( face.contributes() ) + exporter.AddBrushFace( face ); + } private: -ExportData& exporter; + ExportData& exporter; }; class ForEachSelected : public SelectionSystem::Visitor { public: -ForEachSelected( ExportData& _exporter ) - : exporter( _exporter ) -{} + ForEachSelected( ExportData& _exporter ) + : exporter( _exporter ) + {} -void visit( scene::Instance& instance ) const { - BrushInstance* bptr = InstanceTypeCast::cast( instance ); - if ( bptr ) { - Brush& brush( bptr->getBrush() ); + void visit( scene::Instance& instance ) const { + BrushInstance* bptr = InstanceTypeCast::cast( instance ); + if ( bptr ) { + Brush& brush( bptr->getBrush() ); - exporter.BeginBrush( brush ); - ForEachFace face_vis( exporter ); - brush.forEachFace( face_vis ); - exporter.EndBrush(); + exporter.BeginBrush( brush ); + ForEachFace face_vis( exporter ); + brush.forEachFace( face_vis ); + exporter.EndBrush(); + } } -} private: -ExportData& exporter; + ExportData& exporter; }; #include "plugin.h" diff --git a/contrib/brushexport/plugin.cpp b/contrib/brushexport/plugin.cpp index 48e57215..308d510d 100644 --- a/contrib/brushexport/plugin.cpp +++ b/contrib/brushexport/plugin.cpp @@ -69,10 +69,11 @@ const char* getCommandTitleList(){ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ if ( string_equal( command, "About" ) ) { - GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), "Brushexport plugin v 2.0 by namespace (www.codecreator.net)\n" - "Enjoy!\n\nSend feedback to spam@codecreator.net", "About me...", - eMB_OK, - eMB_ICONDEFAULT ); + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), + "Brushexport plugin v 2.0 by namespace (www.codecreator.net)\n" + "Enjoy!\n\nSend feedback to spam@codecreator.net", "About me...", + eMB_OK, + eMB_ICONDEFAULT ); } else if ( string_equal( command, "Export .obj" ) ) { CreateWindow(); @@ -89,28 +90,28 @@ class BrushExportDependencies : public GlobalSelectionModuleRef { public: -BrushExportDependencies( void ) - : GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ) -{} + BrushExportDependencies( void ) + : GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ) + {} }; class BrushExportModule : public TypeSystemRef { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "brushexport2" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "brushexport2" ); -BrushExportModule(){ - m_plugin.m_pfnQERPlug_Init = &BrushExport::init; - m_plugin.m_pfnQERPlug_GetName = &BrushExport::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &BrushExport::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &BrushExport::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &BrushExport::dispatch; -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + BrushExportModule(){ + m_plugin.m_pfnQERPlug_Init = &BrushExport::init; + m_plugin.m_pfnQERPlug_GetName = &BrushExport::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &BrushExport::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &BrushExport::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &BrushExport::dispatch; + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonBrushExportModule; diff --git a/contrib/brushexport/support.cpp b/contrib/brushexport/support.cpp index 5aaf6024..3bc57cdf 100644 --- a/contrib/brushexport/support.cpp +++ b/contrib/brushexport/support.cpp @@ -4,7 +4,7 @@ GtkWidget* lookup_widget( GtkWidget *widget, - const gchar *widget_name ){ + const gchar *widget_name ){ GtkWidget *parent, *found_widget; for (;; ) @@ -25,7 +25,7 @@ lookup_widget( GtkWidget *widget, } found_widget = (GtkWidget*) g_object_get_data( G_OBJECT( widget ), - widget_name ); + widget_name ); if ( !found_widget ) { g_warning( "Widget not found: %s", widget_name ); } diff --git a/contrib/brushexport/support.h b/contrib/brushexport/support.h index e8f4cb04..bde944c9 100644 --- a/contrib/brushexport/support.h +++ b/contrib/brushexport/support.h @@ -19,4 +19,4 @@ * you want returned. */ GtkWidget* lookup_widget( GtkWidget *widget, - const gchar *widget_name ); + const gchar *widget_name ); diff --git a/contrib/camera/camera.cpp b/contrib/camera/camera.cpp index 0ee788d0..739b0b24 100644 --- a/contrib/camera/camera.cpp +++ b/contrib/camera/camera.cpp @@ -50,10 +50,10 @@ int g_iActiveTarget = -1; int g_iPreviewRunning = 0; // 0: no preview 1: start preview 2: preview in progress static const char *PLUGIN_ABOUT = "Camera v1.0 for NetRadiant\n" - "by Arnout van Meer (rr2do2@splashdamage.com)\n\n" - "This product contains software technology\n" - "from id Software, Inc. ('id Technology').\n" - "id Technology (c) 2001, 2002 id Software, Inc."; + "by Arnout van Meer (rr2do2@splashdamage.com)\n\n" + "This product contains software technology\n" + "from id Software, Inc. ('id Technology').\n" + "id Technology (c) 2001, 2002 id Software, Inc."; #include "iplugin.h" @@ -131,21 +131,21 @@ unsigned int ToolbarButtonCount(){ class CameraInspectorButton : public IToolbarButton { public: -virtual const char* getImage() const { - return "camera_insp.png"; -} -virtual const char* getText() const { - return "Inspector"; -} -virtual const char* getTooltip() const { - return "Camera Inspector"; -} -virtual void activate() const { - DoCameraInspector(); -} -virtual EType getType() const { - return eButton; -} + virtual const char* getImage() const { + return "camera_insp.png"; + } + virtual const char* getText() const { + return "Inspector"; + } + virtual const char* getTooltip() const { + return "Camera Inspector"; + } + virtual void activate() const { + DoCameraInspector(); + } + virtual EType getType() const { + return eButton; + } }; CameraInspectorButton g_camerainspectorbutton; @@ -169,11 +169,11 @@ class CameraSynapseClient : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); -CameraSynapseClient() { } -virtual ~CameraSynapseClient() { } + CameraSynapseClient() { } + virtual ~CameraSynapseClient() { } }; CSynapseServer* g_pSynapseServer = NULL; diff --git a/contrib/camera/camera.h b/contrib/camera/camera.h index 896ca1be..eee83a1f 100644 --- a/contrib/camera/camera.h +++ b/contrib/camera/camera.h @@ -89,66 +89,66 @@ extern "C" qboolean loadCamera( int camNum, const char *name ); class CCamera { public: -CCamera( int i ) { - cam = &camera[i]; - camnum = i; - Init(); -} -~CCamera(); - -void Init() { - next = prev = NULL; - fileName[0] = '\0'; - hasbeensaved = 0; -} - -idCameraDef *GetCam() { - return( cam ); -} -int GetCamNum() { - return( camnum ); -} - -char *GetFileName() { - return( fileName ); -} -void SetFileName( const char *name, bool save ) { - strcpy( fileName, name ); - if ( save ) { - hasbeensaved = 1; + CCamera( int i ) { + cam = &camera[i]; + camnum = i; + Init(); } -} + ~CCamera(); -CCamera *GetNext() { - return( next ); -} - -CCamera *GetPrev() { - return( prev ); -} - -void SetNext( CCamera *camera ) { - next = camera; -} -void SetPrev( CCamera *camera ) { - prev = camera; -} - -int HasBeenSaved() { - return( hasbeensaved ); -} -void HasBeenModified() { - if ( hasbeensaved ) { - hasbeensaved = 2; + void Init() { + next = prev = NULL; + fileName[0] = '\0'; + hasbeensaved = 0; + } + + idCameraDef *GetCam() { + return( cam ); + } + int GetCamNum() { + return( camnum ); + } + + char *GetFileName() { + return( fileName ); + } + void SetFileName( const char *name, bool save ) { + strcpy( fileName, name ); + if ( save ) { + hasbeensaved = 1; + } + } + + CCamera *GetNext() { + return( next ); + } + + CCamera *GetPrev() { + return( prev ); + } + + void SetNext( CCamera *camera ) { + next = camera; + } + void SetPrev( CCamera *camera ) { + prev = camera; + } + + int HasBeenSaved() { + return( hasbeensaved ); + } + void HasBeenModified() { + if ( hasbeensaved ) { + hasbeensaved = 2; + } } -} protected: -idCameraDef *cam; -int camnum; -CCamera *next, *prev; -char fileName[PATH_MAX]; -int hasbeensaved; // 0:never saved 1:saved 2:saved, but modified + idCameraDef *cam; + int camnum; + CCamera *next, *prev; + char fileName[PATH_MAX]; + int hasbeensaved; // 0:never saved 1:saved 2:saved, but modified }; CCamera *AllocCam(); diff --git a/contrib/camera/dialogs.cpp b/contrib/camera/dialogs.cpp index dcfd13e9..28b607bc 100644 --- a/contrib/camera/dialogs.cpp +++ b/contrib/camera/dialogs.cpp @@ -327,9 +327,12 @@ static void RefreshEventList( void ){ for ( i = 0; i < GetCurrentCam()->GetCam()->numEvents(); i++ ) { char rowbuf[3][128], *row[3]; // FIXME: sort by time? - sprintf( rowbuf[0], "%li", GetCurrentCam()->GetCam()->getEvent( i )->getTime() ); row[0] = rowbuf[0]; - strncpy( rowbuf[1], GetCurrentCam()->GetCam()->getEvent( i )->typeStr(), sizeof( rowbuf[0] ) ); row[1] = rowbuf[1]; - strncpy( rowbuf[2], GetCurrentCam()->GetCam()->getEvent( i )->getParam(), sizeof( rowbuf[1] ) ); row[2] = rowbuf[2]; + sprintf( rowbuf[0], "%li", GetCurrentCam()->GetCam()->getEvent( i )->getTime() ); + row[0] = rowbuf[0]; + strncpy( rowbuf[1], GetCurrentCam()->GetCam()->getEvent( i )->typeStr(), sizeof( rowbuf[0] ) ); + row[1] = rowbuf[1]; + strncpy( rowbuf[2], GetCurrentCam()->GetCam()->getEvent( i )->getParam(), sizeof( rowbuf[1] ) ); + row[2] = rowbuf[2]; gtk_clist_append( GTK_CLIST( g_pEventsList ), row ); } @@ -1015,8 +1018,8 @@ GtkWidget *CreateCameraInspectorDialog( void ){ vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); // -------------------------- // @@ -1065,8 +1068,8 @@ GtkWidget *CreateCameraInspectorDialog( void ){ frame = gtk_frame_new( "Path and Target editing" ); gtk_widget_show( frame ); gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox ); @@ -1157,8 +1160,8 @@ GtkWidget *CreateCameraInspectorDialog( void ){ frame = gtk_frame_new( "Time" ); gtk_widget_show( frame ); gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox ); diff --git a/contrib/camera/listener.cpp b/contrib/camera/listener.cpp index b9f5fcf9..5216f8e4 100644 --- a/contrib/camera/listener.cpp +++ b/contrib/camera/listener.cpp @@ -67,15 +67,18 @@ bool CListener::OnMouseMove( unsigned int nFlags, double x, double y ){ switch ( m_vt ) { case XY: VectorSet( delta, click[0] - old_x, click[1] - old_y, 0 ); - old_x = click[0]; old_y = click[1]; + old_x = click[0]; + old_y = click[1]; break; case XZ: VectorSet( delta, click[0] - old_x, 0, click[2] - old_y ); - old_x = click[0]; old_y = click[2]; + old_x = click[0]; + old_y = click[2]; break; case YZ: VectorSet( delta, 0, click[1] - old_x, click[2] - old_y ); - old_x = click[1]; old_y = click[2]; + old_x = click[1]; + old_y = click[2]; break; } @@ -108,15 +111,21 @@ bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ){ switch ( m_vt ) { case XY: - old_x = org[0]; old_y = org[1]; org[2] = 64 * 1024; + old_x = org[0]; + old_y = org[1]; + org[2] = 64 * 1024; VectorSet( delta, 0, 0, -1 ); break; case XZ: - old_x = org[0]; old_y = org[2]; org[1] = 64 * 1024; + old_x = org[0]; + old_y = org[2]; + org[1] = 64 * 1024; VectorSet( delta, 0, -1, 0 ); break; case YZ: - old_x = org[1]; old_y = org[2]; org[0] = 64 * 1024; + old_x = org[1]; + old_y = org[2]; + org[0] = 64 * 1024; VectorSet( delta, -1, 0, 0 ); break; } diff --git a/contrib/camera/listener.h b/contrib/camera/listener.h index 13acd543..64f59361 100644 --- a/contrib/camera/listener.h +++ b/contrib/camera/listener.h @@ -27,47 +27,54 @@ class CListener : public IWindowListener { public: -bool OnMouseMove( guint32 nFlags, gdouble x, gdouble y ); -bool OnLButtonDown( guint32 nFlags, gdouble x, gdouble y ); -bool OnMButtonDown( guint32 nFlags, gdouble x, gdouble y ); -bool OnRButtonDown( guint32 nFlags, gdouble x, gdouble y ); -bool OnLButtonUp( guint32 nFlags, gdouble x, gdouble y ); -bool OnMButtonUp( guint32 nFlags, gdouble x, gdouble y ); -bool OnRButtonUp( guint32 nFlags, gdouble x, gdouble y ); -bool OnKeyPressed( char *s ) { return false; } -bool Paint() { return true; } -void Close() { } - -void UnRegister(); -void Register(); -CListener(); -virtual ~CListener(); - -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + bool OnMouseMove( guint32 nFlags, gdouble x, gdouble y ); + bool OnLButtonDown( guint32 nFlags, gdouble x, gdouble y ); + bool OnMButtonDown( guint32 nFlags, gdouble x, gdouble y ); + bool OnRButtonDown( guint32 nFlags, gdouble x, gdouble y ); + bool OnLButtonUp( guint32 nFlags, gdouble x, gdouble y ); + bool OnMButtonUp( guint32 nFlags, gdouble x, gdouble y ); + bool OnRButtonUp( guint32 nFlags, gdouble x, gdouble y ); + bool OnKeyPressed( char *s ) { + return false; } -} - -void SetViewType( VIEWTYPE vt ) { - if ( m_vt != vt ) { - oldValid = false; + bool Paint() { + return true; + } + void Close() { } + + void UnRegister(); + void Register(); + CListener(); + virtual ~CListener(); + + void IncRef() { + refCount++; + } + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } + } + + void SetViewType( VIEWTYPE vt ) { + if ( m_vt != vt ) { + oldValid = false; + } + m_vt = vt; } - m_vt = vt; -} private: -IXYWndWrapper *g_pXYWndWrapper; + IXYWndWrapper *g_pXYWndWrapper; -bool m_bHooked; -int refCount; -VIEWTYPE m_vt; + bool m_bHooked; + int refCount; + VIEWTYPE m_vt; // mouse button status -bool m_bLeftMBPressed, m_bRightMBPressed, m_bMiddleMBPressed; + bool m_bLeftMBPressed, m_bRightMBPressed, m_bMiddleMBPressed; // old mouse coordinates -bool oldValid; -gdouble old_x, old_y; + bool oldValid; + gdouble old_x, old_y; }; diff --git a/contrib/camera/misc.h b/contrib/camera/misc.h index 6e226d33..81dcc490 100644 --- a/contrib/camera/misc.h +++ b/contrib/camera/misc.h @@ -35,8 +35,8 @@ typedef int fileHandle_t; extern "C" { // command buffer -void Cbuf_AddText( const char *text ); -void Cbuf_Execute( void ); + void Cbuf_AddText( const char *text ); + void Cbuf_Execute( void ); // common #ifndef CDECL @@ -47,20 +47,20 @@ void Cbuf_Execute( void ); #endif #endif -void CDECL Com_Error( int level, const char *error, ... ); -void CDECL Com_Printf( const char *msg, ... ); -void CDECL Com_DPrintf( const char *msg, ... ); -void *Com_Allocate( int bytes ); -void Com_Dealloc( void *ptr ); + void CDECL Com_Error( int level, const char *error, ... ); + void CDECL Com_Printf( const char *msg, ... ); + void CDECL Com_DPrintf( const char *msg, ... ); + void *Com_Allocate( int bytes ); + void Com_Dealloc( void *ptr ); // filesystem -int FS_Read( void *buffer, int len, fileHandle_t f ); -int FS_Write( const void *buffer, int len, fileHandle_t h ); -int FS_ReadFile( const char *qpath, void **buffer ); -void FS_FreeFile( void *buffer ); -int FS_FOpenFileRead( const char *filename, fileHandle_t *file, bool uniqueFILE ); -fileHandle_t FS_FOpenFileWrite( const char *filename ); -void FS_FCloseFile( fileHandle_t f ); + int FS_Read( void *buffer, int len, fileHandle_t f ); + int FS_Write( const void *buffer, int len, fileHandle_t h ); + int FS_ReadFile( const char *qpath, void **buffer ); + void FS_FreeFile( void *buffer ); + int FS_FOpenFileRead( const char *filename, fileHandle_t *file, bool uniqueFILE ); + fileHandle_t FS_FOpenFileWrite( const char *filename ); + void FS_FCloseFile( fileHandle_t f ); } // vectors diff --git a/contrib/camera/renderer.h b/contrib/camera/renderer.h index b84680ba..291f9de4 100644 --- a/contrib/camera/renderer.h +++ b/contrib/camera/renderer.h @@ -26,25 +26,28 @@ class CRenderer : public IGL2DWindow, public IGL3DWindow { public: -CRenderer(); -virtual ~CRenderer(); + CRenderer(); + virtual ~CRenderer(); protected: -int refCount; + int refCount; public: -void Register(); -void UnRegister(); -void Initialize(); -void Draw2D( VIEWTYPE vt ); -void Draw3D(); + void Register(); + void UnRegister(); + void Initialize(); + void Draw2D( VIEWTYPE vt ); + void Draw3D(); -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + void IncRef() { + refCount++; + } + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } } -} -bool m_bHooked; + bool m_bHooked; }; diff --git a/contrib/gtkgensurf/bitmap.cpp b/contrib/gtkgensurf/bitmap.cpp index 2ca7e6b4..766267b8 100644 --- a/contrib/gtkgensurf/bitmap.cpp +++ b/contrib/gtkgensurf/bitmap.cpp @@ -116,84 +116,99 @@ static unsigned char* OpenBitmapFile(){ INVALID_FORMAT; } - rc = fread( (uint32_t*)&( filesize ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( filesize ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint16_t*)&( res1 ),2,1,fp ); m_bytesRead += 2; + rc = fread( (uint16_t*)&( res1 ),2,1,fp ); + m_bytesRead += 2; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint16_t*)&( res2 ),2,1,fp ); m_bytesRead += 2; + rc = fread( (uint16_t*)&( res2 ),2,1,fp ); + m_bytesRead += 2; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( pixoff ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( pixoff ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( bmisize ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( bmisize ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t *)&( bmWidth ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t *)&( bmWidth ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( bmHeight ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( bmHeight ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint16_t*)&( bmPlanes ),2,1,fp ); m_bytesRead += 2; + rc = fread( (uint16_t*)&( bmPlanes ),2,1,fp ); + m_bytesRead += 2; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint16_t*)&( bmBitsPixel ),2,1,fp ); m_bytesRead += 2; + rc = fread( (uint16_t*)&( bmBitsPixel ),2,1,fp ); + m_bytesRead += 2; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( compression ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( compression ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( sizeimage ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( sizeimage ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( xscale ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( xscale ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( yscale ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( yscale ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( colors ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( colors ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } - rc = fread( (uint32_t*)&( impcol ),4,1,fp ); m_bytesRead += 4; + rc = fread( (uint32_t*)&( impcol ),4,1,fp ); + m_bytesRead += 4; if ( rc != 1 ) { INVALID_FORMAT; } if ( bmBitsPixel != 8 ) { g_FuncTable.m_pfnMessageBox( g_pWnd, "This is not an 8-bit image. GenSurf can't use it.", - "Bitmap", eMB_OK, eMB_ICONWARNING ); + "Bitmap", eMB_OK, eMB_ICONWARNING ); fclose( fp ); return NULL; } @@ -321,7 +336,8 @@ static unsigned char* OpenBitmapFile(){ c1 = getc( fp ); for ( i = 0; i < c; x++, i++ ) { - *pp = c1; pp++; + *pp = c1; + pp++; } } else @@ -349,7 +365,8 @@ static unsigned char* OpenBitmapFile(){ for ( i = 0; i < c; x++, i++ ) { c1 = getc( fp ); - *pp = c1; pp++; + *pp = c1; + pp++; } if ( c & 1 ) { @@ -369,7 +386,8 @@ static unsigned char* OpenBitmapFile(){ c1 = getc( fp ); for ( i = 0; i < c; x++, i++ ) { - *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); pp++; + *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); + pp++; } } else @@ -399,7 +417,8 @@ static unsigned char* OpenBitmapFile(){ if ( ( i & 1 ) == 0 ) { c1 = getc( fp ); } - *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); pp++; + *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); + pp++; } if ( ( ( c & 3 ) == 1 ) || ( ( c & 3 ) == 2 ) ) { @@ -439,7 +458,7 @@ bool OpenBitmap(){ if ( g_pWnd ) { gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ), gbmp.name ); gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_reload" ) ), - strlen( gbmp.name ) ? TRUE : FALSE ); + strlen( gbmp.name ) ? TRUE : FALSE ); UpdatePreview( true ); } diff --git a/contrib/gtkgensurf/dec.cpp b/contrib/gtkgensurf/dec.cpp index 158a4302..9eb463c6 100644 --- a/contrib/gtkgensurf/dec.cpp +++ b/contrib/gtkgensurf/dec.cpp @@ -135,18 +135,18 @@ void MakeDecimatedMap( int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri ){ for ( j = 0, Node[i].tri = -1; ( j < NumTris[0] ) && ( Node[i].tri == -1 ); j++ ) { if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2], - Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2] ) < 0. ) { + Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2], + Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2] ) < 0. ) { continue; } if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2], - Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2] ) < 0. ) { + Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2], + Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2] ) < 0. ) { continue; } if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2], - Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2] ) < 0. ) { + Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2], + Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2] ) < 0. ) { continue; } Node[i].tri = j; @@ -157,22 +157,22 @@ void MakeDecimatedMap( int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri ){ SetCursor(ghCursorCurrent); */ g_FuncTable.m_pfnMessageBox( g_pRadiantWnd, - "Error: Couldn't find the triangle bounding a point.", - "Decimation Error", eMB_OK, eMB_ICONWARNING ); + "Error: Couldn't find the triangle bounding a point.", + "Decimation Error", eMB_OK, eMB_ICONWARNING ); return; } if ( !Tri[Node[i].tri].flag ) { PlaneFromPoints( Node[Tri[Node[i].tri].v[0]].p, - Node[Tri[Node[i].tri].v[1]].p, - Node[Tri[Node[i].tri].v[2]].p, - &Tri[Node[i].tri].plane ); + Node[Tri[Node[i].tri].v[1]].p, + Node[Tri[Node[i].tri].v[2]].p, + &Tri[Node[i].tri].plane ); Tri[Node[i].tri].flag = 1; } Node[i].error = - Node[i].p[j0] - ( Tri[Node[i].tri].plane.dist - - Tri[Node[i].tri].plane.normal[j1] * Node[i].p[j1] - - Tri[Node[i].tri].plane.normal[j2] * Node[i].p[j2] ) / - Tri[Node[i].tri].plane.normal[j0]; + Node[i].p[j0] - ( Tri[Node[i].tri].plane.dist - + Tri[Node[i].tri].plane.normal[j1] * Node[i].p[j1] - + Tri[Node[i].tri].plane.normal[j2] * Node[i].p[j2] ) / + Tri[Node[i].tri].plane.normal[j0]; biggesterror = max( biggesterror,Absolute( Node[i].error ) ); } if ( biggesterror == 0 ) { @@ -249,18 +249,18 @@ void MakeDecimatedMap( int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri ){ for ( j = 0; j < NumTris[0] && Node[i].tri == -1; j++ ) { if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2], - Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2] ) < 0. ) { + Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2], + Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2] ) < 0. ) { continue; } if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2], - Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2] ) < 0. ) { + Node[Tri[j].v[1]].p[j1],Node[Tri[j].v[1]].p[j2], + Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2] ) < 0. ) { continue; } if ( side( Node[i].p[j1], Node[i].p[j2], - Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2], - Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2] ) < 0. ) { + Node[Tri[j].v[2]].p[j1],Node[Tri[j].v[2]].p[j2], + Node[Tri[j].v[0]].p[j1],Node[Tri[j].v[0]].p[j2] ) < 0. ) { continue; } Node[i].tri = j; @@ -271,22 +271,22 @@ void MakeDecimatedMap( int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri ){ SetCursor(ghCursorCurrent); */ g_FuncTable.m_pfnMessageBox( g_pRadiantWnd, - "Error: Couldn't find the triangle bounding a point.", - "Decimation Error", eMB_OK, eMB_ICONWARNING ); + "Error: Couldn't find the triangle bounding a point.", + "Decimation Error", eMB_OK, eMB_ICONWARNING ); return; } if ( !Tri[Node[i].tri].flag ) { PlaneFromPoints( Node[Tri[Node[i].tri].v[0]].p, - Node[Tri[Node[i].tri].v[1]].p, - Node[Tri[Node[i].tri].v[2]].p, - &Tri[Node[i].tri].plane ); + Node[Tri[Node[i].tri].v[1]].p, + Node[Tri[Node[i].tri].v[2]].p, + &Tri[Node[i].tri].plane ); Tri[Node[i].tri].flag = 1; } Node[i].error = - Node[i].p[j0] - ( Tri[Node[i].tri].plane.dist - - Tri[Node[i].tri].plane.normal[j1] * Node[i].p[j1] - - Tri[Node[i].tri].plane.normal[j2] * Node[i].p[j2] ) / - Tri[Node[i].tri].plane.normal[j0]; + Node[i].p[j0] - ( Tri[Node[i].tri].plane.dist - + Tri[Node[i].tri].plane.normal[j1] * Node[i].p[j1] - + Tri[Node[i].tri].plane.normal[j2] * Node[i].p[j2] ) / + Tri[Node[i].tri].plane.normal[j0]; if ( Absolute( Node[i].error ) > 0.5 ) { NumNodesUsed++; Node[i].used++; @@ -756,7 +756,7 @@ int compare( TRITABLE *t1, TRITABLE *t2 ){ } void MakeBrushes( int NumTris, NODE *Node, TRI *Tri,bool surf, - int offset,char *texture0, char *texture1, char *texture2 ){ + int offset,char *texture0, char *texture1, char *texture2 ){ extern double backface; BRUSH brush; int contents; @@ -1016,7 +1016,7 @@ void MakeBrushes( int NumTris, NODE *Node, TRI *Tri,bool surf, for ( j = 0; j < 5; j++ ) { strcpy( brush.face[j].texture, - ( strlen( texture1 ) ? texture1 : texture0 ) ); + ( strlen( texture1 ) ? texture1 : texture0 ) ); brush.face[j].Shift[0] = (float)TexOffset[0]; brush.face[j].Shift[1] = (float)TexOffset[1]; brush.face[j].Rotate = 0.; @@ -1205,8 +1205,8 @@ void MapOut( int NumNodes,int NumTris, NODE *Node, TRI *Tri ){ for ( t = 0; t < 3 && OK; t++ ) { s[t] = side( Node[q[h0]].p[j1],Node[q[h0]].p[j2], - Node[q[h1]].p[j1],Node[q[h1]].p[j2], - Node[Tri[k].v[t]].p[j1],Node[Tri[k].v[t]].p[j2] ); + Node[q[h1]].p[j1],Node[q[h1]].p[j2], + Node[Tri[k].v[t]].p[j1],Node[Tri[k].v[t]].p[j2] ); } if ( ( s[1] > 0 || s[2] > 0 ) && s[0] < 0 ) { OK = 0; diff --git a/contrib/gtkgensurf/face.cpp b/contrib/gtkgensurf/face.cpp index 77ce7dec..d24c4b64 100644 --- a/contrib/gtkgensurf/face.cpp +++ b/contrib/gtkgensurf/face.cpp @@ -41,8 +41,8 @@ void PlaneFromPoints( float *p0, float *p1, float *p2, PLANE *plane ){ plane->normal[2] = t1[0] * t2[1] - t1[1] * t2[0]; length = (vec)( sqrt( plane->normal[0] * plane->normal[0] + - plane->normal[1] * plane->normal[1] + - plane->normal[2] * plane->normal[2] ) ); + plane->normal[1] * plane->normal[1] + + plane->normal[2] * plane->normal[2] ) ); if ( length == 0 ) { VectorClear( plane->normal ); } @@ -263,7 +263,7 @@ void ChopWindingInPlace( MY_WINDING **inout, vec3 normal, vec dist, vec epsilon dot = dists[i] / ( dists[i] - dists[i + 1] ); for ( j = 0 ; j < 3 ; j++ ) - { // avoid round off error when possible + { // avoid round off error when possible if ( normal[j] == 1 ) { mid[j] = dist; } diff --git a/contrib/gtkgensurf/font.cpp b/contrib/gtkgensurf/font.cpp index 35004bfd..69803dce 100644 --- a/contrib/gtkgensurf/font.cpp +++ b/contrib/gtkgensurf/font.cpp @@ -232,7 +232,7 @@ void texfont_init(){ } g_GLTable.m_pfn_qglTexImage2D( GL_TEXTURE_2D, 0, GL_INTENSITY4, 128, 128, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, buf ); + GL_LUMINANCE, GL_UNSIGNED_BYTE, buf ); free( buf ); } diff --git a/contrib/gtkgensurf/gendlgs.cpp b/contrib/gtkgensurf/gendlgs.cpp index ed72569c..4522c494 100644 --- a/contrib/gtkgensurf/gendlgs.cpp +++ b/contrib/gtkgensurf/gendlgs.cpp @@ -89,14 +89,14 @@ void About( GtkWidget *parent ){ // leo: I'm too lazy to create a nice about box // ^Fishman - I am lazy too :P. g_FuncTable.m_pfnMessageBox( parent, "GtkGenSurf 1.05\n\n" - "Original version\n" - "David Hyde (rascal@vicksburg.com)\n\n" - "Porting\n" - "Leonardo Zide (leo@lokigames.com)\n\n" - "Enhancements\n" - "Pablo Zurita (pablo@qeradiant.com)\n" - "Hydra (hydra@hydras-world.com)", - "About GtkGenSurf", eMB_OK ); + "Original version\n" + "David Hyde (rascal@vicksburg.com)\n\n" + "Porting\n" + "Leonardo Zide (leo@lokigames.com)\n\n" + "Enhancements\n" + "Pablo Zurita (pablo@qeradiant.com)\n" + "Hydra (hydra@hydras-world.com)", + "About GtkGenSurf", eMB_OK ); } // ============================================================================= @@ -136,8 +136,8 @@ static void SetupControls(){ ENABLE_WIDGET( "bmp_text3", FALSE ); ENABLE_WIDGET( "bmp_reload", FALSE ); gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_note" ) ), - "These options are disabled unless \"From Bitmap\"\n" - "is selected as the Waveform on the General tab." ); + "These options are disabled unless \"From Bitmap\"\n" + "is selected as the Waveform on the General tab." ); } else { @@ -150,9 +150,9 @@ static void SetupControls(){ ENABLE_WIDGET( "bmp_text3", TRUE ); ENABLE_WIDGET( "bmp_reload", strlen( gbmp.name ) != 0 ); gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_note" ) ), - "GenSurf works only with 8-bit bitmaps. Color indices are\n" - "mapped to values for each vertex. Generally, gray scale\n" - "images are stored with black as color 0, white as color 255." ); + "GenSurf works only with 8-bit bitmaps. Color indices are\n" + "mapped to values for each vertex. Generally, gray scale\n" + "images are stored with black as color 0, white as color 255." ); } break; @@ -275,7 +275,7 @@ static void SetDlgValues( int tab ){ gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( plane_radios[Plane] ), TRUE ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( wave_radios[WaveType] ), TRUE ); gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "random" ) ), - RandomSeed ); + RandomSeed ); sprintf( Text, RForm, WaveLength ); gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "wavelength" ) ), Text ); sprintf( Text, RForm, Amplitude ); @@ -283,7 +283,7 @@ static void SetDlgValues( int tab ){ sprintf( Text, RForm, Roughness ); gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "roughness" ) ), Text ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data - ( G_OBJECT( g_pWnd ), "main_antialiasing" ) ), Antialiasing ); + ( G_OBJECT( g_pWnd ), "main_antialiasing" ) ), Antialiasing ); break; case EXTENTS_TAB: @@ -308,11 +308,11 @@ static void SetDlgValues( int tab ){ gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "sp" ) ), SP ); // ^Fishman - Snap to grid. gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data - ( G_OBJECT( g_pWnd ), "linearborder" ) ), FixBorders ); + ( G_OBJECT( g_pWnd ), "linearborder" ) ), FixBorders ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data - ( G_OBJECT( g_pWnd ), "use_patches" ) ), UsePatches ); + ( G_OBJECT( g_pWnd ), "use_patches" ) ), UsePatches ); gtk_adjustment_set_value( GTK_ADJUSTMENT( g_object_get_data( G_OBJECT( g_pWnd ), "decimate_adj" ) ), - Decimate ); + Decimate ); if ( Game == QUAKE3 && UsePatches ) { gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "decimate" ) ), FALSE ); @@ -395,7 +395,7 @@ static void SetDlgValues( int tab ){ gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texture2" ) ), Texture[Game][1] ); gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texture3" ) ), Texture[Game][2] ); gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "tex_slant" ) ), - SlantAngle ); + SlantAngle ); sprintf( Text,RForm,TexOffset[0] ); gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texoffsetx" ) ), Text ); sprintf( Text,RForm,TexOffset[1] ); @@ -586,7 +586,7 @@ static void ReadDlgValues( int tab ){ } else{ SendDlgItemMessage( hwndDisplay, DLG_TEX_LIST1, CB_GETLBTEXT, i, - (LPARAM)(LPCSTR)Texture[Game][0] ); + (LPARAM)(LPCSTR)Texture[Game][0] ); } i = SendDlgItemMessage( hwndDisplay, DLG_TEX_LIST2, CB_GETCURSEL, 0, 0 ); @@ -595,7 +595,7 @@ static void ReadDlgValues( int tab ){ } else{ SendDlgItemMessage( hwndDisplay, DLG_TEX_LIST2, CB_GETLBTEXT, i, - (LPARAM)(LPCSTR)Texture[Game][1] ); + (LPARAM)(LPCSTR)Texture[Game][1] ); } i = SendDlgItemMessage( hwndDisplay, DLG_TEX_LIST3, CB_GETCURSEL, 0, 0 ); @@ -604,7 +604,7 @@ static void ReadDlgValues( int tab ){ } else{ SendDlgItemMessage( hwndDisplay, DLG_TEX_LIST3, CB_GETLBTEXT, i, - (LPARAM)(LPCSTR)Texture[Game][2] ); + (LPARAM)(LPCSTR)Texture[Game][2] ); } } else @@ -645,7 +645,7 @@ static void switch_page( GtkNotebook *notebook, GtkWidget *page, guint page_num, if ( page_num == FIXPOINTS_TAB ) { OldPreview = Preview; gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), - "main_preview" ) ), TRUE ); + "main_preview" ) ), TRUE ); VertexMode = 1; UpdatePreview( true ); NumVerticesSelected = 0; @@ -654,7 +654,7 @@ static void switch_page( GtkNotebook *notebook, GtkWidget *page, guint page_num, if ( current_tab == FIXPOINTS_TAB ) { if ( !OldPreview ) { gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), - "main_preview" ) ), FALSE ); + "main_preview" ) ), FALSE ); } VertexMode = 0; UpdatePreview( true ); @@ -737,16 +737,16 @@ static void main_go( GtkWidget *widget, gpointer data ){ if ( Hll >= Hur ) { g_FuncTable.m_pfnMessageBox( g_pWnd, "The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); + "the corresponding \"upper-right\" values in " + "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); gtk_notebook_set_current_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); return; } if ( Vll >= Vur ) { g_FuncTable.m_pfnMessageBox( g_pWnd,"The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); + "the corresponding \"upper-right\" values in " + "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); gtk_notebook_set_current_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); return; } @@ -757,14 +757,14 @@ static void main_go( GtkWidget *widget, gpointer data ){ return; } -/* if (Decimate>0 && GimpHints!=0) - { - MessageBox(hwnd,"You've elected to use a decimated grid and gimp's non-detail hint brushes. " - "This combination usually produces bizarre visual errors in the game, " - "so GenSurf has turned off the hint brush option.", - "GenSurf",eMB_ICONWARNING); - GimpHints = 0; - } */ +/* if (Decimate>0 && GimpHints!=0) + { + MessageBox(hwnd,"You've elected to use a decimated grid and gimp's non-detail hint brushes. " + "This combination usually produces bizarre visual errors in the game, " + "so GenSurf has turned off the hint brush option.", + "GenSurf",eMB_ICONWARNING); + GimpHints = 0; + } */ gtk_widget_hide( g_pWnd ); if ( g_pWndPreview ) { @@ -930,7 +930,7 @@ static gint fix_value_entryfocusout( GtkWidget* widget, GdkEventFocus *event, gp if ( i < -65536 || i > 65536 ) { gdk_beep(); g_FuncTable.m_pfnMessageBox( g_pWnd, "The value must be between -65536 and 65536, inclusive.", - "GenSurf", eMB_OK, eMB_ICONWARNING ); + "GenSurf", eMB_OK, eMB_ICONWARNING ); sprintf( Text, "%d", (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); gtk_entry_set_text( GTK_ENTRY( widget ), Text ); gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( widget ) ), widget ); @@ -940,7 +940,7 @@ static gint fix_value_entryfocusout( GtkWidget* widget, GdkEventFocus *event, gp xyz[Vertex[k].i][Vertex[k].j].fixed_value = i; gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "fix_value" ) ), - (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); + (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); UpdatePreview( true ); } return FALSE; @@ -1025,7 +1025,7 @@ void vertex_selected(){ } gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "fix_value" ) ), - (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); + (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); sprintf( Text,"%d",(int)xyz[Vertex[0].i][Vertex[0].j].range ); gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "fix_range" ) ), Text ); @@ -1097,160 +1097,160 @@ static gint doublevariable_entryfocusout( GtkWidget* widget, GdkEventFocus* even void create_tooltips(){ // Main gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "go" ) ), - "Accept all input and generate a surface in Q3Radiant" ); + "Accept all input and generate a surface in Q3Radiant" ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "open" ) ), - "Open a previously saved GenSurf settings file." ); + "Open a previously saved GenSurf settings file." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "save" ) ), - "Save all settings to a file." ); + "Save all settings to a file." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "defaults" ) ), - "Restore default values from DEFAULTS.SRF. If this file does not exist, GenSurf " - "initializes all input parameters to reasonable values. You can create your own " - "default surface by setting all parameters to your liking, then saving a settings " - "file as DEFAULTS.SRF with the Save As button." ); + "Restore default values from DEFAULTS.SRF. If this file does not exist, GenSurf " + "initializes all input parameters to reasonable values. You can create your own " + "default surface by setting all parameters to your liking, then saving a settings " + "file as DEFAULTS.SRF with the Save As button." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "main_preview" ) ), - "View a wire-frame representation of the surface" ); + "View a wire-frame representation of the surface" ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "main_antialiasing" ) ), - "The lines in the preview window are antialiased for better quality" ); + "The lines in the preview window are antialiased for better quality" ); // General tab gtk_widget_set_tooltip_text( GTK_WIDGET( wave_radios[0] ), - "Builds a surface with alternating hills and valleys. Uses the general form Z=cos(X) " - "x sin(Y)" ); + "Builds a surface with alternating hills and valleys. Uses the general form Z=cos(X) " + "x sin(Y)" ); gtk_widget_set_tooltip_text( GTK_WIDGET( wave_radios[1] ), - "Builds a surface with ridges parallel to the vertical axis." ); + "Builds a surface with ridges parallel to the vertical axis." ); gtk_widget_set_tooltip_text( GTK_WIDGET( wave_radios[2] ), - "Builds a surface with ridges parallel to the horizontal axis." ); + "Builds a surface with ridges parallel to the horizontal axis." ); gtk_widget_set_tooltip_text( GTK_WIDGET( wave_radios[3] ), - "Builds a map from a bitmap image representing a contour plot. Click the \"Bitmap\" " - "tab to select the image. GenSurf only supports 256-color (8 bit) " - "bitmaps. GenSurf will work with any 256-color bitmap, but gray scale bitmaps are a bit " - "more intuitive." ); + "Builds a map from a bitmap image representing a contour plot. Click the \"Bitmap\" " + "tab to select the image. GenSurf only supports 256-color (8 bit) " + "bitmaps. GenSurf will work with any 256-color bitmap, but gray scale bitmaps are a bit " + "more intuitive." ); gtk_widget_set_tooltip_text( GTK_WIDGET( wave_radios[4] ), - "Builds a random surface using the Plasma Cloud technique. Variance is controlled " - "by the Roughness input. To build a surface with completely random values not " - "dependent on neighboring vertices, use one of the other waveforms with 0 amplitude." ); + "Builds a random surface using the Plasma Cloud technique. Variance is controlled " + "by the Roughness input. To build a surface with completely random values not " + "dependent on neighboring vertices, use one of the other waveforms with 0 amplitude." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "wavelength" ) ), - "Enter the wavelength (distance between crests). NOTE: Wavelengths equal to the grid " - "size or 2 times the grid size will result in 0 amplitudes. For best results, the " - "wavelength value should be at least 4 times the grid size (extents divided by the " - "number of divisions" ); + "Enter the wavelength (distance between crests). NOTE: Wavelengths equal to the grid " + "size or 2 times the grid size will result in 0 amplitudes. For best results, the " + "wavelength value should be at least 4 times the grid size (extents divided by the " + "number of divisions" ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "amplitude" ) ), - "Enter the height of hills/ridges." ); + "Enter the height of hills/ridges." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "roughness" ) ), - "Enter the roughness value (noise) for the surface. For fractal surfaces, this value " - "is used as a variance in the fractal calculations." ); + "Enter the roughness value (noise) for the surface. For fractal surfaces, this value " + "is used as a variance in the fractal calculations." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "random" ) ), - "Seed value for the pseudo-random number generator." ); + "Seed value for the pseudo-random number generator." ); // Extents tab gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "hmin" ) ), - "Minimum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction." ); + "Minimum horizontal coordinate of the surface, i.e. X for a surface parallel to " + "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "hmax" ) ), - "Maximum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction." ); + "Maximum horizontal coordinate of the surface, i.e. X for a surface parallel to " + "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "vmin" ) ), - "Minimum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction." ); + "Minimum vertical coordinate of the surface, i.e. Y for a surface parallel to " + "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "vmax" ) ), - "Maximum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction." ); + "Maximum vertical coordinate of the surface, i.e. Y for a surface parallel to " + "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "nh" ) ), - "Number of divisions in the horizontal direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction." ); + "Number of divisions in the horizontal direction. For best results, the extents " + "in a given direction should be evenly divisible by the number of divisions in " + "that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "nv" ) ), - "Number of divisions in the vertical direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction." ); + "Number of divisions in the vertical direction. For best results, the extents " + "in a given direction should be evenly divisible by the number of divisions in " + "that direction." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "use_patches" ) ), - "Produce one or more curved patches in the shape of your selected surface rather " - "than producing solid brushes. Depending on the size of your surface (and the " - "user's graphic detail settings, which you cannot control), curved surfaces will " - "be represented in the game by a very large number of polygons. Read the warnings " - "concerning curved surfaces on the GenSurf web page before using this feature." ); + "Produce one or more curved patches in the shape of your selected surface rather " + "than producing solid brushes. Depending on the size of your surface (and the " + "user's graphic detail settings, which you cannot control), curved surfaces will " + "be represented in the game by a very large number of polygons. Read the warnings " + "concerning curved surfaces on the GenSurf web page before using this feature." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "decimate" ) ), - "Use the slider to control the number of vertices discarded by GenSurf. For many " - "surfaces, you can produce roughly the same shape surface with a high decimation " - "value. This will generally result in a map with lower polygon counts (and better " - "in-game performance). However, this feature should NOT be used for large terrain " - "surfaces in Q3" ); + "Use the slider to control the number of vertices discarded by GenSurf. For many " + "surfaces, you can produce roughly the same shape surface with a high decimation " + "value. This will generally result in a map with lower polygon counts (and better " + "in-game performance). However, this feature should NOT be used for large terrain " + "surfaces in Q3" ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z00" ) ), - "Enter the height of the surface at the lower left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked." ); + "Enter the height of the surface at the lower left corner. This value will likely " + "be modified unless \"Linear Borders\" is checked." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z01" ) ), - "Enter the height of the surface at the upper left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked." ); + "Enter the height of the surface at the upper left corner. This value will likely " + "be modified unless \"Linear Borders\" is checked." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z10" ) ), - "Enter the height of the surface at the lower right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked." ); + "Enter the height of the surface at the lower right corner. This value will likely " + "be modified unless \"Linear Borders\" is checked." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z11" ) ), - "Enter the height of the surface at the upper right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked." ); + "Enter the height of the surface at the upper right corner. This value will likely " + "be modified unless \"Linear Borders\" is checked." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "linearborder" ) ), - "Restrict the edges of the surface to a straight line. This will help match up " - "brush edges if you drop this surface into another map." ); + "Restrict the edges of the surface to a straight line. This will help match up " + "brush edges if you drop this surface into another map." ); // Bitmap tab gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ), - "Type the name of an 8-bit bitmap image file, or click Browse to select an image " - "from a list of those available on your system." ); + "Type the name of an 8-bit bitmap image file, or click Browse to select an image " + "from a list of those available on your system." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file_browse" ) ), - "Select a bitmap image file from a list of those available on your system." ); + "Select a bitmap image file from a list of those available on your system." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_reload" ) ), - "Reload the selected bitmap file after making changes in an external image editor." ); + "Reload the selected bitmap file after making changes in an external image editor." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_black" ) ), - "Enter the value corresponding to color index 0 in the bitmap file. For gray scale " - "images, color 0 is normally black." ); + "Enter the value corresponding to color index 0 in the bitmap file. For gray scale " + "images, color 0 is normally black." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_white" ) ), - "Enter the value corresponding to color index 255 in the bitmap file. For gray scale " - "images, color 255 is normally white." ); + "Enter the value corresponding to color index 255 in the bitmap file. For gray scale " + "images, color 255 is normally white." ); // Fixpoints tab gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_value" ) ), - "Enter a value for the selected vertex. This value will not be adjusted when applying " - "a waveform or roughness to the surface. Unlock this vertex (so that it will be " - "adjusted normally) by clicking \"Free\". This vertex will influence vertices within " - "the \"Range affected\" of this vertex." ); + "Enter a value for the selected vertex. This value will not be adjusted when applying " + "a waveform or roughness to the surface. Unlock this vertex (so that it will be " + "adjusted normally) by clicking \"Free\". This vertex will influence vertices within " + "the \"Range affected\" of this vertex." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_range" ) ), - "Enter the range away from the selected vertex that other vertices will be affected. " - "Use 0 if you don't want other vertices to be influenced by the currently selected " - "one. Note: this box is disabled if you've chosen the fractal generator, as it uses " - "a completely different method for determining values." ); + "Enter the range away from the selected vertex that other vertices will be affected. " + "Use 0 if you don't want other vertices to be influenced by the currently selected " + "one. Note: this box is disabled if you've chosen the fractal generator, as it uses " + "a completely different method for determining values." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_rate" ) ), - "Enter a rate of change for the surface affected by the fixed value. 0 gives a smooth " - "sinusoidal curve, values less than 0 give progressively sharper spikes, and values " - "greater than 0 take on a square shape. Values less than -30 or greater than 30 are " - "set to -30 and 30, respectively. Note that this entry will have no effect unless " - "you also specify a \"range affected\"." ); + "Enter a rate of change for the surface affected by the fixed value. 0 gives a smooth " + "sinusoidal curve, values less than 0 give progressively sharper spikes, and values " + "greater than 0 take on a square shape. Values less than -30 or greater than 30 are " + "set to -30 and 30, respectively. Note that this entry will have no effect unless " + "you also specify a \"range affected\"." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_free" ) ), - "Click this to free (unlock the value of) the currently selected vertex." ); + "Click this to free (unlock the value of) the currently selected vertex." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_freeall" ) ), - "Click this to free (unlock the values of) all vertices." ); + "Click this to free (unlock the values of) all vertices." ); // Texture tab gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture1" ) ), - "Enter the name of the texture or shader used for the surface faces." ); + "Enter the name of the texture or shader used for the surface faces." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture2" ) ), - "Enter the name of the texture or shader used for faces other than the surface. Under " - "normal circumstances this should be \"common/caulk\"" ); + "Enter the name of the texture or shader used for faces other than the surface. Under " + "normal circumstances this should be \"common/caulk\"" ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture3" ) ), - "Enter the name of the texture or shader used for \"steep\" surface faces, where \"steep\" " - "is the angle specified below. If this entry is left blank or if the \"steep\" angle is 0, " - "all surface faces will use the texture specified by \"Surface\"." ); + "Enter the name of the texture or shader used for \"steep\" surface faces, where \"steep\" " + "is the angle specified below. If this entry is left blank or if the \"steep\" angle is 0, " + "all surface faces will use the texture specified by \"Surface\"." ); gtk_widget_set_tooltip_text( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "detail" ) ), - "Check this box to use the detail content property on the generated brushes. Compile " - "times will be considerably shorter if the detail property is used, though the surface " - "will not block visibility at all. If you use the detail property, you should make sure " - "that \"common/caulk\" is used for the non-surface faces, or the polygon count will be " - "much higher than necessary." ); + "Check this box to use the detail content property on the generated brushes. Compile " + "times will be considerably shorter if the detail property is used, though the surface " + "will not block visibility at all. If you use the detail property, you should make sure " + "that \"common/caulk\" is used for the non-surface faces, or the polygon count will be " + "much higher than necessary." ); } // ============================================================================= @@ -1263,9 +1263,11 @@ GtkWidget* create_main_dialog(){ int i; const char *games[] = { "Quake 2", "Half-Life", "SiN", "Heretic 2", "Kingpin", "Genesis3D", "Quake 3 Arena" }; const char *waveforms[] = { "Alternating hill/valley", "Cylindrical left-to-right", "Cylindrical top-to-bottom", - "From bitmap", "Fractal" }; + "From bitmap", "Fractal" + }; const char *orientations[] = { "Ground surface", "Ceiling", "Wall facing 0", "Wall facing 90", - "Wall facing 180","Wall facing 270" }; + "Wall facing 180","Wall facing 270" + }; g_pWnd = dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( dlg ), gszCaption ); @@ -1282,7 +1284,7 @@ GtkWidget* create_main_dialog(){ gtk_widget_show( notebook ); gtk_box_pack_start( GTK_BOX( hbox ), notebook, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( notebook ), "switch_page", - G_CALLBACK( switch_page ), NULL ); + G_CALLBACK( switch_page ), NULL ); gtk_notebook_set_tab_pos( GTK_NOTEBOOK( notebook ), GTK_POS_TOP ); g_object_set_data( G_OBJECT( dlg ), "notebook", notebook ); @@ -1299,8 +1301,8 @@ GtkWidget* create_main_dialog(){ frame = gtk_frame_new( "Game" ); gtk_widget_show( frame ); gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( TRUE, 5 ); gtk_widget_show( vbox ); @@ -1319,8 +1321,8 @@ GtkWidget* create_main_dialog(){ frame = gtk_frame_new( "Waveform" ); gtk_widget_show( frame ); gtk_table_attach( GTK_TABLE( table ), frame, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( TRUE, 5 ); gtk_widget_show( vbox ); @@ -1339,8 +1341,8 @@ GtkWidget* create_main_dialog(){ frame = gtk_frame_new( "Orientation" ); gtk_widget_show( frame ); gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( TRUE, 5 ); gtk_widget_show( vbox ); @@ -1361,46 +1363,46 @@ GtkWidget* create_main_dialog(){ gtk_table_set_row_spacings( GTK_TABLE( table2 ), 5 ); gtk_table_set_col_spacings( GTK_TABLE( table2 ), 5 ); gtk_table_attach( GTK_TABLE( table ), table2, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); label = gtk_label_new( "Wavelength:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); label = gtk_label_new( "Max. amplitude:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); label = gtk_label_new( "Roughness:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); label = gtk_label_new( "Random seed:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 3, 4, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "wavelength", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &WaveLength ); @@ -1408,8 +1410,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "amplitude", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Amplitude ); @@ -1417,8 +1419,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "roughness", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Roughness ); @@ -1428,8 +1430,8 @@ GtkWidget* create_main_dialog(){ spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table2 ), spin, 1, 2, 3, 4, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "random", spin ); @@ -1459,48 +1461,48 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "X:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "hmin_text", label ); label = gtk_label_new( "X:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "hmax_text", label ); label = gtk_label_new( "Y:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "vmin_text", label ); label = gtk_label_new( "Y:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "vmax_text", label ); label = gtk_label_new( "Lower-left" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); label = gtk_label_new( "Upper-right" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "hmin", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Hll ); @@ -1508,8 +1510,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "hmax", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Hur ); @@ -1517,8 +1519,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "vmin", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Vll ); @@ -1526,8 +1528,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "vmax", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Vur ); @@ -1546,15 +1548,15 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "X:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "nh_text", label ); label = gtk_label_new( "Y:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "nv_text", label ); adj = gtk_adjustment_new( 8, 1, MAX_ROWS, 1, 10, 0 ); @@ -1562,8 +1564,8 @@ GtkWidget* create_main_dialog(){ spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "nh", spin ); @@ -1572,8 +1574,8 @@ GtkWidget* create_main_dialog(){ spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "nv", spin ); @@ -1630,32 +1632,32 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Upper-left:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); label = gtk_label_new( "Lower-left:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); label = gtk_label_new( "Upper-right:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); label = gtk_label_new( "Lower-right:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "z01", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z01 ); @@ -1663,8 +1665,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "z00", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z00 ); @@ -1672,8 +1674,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "z11", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z11 ); @@ -1681,8 +1683,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 50, -1 ); g_object_set_data( G_OBJECT( dlg ), "z10", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z10 ); @@ -1690,8 +1692,8 @@ GtkWidget* create_main_dialog(){ check = gtk_check_button_new_with_label( "Linear borders" ); gtk_widget_show( check ); gtk_table_attach( GTK_TABLE( table ), check, 0, 4, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "linearborder", check ); g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( extents_linearborder ), NULL ); @@ -1718,23 +1720,23 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Filename:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "bmp_text1", label ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "bmp_file", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( bitmap_file_entryfocusout ), NULL ); hbox2 = gtk_hbox_new( TRUE, 5 ); gtk_widget_show( hbox2 ); gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); button = gtk_button_new_with_label( "Browse..." ); gtk_widget_show( button ); @@ -1760,8 +1762,8 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Map color 0 to:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "bmp_text2", label ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); @@ -1769,8 +1771,8 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Map color 255 to:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); g_object_set_data( G_OBJECT( dlg ), "bmp_text3", label ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); @@ -1778,8 +1780,8 @@ GtkWidget* create_main_dialog(){ hbox2 = gtk_hbox_new( FALSE, 5 ); gtk_widget_show( hbox2 ); gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); entry = gtk_entry_new(); gtk_widget_show( entry ); @@ -1791,8 +1793,8 @@ GtkWidget* create_main_dialog(){ hbox2 = gtk_hbox_new( FALSE, 5 ); gtk_widget_show( hbox2 ); gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); entry = gtk_entry_new(); gtk_widget_show( entry ); @@ -1810,11 +1812,11 @@ GtkWidget* create_main_dialog(){ gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), vbox, label ); label = gtk_label_new( "Click on a vertex in the lower half of the preview window,\n" - "then use the arrow keys or text box to assign a value.\n" - "Use Ctrl+Click to select multiple vertices/toggle a\n" - "selection. Use Shift+Click to select a range of vertices.\n\n" - "Click \"Free\" to unlock a vertex. Vertices within \"Range\n" - "affected\" will be influenced by this vertex." ); + "then use the arrow keys or text box to assign a value.\n" + "Use Ctrl+Click to select multiple vertices/toggle a\n" + "selection. Use Shift+Click to select a range of vertices.\n\n" + "Click \"Free\" to unlock a vertex. Vertices within \"Range\n" + "affected\" will be influenced by this vertex." ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, TRUE, 0 ); @@ -1828,24 +1830,24 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Value:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); g_object_set_data( G_OBJECT( dlg ), "fix_value_text", label ); label = gtk_label_new( "Range affected:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); g_object_set_data( G_OBJECT( dlg ), "fix_range_text", label ); label = gtk_label_new( "Rate of change:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); g_object_set_data( G_OBJECT( dlg ), "fix_rate_text", label ); @@ -1854,8 +1856,8 @@ GtkWidget* create_main_dialog(){ spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( GTK_EXPAND ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_EXPAND ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "fix_value", spin ); g_signal_connect( G_OBJECT( spin ), "focus_out_event", G_CALLBACK( fix_value_entryfocusout ), NULL ); @@ -1863,8 +1865,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "fix_range", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( fix_range_entryfocusout ), NULL ); @@ -1872,8 +1874,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "fix_rate", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( fix_rate_entryfocusout ), NULL ); @@ -1881,8 +1883,8 @@ GtkWidget* create_main_dialog(){ button = gtk_button_new_with_label( "Free" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( button, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "fix_free", button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( fix_free ), NULL ); @@ -1890,8 +1892,8 @@ GtkWidget* create_main_dialog(){ button = gtk_button_new_with_label( "Free All" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( button, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "fix_freeall", button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( fix_freeall ), NULL ); @@ -1914,29 +1916,29 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Surface:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); label = gtk_label_new( "Other:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); label = gtk_label_new( "Steep:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texture1", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( texture_entryfocusout ), GINT_TO_POINTER( 0 ) ); @@ -1944,8 +1946,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texture2", entry ); g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( texture_entryfocusout ), GINT_TO_POINTER( 1 ) ); @@ -1953,8 +1955,8 @@ GtkWidget* create_main_dialog(){ entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texture3", entry ); @@ -1981,44 +1983,44 @@ GtkWidget* create_main_dialog(){ label = gtk_label_new( "Offset " ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); label = gtk_label_new( "Scale " ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 4, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texoffsetx", entry ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texoffsety", entry ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texscalex", entry ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); gtk_widget_set_size_request( entry, 60, -1 ); g_object_set_data( G_OBJECT( dlg ), "texscaley", entry ); @@ -2141,8 +2143,8 @@ qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lpara SetDlgItemText( hwnd,DLG_ABOUT_APP,szText ); /* Application icon: */ SendDlgItemMessage( hwnd, DLG_ABOUT_ICON, - STM_SETICON, (WPARAM)(HICON)LoadIcon( ghInst,"GENSURF" ), - (LPARAM) NULL ); + STM_SETICON, (WPARAM)(HICON)LoadIcon( ghInst,"GENSURF" ), + (LPARAM) NULL ); hwndURL = GetDlgItem( hwnd,DLG_ABOUT_URL ); hdc = GetDC( hwndURL ); @@ -2150,7 +2152,7 @@ qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lpara ReleaseDC( hwndURL,hdc ); GetWindowRect( hwndURL,&rc ); SetWindowPos( hwndURL,(HWND)NULL,0,0,size.cx,size.cy + 2, - SWP_NOMOVE | SWP_NOZORDER ); + SWP_NOMOVE | SWP_NOZORDER ); hwndURL = GetDlgItem( hwnd,DLG_ABOUT_BOARD ); hdc = GetDC( hwndURL ); @@ -2158,7 +2160,7 @@ qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lpara ReleaseDC( hwndURL,hdc ); GetWindowRect( hwndURL,&rc ); SetWindowPos( hwndURL,(HWND)NULL,0,0,size.cx,size.cy + 2, - SWP_NOMOVE | SWP_NOZORDER ); + SWP_NOMOVE | SWP_NOZORDER ); return TRUE; diff --git a/contrib/gtkgensurf/genmap.cpp b/contrib/gtkgensurf/genmap.cpp index a31bfbcb..8997692e 100644 --- a/contrib/gtkgensurf/genmap.cpp +++ b/contrib/gtkgensurf/genmap.cpp @@ -160,8 +160,8 @@ int MapPatches(){ for ( j = 1; j < NV; j += 2 ) { xyz[i][j].pp[k3] = ( 16 * xyz[i][j].p[k3] - xyz[i - 1][j - 1].p[k3] - 2 * xyz[i][j - 1].p[k3] - - xyz[i + 1][j - 1].p[k3] - 2 * xyz[i - 1][j].p[k3] - 2 * xyz[i + 1][j].p[k3] - - xyz[i - 1][j + 1].p[k3] - 2 * xyz[i][j + 1].p[k3] - xyz[i + 1][j + 1].p[k3] ) / 4; + - xyz[i + 1][j - 1].p[k3] - 2 * xyz[i - 1][j].p[k3] - 2 * xyz[i + 1][j].p[k3] + - xyz[i - 1][j + 1].p[k3] - 2 * xyz[i][j + 1].p[k3] - xyz[i + 1][j + 1].p[k3] ) / 4; } } @@ -389,7 +389,7 @@ void MapBrushes(){ XYZtoV( &v[3],&brush.face[0].v[1] ); XYZtoV( &v[4],&brush.face[0].v[2] ); strcpy( brush.face[0].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[0].Shift[0] = (float)TexOffset[0]; brush.face[0].Shift[1] = (float)TexOffset[1]; brush.face[0].Rotate = 0.; @@ -403,7 +403,7 @@ void MapBrushes(){ XYZtoV( &v[4],&brush.face[1].v[1] ); XYZtoV( &v[5],&brush.face[1].v[2] ); strcpy( brush.face[1].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[1].Shift[0] = (float)TexOffset[0]; brush.face[1].Shift[1] = (float)TexOffset[1]; brush.face[1].Rotate = 0.; @@ -417,7 +417,7 @@ void MapBrushes(){ XYZtoV( &v[5],&brush.face[2].v[1] ); XYZtoV( &v[3],&brush.face[2].v[2] ); strcpy( brush.face[2].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[2].Shift[0] = (float)TexOffset[0]; brush.face[2].Shift[1] = (float)TexOffset[1]; brush.face[2].Rotate = 0.; @@ -452,7 +452,7 @@ void MapBrushes(){ XYZtoV( &v[5],&brush.face[3].v[1] ); XYZtoV( &v[4],&brush.face[3].v[2] ); strcpy( brush.face[3].texture, - ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? surft : sidetext ) ); + ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? surft : sidetext ) ); brush.face[3].Shift[0] = (float)TexOffset[0]; brush.face[3].Shift[1] = (float)TexOffset[1]; brush.face[3].Rotate = 0.; @@ -487,7 +487,7 @@ void MapBrushes(){ XYZtoV( &v[1],&brush.face[4].v[1] ); XYZtoV( &v[2],&brush.face[4].v[2] ); strcpy( brush.face[4].texture, - ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? sidetext : surft ) ); + ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? sidetext : surft ) ); brush.face[4].Shift[0] = (float)TexOffset[0]; brush.face[4].Shift[1] = (float)TexOffset[1]; brush.face[4].Rotate = 0.; @@ -557,7 +557,7 @@ void MapBrushes(){ XYZtoV( &v[3],&brush.face[0].v[1] ); XYZtoV( &v[4],&brush.face[0].v[2] ); strcpy( brush.face[0].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[0].Shift[0] = (float)TexOffset[0]; brush.face[0].Shift[1] = (float)TexOffset[1]; brush.face[0].Rotate = 0.; @@ -571,7 +571,7 @@ void MapBrushes(){ XYZtoV( &v[4],&brush.face[1].v[1] ); XYZtoV( &v[5],&brush.face[1].v[2] ); strcpy( brush.face[1].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[1].Shift[0] = (float)TexOffset[0]; brush.face[1].Shift[1] = (float)TexOffset[1]; brush.face[1].Rotate = 0.; @@ -585,7 +585,7 @@ void MapBrushes(){ XYZtoV( &v[5],&brush.face[2].v[1] ); XYZtoV( &v[3],&brush.face[2].v[2] ); strcpy( brush.face[2].texture, - ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); + ( strlen( Texture[Game][1] ) ? Texture[Game][1] : Texture[Game][0] ) ); brush.face[2].Shift[0] = (float)TexOffset[0]; brush.face[2].Shift[1] = (float)TexOffset[1]; brush.face[2].Rotate = 0.; @@ -619,7 +619,7 @@ void MapBrushes(){ XYZtoV( &v[5],&brush.face[3].v[1] ); XYZtoV( &v[4],&brush.face[3].v[2] ); strcpy( brush.face[3].texture, - ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? surft : sidetext ) ); + ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? surft : sidetext ) ); brush.face[3].Shift[0] = (float)TexOffset[0]; brush.face[3].Shift[1] = (float)TexOffset[1]; brush.face[3].Rotate = 0.; @@ -653,7 +653,7 @@ void MapBrushes(){ XYZtoV( &v[1],&brush.face[4].v[1] ); XYZtoV( &v[2],&brush.face[4].v[2] ); strcpy( brush.face[4].texture, - ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? sidetext : surft ) ); + ( Plane == PLANE_XZ0 || Plane == PLANE_XZ1 ? sidetext : surft ) ); brush.face[4].Shift[0] = (float)TexOffset[0]; brush.face[4].Shift[1] = (float)TexOffset[1]; brush.face[4].Rotate = 0.; @@ -1410,14 +1410,14 @@ void GenerateXYZ(){ } else if ( rate < 0. ) { delta = ( 1 + rate ) * 0.5 * ( cos( dr * PI ) + 1.0 ) - - rate*pow( ( 1. - dr ),2 ); + rate*pow( ( 1. - dr ),2 ); } else if ( rate == 0. ) { delta = 0.5 * ( cos( dr * PI ) + 1.0 ); } else if ( rate <= 1. ) { delta = ( 1. - rate ) * 0.5 * ( cos( dr * PI ) + 1.0 ) + - rate * ( 1. - pow( dr,2 ) ); + rate * ( 1. - pow( dr,2 ) ); } else { @@ -1648,20 +1648,20 @@ void GenerateXYZ(){ } } /* - sprintf(CSV,"csv%03d.csv",Decimate); - f = fopen(CSV,"w"); - for(i=0; i 0 ) { @@ -1750,8 +1750,8 @@ void SubdividePlasma( int i0,int j0,int i1,int j1 ){ if ( i1 > i0 + 1 ) { if ( !xyz[i][j0].done ) { xyz[i][j0].pp[2] = xyz[i0][j0].pp[2] + - ( xyz[i1][j0].pp[2] - xyz[i0][j0].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + - ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + ( xyz[i1][j0].pp[2] - xyz[i0][j0].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); xyz[i][j0].done = 1; } else{ @@ -1759,8 +1759,8 @@ void SubdividePlasma( int i0,int j0,int i1,int j1 ){ } if ( ( j1 > j0 ) && ( !xyz[i][j1].done ) ) { xyz[i][j1].pp[2] = xyz[i0][j1].pp[2] + - ( xyz[i1][j1].pp[2] - xyz[i0][j1].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + - ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + ( xyz[i1][j1].pp[2] - xyz[i0][j1].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); xyz[i][j1].done = 1; } else{ @@ -1770,8 +1770,8 @@ void SubdividePlasma( int i0,int j0,int i1,int j1 ){ if ( j1 > j0 + 1 ) { if ( !xyz[i0][j].done ) { xyz[i0][j].pp[2] = xyz[i0][j0].pp[2] + - ( xyz[i0][j1].pp[2] - xyz[i0][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + - ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + ( xyz[i0][j1].pp[2] - xyz[i0][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + + ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); xyz[i0][j].done = 1; } else{ @@ -1779,8 +1779,8 @@ void SubdividePlasma( int i0,int j0,int i1,int j1 ){ } if ( ( i1 > i0 ) && ( !xyz[i1][j].done ) ) { xyz[i1][j].pp[2] = xyz[i1][j0].pp[2] + - ( xyz[i1][j1].pp[2] - xyz[i1][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + - ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + ( xyz[i1][j1].pp[2] - xyz[i1][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + + ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); xyz[i1][j].done = 1; } else{ @@ -1790,11 +1790,11 @@ void SubdividePlasma( int i0,int j0,int i1,int j1 ){ if ( ( i1 > i0 + 1 ) && ( j1 > j0 + 1 ) ) { if ( !xyz[i][j].done ) { z1 = xyz[i0][j].pp[2] + - ( xyz[i1][j].pp[2] - xyz[i0][j].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ); + ( xyz[i1][j].pp[2] - xyz[i0][j].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ); z2 = xyz[i][j0].pp[2] + - ( xyz[i][j1].pp[2] - xyz[i][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ); + ( xyz[i][j1].pp[2] - xyz[i][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ); xyz[i][j].pp[2] = ( z1 + z2 ) / 2. + - ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); xyz[i][j].done = 1; } else{ @@ -1966,18 +1966,18 @@ int TriangleFromPoint( double x, double y ){ for ( j = 0, tri = -1; j < gNumTris && tri == -1; j++ ) { if ( side( x,y, - gNode[gTri[j].v[0]].p[0],gNode[gTri[j].v[0]].p[1], - gNode[gTri[j].v[1]].p[0],gNode[gTri[j].v[1]].p[1] ) < 0. ) { + gNode[gTri[j].v[0]].p[0],gNode[gTri[j].v[0]].p[1], + gNode[gTri[j].v[1]].p[0],gNode[gTri[j].v[1]].p[1] ) < 0. ) { continue; } if ( side( x,y, - gNode[gTri[j].v[1]].p[0],gNode[gTri[j].v[1]].p[1], - gNode[gTri[j].v[2]].p[0],gNode[gTri[j].v[2]].p[1] ) < 0. ) { + gNode[gTri[j].v[1]].p[0],gNode[gTri[j].v[1]].p[1], + gNode[gTri[j].v[2]].p[0],gNode[gTri[j].v[2]].p[1] ) < 0. ) { continue; } if ( side( x,y, - gNode[gTri[j].v[2]].p[0],gNode[gTri[j].v[2]].p[1], - gNode[gTri[j].v[0]].p[0],gNode[gTri[j].v[0]].p[1] ) < 0. ) { + gNode[gTri[j].v[2]].p[0],gNode[gTri[j].v[2]].p[1], + gNode[gTri[j].v[0]].p[0],gNode[gTri[j].v[0]].p[1] ) < 0. ) { continue; } tri = j; @@ -2007,9 +2007,9 @@ int PlayerStartZ( double x, double y ){ for ( k = 0; k < 5; k++ ) { zt = ( gTri[t[k]].plane.dist - - gTri[t[k]].plane.normal[0] * x - - gTri[t[k]].plane.normal[1] * y ) / - gTri[t[k]].plane.normal[2]; + gTri[t[k]].plane.normal[0] * x - + gTri[t[k]].plane.normal[1] * y ) / + gTri[t[k]].plane.normal[2]; z = max( z,zt ); } return (int)( AtLeast( z,2. ) - PlayerBox[Game].z[0] ); diff --git a/contrib/gtkgensurf/gensurf.cpp b/contrib/gtkgensurf/gensurf.cpp index cecc8ab2..e71d9d26 100644 --- a/contrib/gtkgensurf/gensurf.cpp +++ b/contrib/gtkgensurf/gensurf.cpp @@ -82,12 +82,12 @@ TRI *gTri = (TRI *)NULL; int Game; bounding_box PlayerBox[NUMGAMES] = { {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Quake2 - {{-16., 16.}, {-16., 16.}, {-36., 36.}}, // Half-Life - {{-16., 16.}, {-16., 16.}, {-32., 32.}}, // SiN - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Heretic2 (guess) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // KingPin (guess) - {{-30., 30.}, {-30., 30.}, {-10.,160.}}, // Genesis3D (no idea) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}}; // Quake3 (not sure) + {{-16., 16.}, {-16., 16.}, {-36., 36.}}, // Half-Life + {{-16., 16.}, {-16., 16.}, {-32., 32.}}, // SiN + {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Heretic2 (guess) + {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // KingPin (guess) + {{-30., 30.}, {-30., 30.}, {-10.,160.}}, // Genesis3D (no idea) + {{-16., 16.}, {-16., 16.}, {-24., 32.}}}; // Quake3 (not sure) //char gszOutputDir[NUMGAMES][NAME_MAX]; //char gszTextureDir[NUMGAMES][NAME_MAX]; char Texture[NUMGAMES][3][64]; @@ -110,25 +110,25 @@ bool GenSurfInit(){ strcpy( gszIni, g_FuncTable.m_pfnProfileGetDirectory() ); strcat( gszIni, "gensurf.ini" ); -/*if (g_FuncTable.m_pfnReadProjectKey != NULL) - { - char *basepath; +/* if (g_FuncTable.m_pfnReadProjectKey != NULL) + { + char *basepath; - basepath = g_FuncTable.m_pfnReadProjectKey("basepath"); - if (basepath) - { - g_strdown (basepath); - if (strstr(basepath,"baseq3")) - Game = QUAKE3; - else if (strstr (basepath,"baseq2")) - Game = QUAKE2; - else // Gotta have a game, might as well be Quake3 - Game = QUAKE3; - } - else - Game = QUAKE3; - } - else */ + basepath = g_FuncTable.m_pfnReadProjectKey("basepath"); + if (basepath) + { + g_strdown (basepath); + if (strstr(basepath,"baseq3")) + Game = QUAKE3; + else if (strstr (basepath,"baseq2")) + Game = QUAKE2; + else // Gotta have a game, might as well be Quake3 + Game = QUAKE3; + } + else + Game = QUAKE3; + } + else */ Game = QUAKE3; @@ -420,7 +420,7 @@ void UpdatePreview( bool DataChange ){ void SaveSetup( GtkWidget *parent ){ const char *name = g_FuncTable.m_pfnFileDialog( parent, false, "Save GenSurf Settings", - g_FuncTable.m_pfnProfileGetDirectory() ); + g_FuncTable.m_pfnProfileGetDirectory() ); if ( name != NULL ) { char key[32], text[32]; @@ -457,7 +457,7 @@ void OpenSetup( GtkWidget *parent, int UseDefaults ){ } else{ name = g_FuncTable.m_pfnFileDialog( parent, true, "Open GenSurf Settings", - g_FuncTable.m_pfnProfileGetDirectory() ); + g_FuncTable.m_pfnProfileGetDirectory() ); } if ( name != NULL ) { diff --git a/contrib/gtkgensurf/gensurf.h b/contrib/gtkgensurf/gensurf.h index 99e4a46b..a4ad3f49 100644 --- a/contrib/gtkgensurf/gensurf.h +++ b/contrib/gtkgensurf/gensurf.h @@ -63,13 +63,21 @@ extern _QERBrushTable __BRUSHTABLENAME; #include #else template -inline T min( T x, T y ) { return ( x < y ) ? x : y; } +inline T min( T x, T y ) { + return ( x < y ) ? x : y; +} template -inline T max( T x, T y ) { return ( x > y ) ? x : y; } +inline T max( T x, T y ) { + return ( x > y ) ? x : y; +} #endif -typedef struct { long x, y; } Point; -typedef struct { long left, top, right, bottom; } Rect; +typedef struct { + long x, y; +} Point; +typedef struct { + long left, top, right, bottom; +} Rect; #define NAME_MAX 255 diff --git a/contrib/gtkgensurf/plugin.cpp b/contrib/gtkgensurf/plugin.cpp index 38a730da..5d6a6156 100644 --- a/contrib/gtkgensurf/plugin.cpp +++ b/contrib/gtkgensurf/plugin.cpp @@ -43,7 +43,7 @@ const char* QERPlug_GetName(){ const char* QERPlug_GetCommandList(){ return "Wall facing 270...;Wall facing 180...;Wall facing 90...;Wall facing 0...;" - "Ceiling...;Ground surface...;-;About..."; + "Ceiling...;Ground surface...;-;About..."; } // vMin/vMax provide the bounds of the selection, they are zero if there is no selection @@ -153,11 +153,11 @@ class GenSurfSynapseClient : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); -GenSurfSynapseClient() { } -virtual ~GenSurfSynapseClient() { } + GenSurfSynapseClient() { } + virtual ~GenSurfSynapseClient() { } }; CSynapseServer* g_pSynapseServer = NULL; diff --git a/contrib/gtkgensurf/triangle.h b/contrib/gtkgensurf/triangle.h index 337da40c..9ab182d5 100644 --- a/contrib/gtkgensurf/triangle.h +++ b/contrib/gtkgensurf/triangle.h @@ -281,7 +281,7 @@ struct triangulateio { }; void triangulate( char *, struct triangulateio *, struct triangulateio *, - struct triangulateio * ); + struct triangulateio * ); #ifdef __cplusplus } diff --git a/contrib/gtkgensurf/view.cpp b/contrib/gtkgensurf/view.cpp index d50d958d..dd96dc0b 100644 --- a/contrib/gtkgensurf/view.cpp +++ b/contrib/gtkgensurf/view.cpp @@ -309,7 +309,7 @@ static void motion( GtkWidget *widget, GdkEventMotion *event, gpointer data ){ g_GLTable.m_pfn_qglEnable( GL_SCISSOR_TEST ); g_GLTable.m_pfn_qglScissor( rcCoord.left, rcCoord.bottom, rcCoord.right - rcCoord.left, - rcCoord.top - rcCoord.bottom ); + rcCoord.top - rcCoord.bottom ); g_GLTable.m_pfn_qglClear( GL_COLOR_BUFFER_BIT ); if ( PtInRect( &rcGrid,pt ) ) { @@ -431,7 +431,7 @@ void CreateViewWindow(){ g_signal_connect( G_OBJECT( g_pPreviewWidget ), "expose_event", G_CALLBACK( expose ), NULL ); g_signal_connect( G_OBJECT( g_pPreviewWidget ), "motion_notify_event", G_CALLBACK( motion ), NULL ); g_signal_connect( G_OBJECT( g_pPreviewWidget ), "button_press_event", - G_CALLBACK( button_press ), NULL ); + G_CALLBACK( button_press ), NULL ); gtk_widget_show( g_pPreviewWidget ); gtk_container_add( GTK_CONTAINER( frame ), g_pPreviewWidget ); @@ -559,9 +559,9 @@ void DrawPreview( Rect rc ){ uv[2][1].p[k] = ( 4 * xyz[i + 2][j + 1].p[k] - xyz[i + 2][j ].p[k] - xyz[i + 2][j + 2].p[k] ) / 2; uv[1][2].p[k] = ( 4 * xyz[i + 1][j + 2].p[k] - xyz[i ][j + 2].p[k] - xyz[i + 2][j + 2].p[k] ) / 2; uv[1][1].p[k] = ( 16 * xyz[i + 1][j + 1].p[k] - - xyz[i ][j ].p[k] - 2 * xyz[i + 1][j ].p[k] - xyz[i + 2][j ].p[k] - - 2 * xyz[i ][j + 1].p[k] - 2 * xyz[i + 2][j + 1].p[k] - - xyz[i ][j + 2].p[k] - 2 * xyz[i + 1][j + 2].p[k] - xyz[i + 2][j + 2].p[k] ) / 4; + xyz[i ][j ].p[k] - 2 * xyz[i + 1][j ].p[k] - xyz[i + 2][j ].p[k] - + 2 * xyz[i ][j + 1].p[k] - 2 * xyz[i + 2][j + 1].p[k] - + xyz[i ][j + 2].p[k] - 2 * xyz[i + 1][j + 2].p[k] - xyz[i + 2][j + 2].p[k] ) / 4; for ( ii = 0; ii <= SUBDIVS; ii++ ) { @@ -1149,10 +1149,10 @@ void Scale( Rect rc,XYZ xyz,Point *pt ){ #ifdef ISOMETRIC pt[0].x = X0 + (int)( SF * ( ( xyz.p[0] - XLo ) * COSXA + - ( YHi - xyz.p[1] ) * COSYA ) ); + ( YHi - xyz.p[1] ) * COSYA ) ); pt[0].y = Y0 + (int)( SF * ( ZHi - xyz.p[2] + - ( YHi - xyz.p[1] ) * SINYA + - ( XHi - xyz.p[0] ) * SINXA ) ); + ( YHi - xyz.p[1] ) * SINYA + + ( XHi - xyz.p[0] ) * SINXA ) ); #else pt[0].x = X0 + (int)( SF * ( xyz.pp[0] - Hlo ) ); pt[0].y = Y0 - (int)( SF * ( Vhi - xyz.pp[1] ) ); diff --git a/contrib/hydratoolz/plugin.cpp b/contrib/hydratoolz/plugin.cpp index 4f8cc6c9..d43ab7af 100644 --- a/contrib/hydratoolz/plugin.cpp +++ b/contrib/hydratoolz/plugin.cpp @@ -87,9 +87,9 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_modal( GTK_WINDOW( window ), TRUE ); g_signal_connect( G_OBJECT( window ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( window ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), lpCaption ); gtk_container_set_border_width( GTK_CONTAINER( window ), 10 ); g_object_set_data( G_OBJECT( window ), "loop", &loop ); @@ -117,7 +117,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -127,7 +127,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -135,7 +135,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); gtk_widget_show( w ); ret = IDCANCEL; } @@ -143,7 +143,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -151,13 +151,13 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); gtk_widget_show( w ); ret = IDCANCEL; } @@ -166,7 +166,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -174,7 +174,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); gtk_widget_show( w ); ret = IDNO; } @@ -223,7 +223,7 @@ void ExtractFileName( const char *path, char *dest ){ // back up until a \ or the start // while ( src != path && *( src - 1 ) != '/' - && *( src - 1 ) != '\\' ) + && *( src - 1 ) != '\\' ) src--; while ( *src ) @@ -242,7 +242,8 @@ void ConvertDOSToUnixName( char *dst, const char *src ){ else{ *dst = *src; } - dst++; src++; + dst++; + src++; } *dst = 0; } @@ -454,7 +455,7 @@ const char *PLUGIN_NAME = "Q3 Texture Tools"; const char *PLUGIN_COMMANDS = "About...;Create/Update WAD keypair"; const char *PLUGIN_ABOUT = "HydraToolz for GTKRadiant\n\n" - "By Hydra!"; + "By Hydra!"; extern "C" void* WINAPI QERPlug_GetFuncTable(){ return &g_FuncTable; diff --git a/contrib/hydratoolz/plugin.h b/contrib/hydratoolz/plugin.h index 7e9e9771..9848fbfd 100644 --- a/contrib/hydratoolz/plugin.h +++ b/contrib/hydratoolz/plugin.h @@ -48,11 +48,11 @@ class CSynapseClientHydraToolz : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); -CSynapseClientHydraToolz() { } -virtual ~CSynapseClientHydraToolz() { } + CSynapseClientHydraToolz() { } + virtual ~CSynapseClientHydraToolz() { } }; #endif // _PLUGIN_H_ diff --git a/contrib/prtview/AboutDialog.cpp b/contrib/prtview/AboutDialog.cpp index 533823b1..cd3d04a2 100644 --- a/contrib/prtview/AboutDialog.cpp +++ b/contrib/prtview/AboutDialog.cpp @@ -57,9 +57,9 @@ void DoAboutDlg(){ gtk_window_set_modal( GTK_WINDOW( dlg ), TRUE ); gtk_window_set_title( GTK_WINDOW( dlg ), "About Portal Viewer" ); g_signal_connect( G_OBJECT( dlg ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( dlg ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); @@ -69,11 +69,11 @@ void DoAboutDlg(){ gtk_container_set_border_width( GTK_CONTAINER( hbox ), 10 ); label = gtk_label_new( "Version 1.000\n\n" - "Gtk port by Leonardo Zide\nleo@lokigames.com\n\n" - "Written by Geoffrey DeWan\ngdewan@prairienet.org\n\n" - "Built against NetRadiant " RADIANT_VERSION "\n" - __DATE__ - ); + "Gtk port by Leonardo Zide\nleo@lokigames.com\n\n" + "Written by Geoffrey DeWan\ngdewan@prairienet.org\n\n" + "Built against NetRadiant " RADIANT_VERSION "\n" + __DATE__ + ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( hbox ), label, TRUE, TRUE, 0 ); gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); @@ -86,7 +86,7 @@ void DoAboutDlg(){ gtk_widget_show( button ); gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_size_request( button, 60, -1 ); gtk_widget_show( dlg ); diff --git a/contrib/prtview/ConfigDialog.cpp b/contrib/prtview/ConfigDialog.cpp index 24084150..73baae83 100644 --- a/contrib/prtview/ConfigDialog.cpp +++ b/contrib/prtview/ConfigDialog.cpp @@ -55,8 +55,9 @@ static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer static int DoColor( PackedColour *c ){ GtkWidget* dlg; GdkColor clr = { 0, guint16( GetRValue( *c ) * ( 65535 / 255 ) ), - guint16( GetGValue( *c ) * ( 65535 / 255 ) ), - guint16( GetBValue( *c ) * ( 65535 / 255 ) ) }; + guint16( GetGValue( *c ) * ( 65535 / 255 ) ), + guint16( GetBValue( *c ) * ( 65535 / 255 ) ) + }; int loop = 1, ret = IDCANCEL; dlg = gtk_color_selection_dialog_new( "Choose Color" ); @@ -250,9 +251,9 @@ void DoConfigDialog(){ gtk_window_set_modal( GTK_WINDOW( dlg ), TRUE ); gtk_window_set_title( GTK_WINDOW( dlg ), "Portal Viewer Configuration" ); g_signal_connect( G_OBJECT( dlg ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( dlg ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); @@ -294,43 +295,43 @@ void DoConfigDialog(){ button = gtk_button_new_with_label( "Color" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnColor3d ), NULL ); button = gtk_button_new_with_label( "Depth Color" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnColorFog ), NULL ); aa3check = gtk_check_button_new_with_label( "Anti-Alias (May not work on some video cards)" ); gtk_widget_show( aa3check ); gtk_table_attach( GTK_TABLE( table ), aa3check, 1, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( aa3check ), "toggled", G_CALLBACK( OnAntiAlias3d ), NULL ); depthcheck = gtk_check_button_new_with_label( "Depth Cue" ); gtk_widget_show( depthcheck ); gtk_table_attach( GTK_TABLE( table ), depthcheck, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( depthcheck ), "toggled", G_CALLBACK( OnFog ), NULL ); linescheck = gtk_check_button_new_with_label( "Lines" ); gtk_widget_show( linescheck ); gtk_table_attach( GTK_TABLE( table ), linescheck, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( linescheck ), "toggled", G_CALLBACK( OnLines ), NULL ); polyscheck = gtk_check_button_new_with_label( "Polygons" ); gtk_widget_show( polyscheck ); gtk_table_attach( GTK_TABLE( table ), polyscheck, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( polyscheck ), "toggled", G_CALLBACK( OnPoly ), NULL ); zlist = gtk_combo_box_text_new(); @@ -353,15 +354,15 @@ void DoConfigDialog(){ transslider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); gtk_widget_show( transslider ); gtk_table_attach( GTK_TABLE( table ), transslider, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_scale_set_draw_value( GTK_SCALE( transslider ), FALSE ); translabel = gtk_label_new( "" ); gtk_widget_show( translabel ); gtk_table_attach( GTK_TABLE( table ), translabel, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( translabel ), 0.0, 0.0 ); g_signal_connect( adj, "value_changed", G_CALLBACK( OnScrollTrans ), translabel ); @@ -369,15 +370,15 @@ void DoConfigDialog(){ clipslider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); gtk_widget_show( clipslider ); gtk_table_attach( GTK_TABLE( table ), clipslider, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_scale_set_draw_value( GTK_SCALE( clipslider ), FALSE ); cliplabel = gtk_label_new( "" ); gtk_widget_show( cliplabel ); gtk_table_attach( GTK_TABLE( table ), cliplabel, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( cliplabel ), 0.0, 0.0 ); g_signal_connect( adj, "value_changed", G_CALLBACK( OnScrollClip ), cliplabel ); @@ -451,7 +452,7 @@ void DoConfigDialog(){ gtk_widget_show( button ); gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_size_request( button, 60, -1 ); // initialize dialog diff --git a/contrib/prtview/LoadPortalFileDialog.cpp b/contrib/prtview/LoadPortalFileDialog.cpp index 58fb553a..de93c616 100644 --- a/contrib/prtview/LoadPortalFileDialog.cpp +++ b/contrib/prtview/LoadPortalFileDialog.cpp @@ -71,9 +71,9 @@ int DoLoadPortalFileDialog(){ gtk_window_set_modal( GTK_WINDOW( dlg ), TRUE ); gtk_window_set_title( GTK_WINDOW( dlg ), "Load .prt" ); g_signal_connect( G_OBJECT( dlg ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( dlg ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); @@ -113,14 +113,14 @@ int DoLoadPortalFileDialog(){ gtk_widget_show( button ); gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); gtk_widget_set_size_request( button, 60, -1 ); button = gtk_button_new_with_label( "OK" ); gtk_widget_show( button ); gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_size_request( button, 60, -1 ); strcpy( portals.fn, GlobalRadiant().getMapName() ); diff --git a/contrib/prtview/portals.cpp b/contrib/prtview/portals.cpp index 818344fa..53a02d2c 100644 --- a/contrib/prtview/portals.cpp +++ b/contrib/prtview/portals.cpp @@ -206,45 +206,45 @@ void CPortals::Load(){ switch ( format ) { case PRT1: - { - GETLINE; //leafs count https://github.com/kduske/TrenchBroom/issues/1157 //clusters in q3 - sscanf( buf, "%u", &node_count ); - GETLINE; //portals count - sscanf( buf, "%u", &portal_count ); - } - break; + { + GETLINE; //leafs count https://github.com/kduske/TrenchBroom/issues/1157 //clusters in q3 + sscanf( buf, "%u", &node_count ); + GETLINE; //portals count + sscanf( buf, "%u", &portal_count ); + } + break; case PRT2: - { - GETLINE; //leafs count - sscanf( buf, "%u", &node_count ); - GETLINE; //clusters count - GETLINE; //portals count - sscanf( buf, "%u", &portal_count ); + { + GETLINE; //leafs count + sscanf( buf, "%u", &node_count ); + GETLINE; //clusters count + GETLINE; //portals count + sscanf( buf, "%u", &portal_count ); - } - break; + } + break; case PRT1AM: - { - GETLINE; //clusters count - GETLINE; //portals count - sscanf( buf, "%u", &portal_count ); - GETLINE; //leafs count - sscanf( buf, "%u", &node_count ); - } - break; + { + GETLINE; //clusters count + GETLINE; //portals count + sscanf( buf, "%u", &portal_count ); + GETLINE; //leafs count + sscanf( buf, "%u", &node_count ); + } + break; } /* - if(node_count > 0xFFFF) - { - fclose(in); + if(node_count > 0xFFFF) + { + fclose(in); - node_count = 0; + node_count = 0; - globalErrorStream() << " ERROR - Extreme number of nodes, aborting.\n"; + globalErrorStream() << " ERROR - Extreme number of nodes, aborting.\n"; - return; - } + return; + } */ if ( portal_count > 0xFFFF ) { @@ -478,11 +478,11 @@ void CPortalsDrawWireframe::render( RenderStateFlags state ) const { CubicClipVolume calculateCubicClipVolume( const Matrix4& viewproj ){ CubicClipVolume clip; clip.cam = vector4_projected( - matrix4_transformed_vector4( - matrix4_full_inverse( viewproj ), - Vector4( 0, 0, -1, 1 ) - ) - ); + matrix4_transformed_vector4( + matrix4_full_inverse( viewproj ), + Vector4( 0, 0, -1, 1 ) + ) + ); clip.min[0] = clip.cam[0] + ( portals.clip_range * 64.0f ); clip.min[1] = clip.cam[1] + ( portals.clip_range * 64.0f ); clip.min[2] = clip.cam[2] + ( portals.clip_range * 64.0f ); @@ -568,7 +568,7 @@ void CPortalsDrawSolid::render( RenderStateFlags state ) const { } glColor4f( portals.portal[portals.portal_sort[n]].fp_color_random[0], portals.portal[portals.portal_sort[n]].fp_color_random[1], - portals.portal[portals.portal_sort[n]].fp_color_random[2], trans ); + portals.portal[portals.portal_sort[n]].fp_color_random[2], trans ); glBegin( GL_POLYGON ); @@ -608,7 +608,7 @@ void CPortalsDrawSolid::render( RenderStateFlags state ) const { } glColor4f( portals.portal[n].fp_color_random[0], portals.portal[n].fp_color_random[1], - portals.portal[n].fp_color_random[2], trans ); + portals.portal[n].fp_color_random[2], trans ); glBegin( GL_POLYGON ); diff --git a/contrib/prtview/portals.h b/contrib/prtview/portals.h index 069d68b6..16518108 100644 --- a/contrib/prtview/portals.h +++ b/contrib/prtview/portals.h @@ -28,28 +28,28 @@ class CBspPoint { public: -float p[3]; + float p[3]; }; class CBspPortal { public: -CBspPortal(); -~CBspPortal(); + CBspPortal(); + ~CBspPortal(); protected: public: -CBspPoint center; -unsigned point_count; -CBspPoint *point; -CBspPoint *inner_point; -float fp_color_random[4]; -float min[3]; -float max[3]; -float dist; -bool hint; + CBspPoint center; + unsigned point_count; + CBspPoint *point; + CBspPoint *inner_point; + float fp_color_random[4]; + float min[3]; + float max[3]; + float dist; + bool hint; -bool Build( char *def ); + bool Build( char *def ); }; #ifdef PATH_MAX @@ -65,89 +65,89 @@ typedef guint32 PackedColour; class CPortals { -enum ePrtFormat{ - PRT1, - PRT2, - PRT1AM -} format; + enum ePrtFormat { + PRT1, + PRT2, + PRT1AM + } format; public: -CPortals(); -~CPortals(); + CPortals(); + ~CPortals(); -void Load(); // use filename in fn -void Purge(); + void Load(); // use filename in fn + void Purge(); -void FixColors(); + void FixColors(); -char fn[PRTVIEW_PATH_MAX]; + char fn[PRTVIEW_PATH_MAX]; -int zbuffer; -int polygons; -int lines; -bool show_3d; -bool aa_3d; -bool fog; -PackedColour color_3d; -float width_3d; // in 8'ths -float fp_color_3d[4]; -PackedColour color_fog; -float fp_color_fog[4]; -float trans_3d; -float clip_range; -bool clip; + int zbuffer; + int polygons; + int lines; + bool show_3d; + bool aa_3d; + bool fog; + PackedColour color_3d; + float width_3d; // in 8'ths + float fp_color_3d[4]; + PackedColour color_fog; + float fp_color_fog[4]; + float trans_3d; + float clip_range; + bool clip; -bool show_2d; -bool aa_2d; -PackedColour color_2d; -float width_2d; // in 8'ths -float fp_color_2d[4]; + bool show_2d; + bool aa_2d; + PackedColour color_2d; + float width_2d; // in 8'ths + float fp_color_2d[4]; -CBspPortal *portal; -int *portal_sort; -bool hint_flags; + CBspPortal *portal; + int *portal_sort; + bool hint_flags; // CBspNode *node; -unsigned int node_count; -unsigned int portal_count; + unsigned int node_count; + unsigned int portal_count; }; class CubicClipVolume { public: -Vector3 cam, min, max; + Vector3 cam, min, max; }; class CPortalsDrawSolid : public OpenGLRenderable { public: -mutable CubicClipVolume clip; -void render( RenderStateFlags state ) const; + mutable CubicClipVolume clip; + void render( RenderStateFlags state ) const; }; class CPortalsDrawSolidOutline : public OpenGLRenderable { public: -mutable CubicClipVolume clip; -void render( RenderStateFlags state ) const; + mutable CubicClipVolume clip; + void render( RenderStateFlags state ) const; }; class CPortalsDrawWireframe : public OpenGLRenderable { public: -void render( RenderStateFlags state ) const; + void render( RenderStateFlags state ) const; }; class CPortalsRender : public Renderable { public: -CPortalsDrawSolid m_drawSolid; -CPortalsDrawSolidOutline m_drawSolidOutline; -CPortalsDrawWireframe m_drawWireframe; + CPortalsDrawSolid m_drawSolid; + CPortalsDrawSolidOutline m_drawSolidOutline; + CPortalsDrawWireframe m_drawWireframe; -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; }; extern CPortals portals; diff --git a/contrib/prtview/prtview.cpp b/contrib/prtview/prtview.cpp index 7c2a4725..ad8c6f21 100644 --- a/contrib/prtview/prtview.cpp +++ b/contrib/prtview/prtview.cpp @@ -190,15 +190,15 @@ void INISetInt( const char *key, int val, const char *comment /* = NULL */ ){ static const char *PLUGIN_NAME = "Portal Viewer"; // commands in the menu static const char *PLUGIN_COMMANDS = - Q3R_CMD_ABOUT ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_OPTIONS ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_SHOW_2D ";" - Q3R_CMD_SHOW_3D ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_RELEASE ";" - Q3R_CMD_LOAD; + Q3R_CMD_ABOUT ";" + Q3R_CMD_SPLITTER ";" + Q3R_CMD_OPTIONS ";" + Q3R_CMD_SPLITTER ";" + Q3R_CMD_SHOW_2D ";" + Q3R_CMD_SHOW_3D ";" + Q3R_CMD_SPLITTER ";" + Q3R_CMD_RELEASE ";" + Q3R_CMD_LOAD; GtkWidget *g_pRadiantWnd = NULL; @@ -293,26 +293,26 @@ class PrtViewPluginDependencies : class PrtViewPluginModule { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "prtview" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "prtview" ); -PrtViewPluginModule(){ - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + PrtViewPluginModule(){ + m_plugin.m_pfnQERPlug_Init = QERPlug_Init; + m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; + m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - PrtView_construct(); -} -~PrtViewPluginModule(){ - PrtView_destroy(); -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + PrtView_construct(); + } + ~PrtViewPluginModule(){ + PrtView_destroy(); + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonPrtViewPluginModule; diff --git a/contrib/shaderplug/shaderplug.cpp b/contrib/shaderplug/shaderplug.cpp index 89109958..eb8a7b0a 100644 --- a/contrib/shaderplug/shaderplug.cpp +++ b/contrib/shaderplug/shaderplug.cpp @@ -50,9 +50,9 @@ class ShaderPlugPluginDependencies : public GlobalRadiantModuleRef, public GlobalShadersModuleRef { public: -ShaderPlugPluginDependencies() : - GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ){ -} + ShaderPlugPluginDependencies() : + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ){ + } }; namespace Shaderplug @@ -81,11 +81,12 @@ const char* getCommandTitleList(){ } void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ if ( string_equal( command, "About" ) ) { - GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), "Shaderplug (1.0)\n\n" - "by Shaderman (shaderman@gmx.net)", - "About", - eMB_OK, - eMB_ICONDEFAULT ); + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), + "Shaderplug (1.0)\n\n" + "by Shaderman (shaderman@gmx.net)", + "About", + eMB_OK, + eMB_ICONDEFAULT ); } if ( string_equal( command, "Create tag file" ) ) { CreateTagFile(); @@ -182,9 +183,9 @@ void CreateTagFile(){ if ( file_exists( tagFile ) ) { EMessageBoxReturn result = GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), - "WARNING! A tag file already exists! Overwrite it?", "Overwrite tag file?", - eMB_NOYES, - eMB_ICONWARNING ); + "WARNING! A tag file already exists! Overwrite it?", "Overwrite tag file?", + eMB_NOYES, + eMB_ICONWARNING ); if ( result == eIDYES ) { TagBuilder.SaveXmlDoc( tagFile ); @@ -198,32 +199,32 @@ void CreateTagFile(){ } else { GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), - "No shaders or textures found. No XML tag file created!\n" - "", - "ERROR", - eMB_OK, - eMB_ICONERROR ); + "No shaders or textures found. No XML tag file created!\n" + "", + "ERROR", + eMB_OK, + eMB_ICONERROR ); } } } // namespace class ShaderPluginModule { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "ShaderPlug" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "ShaderPlug" ); -ShaderPluginModule(){ - m_plugin.m_pfnQERPlug_Init = &Shaderplug::init; - m_plugin.m_pfnQERPlug_GetName = &Shaderplug::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &Shaderplug::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &Shaderplug::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &Shaderplug::dispatch; -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + ShaderPluginModule(){ + m_plugin.m_pfnQERPlug_Init = &Shaderplug::init; + m_plugin.m_pfnQERPlug_GetName = &Shaderplug::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &Shaderplug::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &Shaderplug::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &Shaderplug::dispatch; + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonShaderPluginModule; diff --git a/contrib/sunplug/sunplug.cpp b/contrib/sunplug/sunplug.cpp index dfaa7c34..02b1349e 100644 --- a/contrib/sunplug/sunplug.cpp +++ b/contrib/sunplug/sunplug.cpp @@ -85,22 +85,22 @@ mapcoord_setting_packet msp; // ************************** class EntityFindByClassname : public scene::Graph::Walker { -const char* m_name; -Entity*& m_entity; + const char* m_name; + Entity*& m_entity; public: -EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ - m_entity = 0; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_entity == 0 ) { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 - && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { - m_entity = entity; - } + EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ + m_entity = 0; + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_entity == 0 ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + m_entity = entity; + } + } + return true; } - return true; -} }; Entity* Scene_FindEntityByClass( const char* name ){ @@ -174,9 +174,9 @@ class SunPlugPluginDependencies : public GlobalEntityModuleRef // to access and modify the entities { public: -SunPlugPluginDependencies() : - GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ){ //, -} + SunPlugPluginDependencies() : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ){ //, + } }; // ************************* @@ -219,21 +219,21 @@ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush class SunPlugModule : public TypeSystemRef { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "SunPlug" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "SunPlug" ); -SunPlugModule(){ - m_plugin.m_pfnQERPlug_Init = &SunPlug::init; - m_plugin.m_pfnQERPlug_GetName = &SunPlug::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &SunPlug::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &SunPlug::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &SunPlug::dispatch; -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + SunPlugModule(){ + m_plugin.m_pfnQERPlug_Init = &SunPlug::init; + m_plugin.m_pfnQERPlug_GetName = &SunPlug::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &SunPlug::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &SunPlug::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &SunPlug::dispatch; + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonSunPlugModule; diff --git a/contrib/ufoaiplug/ufoai.cpp b/contrib/ufoaiplug/ufoai.cpp index 358dd500..274beba9 100644 --- a/contrib/ufoaiplug/ufoai.cpp +++ b/contrib/ufoaiplug/ufoai.cpp @@ -51,10 +51,10 @@ class UFOAIPluginDependencies : public GlobalEntityClassManagerModuleRef { public: -UFOAIPluginDependencies( void ) : - GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ -} + UFOAIPluginDependencies( void ) : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ + } }; namespace UFOAI @@ -79,8 +79,8 @@ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush const char *message = NULL; if ( string_equal( command, "About" ) ) { GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), - "UFO:AI Plugin (http://ufoai.sf.net)\nBuild: " __DATE__ "\nRadiant version: " RADIANT_VERSION "\nPlugin version: " PLUGIN_VERSION "\nAuthor: Martin Gerhardy (tlh2000/mattn)\n", "About", - eMB_OK, eMB_ICONDEFAULT ); + "UFO:AI Plugin (http://ufoai.sf.net)\nBuild: " __DATE__ "\nRadiant version: " RADIANT_VERSION "\nPlugin version: " PLUGIN_VERSION "\nAuthor: Martin Gerhardy (tlh2000/mattn)\n", "About", + eMB_OK, eMB_ICONDEFAULT ); } else if ( string_equal( command, "Level 1" ) ) { filter_level( CONTENTS_LEVEL1 ); @@ -130,8 +130,8 @@ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush if ( message != NULL ) { GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), - message, "Note", - eMB_OK, eMB_ICONDEFAULT ); + message, "Note", + eMB_OK, eMB_ICONDEFAULT ); } SceneChangeNotify(); } @@ -140,21 +140,21 @@ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush class UFOAIModule : public TypeSystemRef { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "UFO:AI" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "UFO:AI" ); -UFOAIModule(){ - m_plugin.m_pfnQERPlug_Init = &UFOAI::init; - m_plugin.m_pfnQERPlug_GetName = &UFOAI::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &UFOAI::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &UFOAI::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &UFOAI::dispatch; -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + UFOAIModule(){ + m_plugin.m_pfnQERPlug_Init = &UFOAI::init; + m_plugin.m_pfnQERPlug_GetName = &UFOAI::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &UFOAI::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &UFOAI::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &UFOAI::dispatch; + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonUFOAIModule; @@ -165,31 +165,31 @@ SingletonUFOAIModule g_UFOAIModule; class UFOAIToolbarDependencies : public ModuleRef<_QERPluginTable> { public: -UFOAIToolbarDependencies() : ModuleRef<_QERPluginTable>( "UFO:AI" ){ -} + UFOAIToolbarDependencies() : ModuleRef<_QERPluginTable>( "UFO:AI" ){ + } }; class UFOAIToolbarModule : public TypeSystemRef { -_QERPlugToolbarTable m_table; + _QERPlugToolbarTable m_table; public: -typedef _QERPlugToolbarTable Type; -STRING_CONSTANT( Name, "UFO:AI" ); + typedef _QERPlugToolbarTable Type; + STRING_CONSTANT( Name, "UFO:AI" ); -UFOAIToolbarModule(){ - if ( !strcmp( GlobalRadiant().getGameDescriptionKeyValue( "name" ), "UFO:Alien Invasion" ) ) { - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; + UFOAIToolbarModule(){ + if ( !strcmp( GlobalRadiant().getGameDescriptionKeyValue( "name" ), "UFO:Alien Invasion" ) ) { + m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; + m_table.m_pfnGetToolbarButton = GetToolbarButton; + } + else + { + m_table.m_pfnToolbarButtonCount = ToolbarNoButtons; + m_table.m_pfnGetToolbarButton = GetToolbarNoButton; + } } - else - { - m_table.m_pfnToolbarButtonCount = ToolbarNoButtons; - m_table.m_pfnGetToolbarButton = GetToolbarNoButton; + _QERPlugToolbarTable* getTable(){ + return &m_table; } -} -_QERPlugToolbarTable* getTable(){ - return &m_table; -} }; typedef SingletonModule SingletonUFOAIToolbarModule; diff --git a/contrib/ufoaiplug/ufoai_filters.cpp b/contrib/ufoaiplug/ufoai_filters.cpp index aa8dd91b..1809e9ef 100644 --- a/contrib/ufoaiplug/ufoai_filters.cpp +++ b/contrib/ufoaiplug/ufoai_filters.cpp @@ -52,127 +52,127 @@ typedef std::list entitylist_t; class EntityFindByName : public scene::Graph::Walker { -const char* m_name; -entitylist_t& m_entitylist; -/* this starts at 1 << level */ -int m_flag; -int m_hide; + const char* m_name; + entitylist_t& m_entitylist; + /* this starts at 1 << level */ + int m_flag; + int m_hide; public: -EntityFindByName( const char* name, entitylist_t& entitylist, int flag, bool hide ) - : m_name( name ), m_entitylist( entitylist ), m_flag( flag ), m_hide( hide ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - int spawnflagsInt; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ) { - if ( string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { - const char *spawnflags = entity->getKeyValue( "spawnflags" ); - globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n"; + EntityFindByName( const char* name, entitylist_t& entitylist, int flag, bool hide ) + : m_name( name ), m_entitylist( entitylist ), m_flag( flag ), m_hide( hide ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + int spawnflagsInt; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ) { + if ( string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + const char *spawnflags = entity->getKeyValue( "spawnflags" ); + globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n"; - if ( !string_empty( spawnflags ) ) { - spawnflagsInt = atoi( spawnflags ); - if ( !( spawnflagsInt & m_flag ) ) { - hide_node( path.top(), m_hide ); // hide/unhide - m_entitylist.push_back( entity ); + if ( !string_empty( spawnflags ) ) { + spawnflagsInt = atoi( spawnflags ); + if ( !( spawnflagsInt & m_flag ) ) { + hide_node( path.top(), m_hide ); // hide/unhide + m_entitylist.push_back( entity ); + } + } + else + { + globalWarningStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n"; } } - else - { - globalWarningStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n"; - } } + return true; } - return true; -} }; class ForEachFace : public BrushVisitor { public: -mutable int m_contentFlagsVis; -mutable int m_surfaceFlagsVis; + mutable int m_contentFlagsVis; + mutable int m_surfaceFlagsVis; -ForEachFace() { - m_contentFlagsVis = -1; - m_surfaceFlagsVis = -1; -} + ForEachFace() { + m_contentFlagsVis = -1; + m_surfaceFlagsVis = -1; + } -void visit( Face& face ) const { + void visit( Face& face ) const { #if _DEBUG - if ( m_surfaceFlagsVis < 0 ) { - m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; - } - else if ( m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags ) { - globalWarningStream() << "Faces with different surfaceflags at brush\n"; - } - if ( m_contentFlagsVis < 0 ) { - m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; - } - else if ( m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags ) { - globalWarningStream() << "Faces with different contentflags at brush\n"; - } + if ( m_surfaceFlagsVis < 0 ) { + m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; + } + else if ( m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags ) { + globalWarningStream() << "Faces with different surfaceflags at brush\n"; + } + if ( m_contentFlagsVis < 0 ) { + m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; + } + else if ( m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags ) { + globalWarningStream() << "Faces with different contentflags at brush\n"; + } #else - m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; - m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; + m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; + m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; #endif -} + } }; typedef std::list brushlist_t; class BrushGetLevel : public scene::Graph::Walker { -brushlist_t& m_brushlist; -int m_flag; -bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags -mutable bool m_notset; -mutable bool m_hide; + brushlist_t& m_brushlist; + int m_flag; + bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags + mutable bool m_notset; + mutable bool m_hide; public: -BrushGetLevel( brushlist_t& brushlist, int flag, bool content, bool notset, bool hide ) - : m_brushlist( brushlist ), m_flag( flag ), m_content( content ), m_notset( notset ), m_hide( hide ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 ) { - ForEachFace faces; - brush->forEachFace( faces ); - // contentflags? - if ( m_content ) { - // are any flags set? - if ( faces.m_contentFlagsVis > 0 ) { - // flag should not be set - if ( m_notset && ( !( faces.m_contentFlagsVis & m_flag ) ) ) { - hide_node( path.top(), m_hide ); - m_brushlist.push_back( brush ); - } - // check whether flag is set - else if ( !m_notset && ( ( faces.m_contentFlagsVis & m_flag ) ) ) { - hide_node( path.top(), m_hide ); - m_brushlist.push_back( brush ); - } - } - } - // surfaceflags? - else - { - // are any flags set? - if ( faces.m_surfaceFlagsVis > 0 ) { - // flag should not be set - if ( m_notset && ( !( faces.m_surfaceFlagsVis & m_flag ) ) ) { - hide_node( path.top(), m_hide ); - m_brushlist.push_back( brush ); - } - // check whether flag is set - else if ( !m_notset && ( ( faces.m_surfaceFlagsVis & m_flag ) ) ) { - hide_node( path.top(), m_hide ); - m_brushlist.push_back( brush ); - } - } - } - + BrushGetLevel( brushlist_t& brushlist, int flag, bool content, bool notset, bool hide ) + : m_brushlist( brushlist ), m_flag( flag ), m_content( content ), m_notset( notset ), m_hide( hide ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 ) { + ForEachFace faces; + brush->forEachFace( faces ); + // contentflags? + if ( m_content ) { + // are any flags set? + if ( faces.m_contentFlagsVis > 0 ) { + // flag should not be set + if ( m_notset && ( !( faces.m_contentFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + // check whether flag is set + else if ( !m_notset && ( ( faces.m_contentFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + } + } + // surfaceflags? + else + { + // are any flags set? + if ( faces.m_surfaceFlagsVis > 0 ) { + // flag should not be set + if ( m_notset && ( !( faces.m_surfaceFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + // check whether flag is set + else if ( !m_notset && ( ( faces.m_surfaceFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + } + } + + } + return true; } - return true; -} }; /** diff --git a/contrib/ufoaiplug/ufoai_gtk.cpp b/contrib/ufoaiplug/ufoai_gtk.cpp index f934e579..70828e69 100644 --- a/contrib/ufoaiplug/ufoai_gtk.cpp +++ b/contrib/ufoaiplug/ufoai_gtk.cpp @@ -80,92 +80,92 @@ std::size_t ToolbarNoButtons( void ){ class CUFOAIToolbarButton : public IToolbarButton { public: -virtual const char* getImage() const { - switch ( mIndex ) - { - case 0: return "ufoai_level1.png"; - case 1: return "ufoai_level2.png"; - case 2: return "ufoai_level3.png"; - case 3: return "ufoai_level4.png"; - case 4: return "ufoai_level5.png"; - case 5: return "ufoai_level6.png"; - case 6: return "ufoai_level7.png"; - case 7: return "ufoai_level8.png"; - case 8: return "ufoai_stepon.png"; - case 9: return "ufoai_actorclip.png"; - case 10: return "ufoai_weaponclip.png"; - case 11: return "ufoai_nodraw.png"; + virtual const char* getImage() const { + switch ( mIndex ) + { + case 0: return "ufoai_level1.png"; + case 1: return "ufoai_level2.png"; + case 2: return "ufoai_level3.png"; + case 3: return "ufoai_level4.png"; + case 4: return "ufoai_level5.png"; + case 5: return "ufoai_level6.png"; + case 6: return "ufoai_level7.png"; + case 7: return "ufoai_level8.png"; + case 8: return "ufoai_stepon.png"; + case 9: return "ufoai_actorclip.png"; + case 10: return "ufoai_weaponclip.png"; + case 11: return "ufoai_nodraw.png"; + } + return NULL; } - return NULL; -} -virtual EType getType() const { - switch ( mIndex ) - { + virtual EType getType() const { + switch ( mIndex ) + { /* case 3: return eButton;*/ - case 8: return eToggleButton; - case 9: return eToggleButton; - case 10: return eToggleButton; - case 11: return eToggleButton; - default: return eButton; + case 8: return eToggleButton; + case 9: return eToggleButton; + case 10: return eToggleButton; + case 11: return eToggleButton; + default: return eButton; + } } -} -virtual const char* getText() const { - switch ( mIndex ) - { - case 0: return "Level 1"; - case 1: return "Level 2"; - case 2: return "Level 3"; - case 3: return "Level 4"; - case 4: return "Level 5"; - case 5: return "Level 6"; - case 6: return "Level 7"; - case 7: return "Level 8"; - case 8: return "Stepon"; - case 9: return "Actorclip"; - case 10: return "Weaponclip"; - case 11: return "Nodraw"; + virtual const char* getText() const { + switch ( mIndex ) + { + case 0: return "Level 1"; + case 1: return "Level 2"; + case 2: return "Level 3"; + case 3: return "Level 4"; + case 4: return "Level 5"; + case 5: return "Level 6"; + case 6: return "Level 7"; + case 7: return "Level 8"; + case 8: return "Stepon"; + case 9: return "Actorclip"; + case 10: return "Weaponclip"; + case 11: return "Nodraw"; + } + return NULL; } - return NULL; -} -virtual const char* getTooltip() const { - switch ( mIndex ) - { - case 0: return "Show only level 1"; - case 1: return "Show only level 2"; - case 2: return "Show only level 3"; - case 3: return "Show only level 4"; - case 4: return "Show only level 5"; - case 5: return "Show only level 6"; - case 6: return "Show only level 7"; - case 7: return "Show only level 8"; - case 8: return "Hide stepon brushes"; - case 9: return "Hide actorclip brushes"; - case 10: return "Hide weaponclip brushes"; - case 11: return "Hide nodraw brushes"; + virtual const char* getTooltip() const { + switch ( mIndex ) + { + case 0: return "Show only level 1"; + case 1: return "Show only level 2"; + case 2: return "Show only level 3"; + case 3: return "Show only level 4"; + case 4: return "Show only level 5"; + case 5: return "Show only level 6"; + case 6: return "Show only level 7"; + case 7: return "Show only level 8"; + case 8: return "Hide stepon brushes"; + case 9: return "Hide actorclip brushes"; + case 10: return "Hide weaponclip brushes"; + case 11: return "Hide nodraw brushes"; + } + return NULL; } - return NULL; + + virtual void activate() const { + switch ( mIndex ) + { + case 0: filter_level( CONTENTS_LEVEL1 ); break; + case 1: filter_level( CONTENTS_LEVEL2 ); break; + case 2: filter_level( CONTENTS_LEVEL3 ); break; + case 3: filter_level( CONTENTS_LEVEL4 ); break; + case 4: filter_level( CONTENTS_LEVEL5 ); break; + case 5: filter_level( CONTENTS_LEVEL6 ); break; + case 6: filter_level( CONTENTS_LEVEL7 ); break; + case 7: filter_level( CONTENTS_LEVEL8 ); break; + case 8: filter_stepon(); break; + case 9: filter_actorclip(); break; + case 10: filter_weaponclip(); break; + case 11: filter_nodraw(); break; + } + SceneChangeNotify(); } -virtual void activate() const { - switch ( mIndex ) - { - case 0: filter_level( CONTENTS_LEVEL1 ); break; - case 1: filter_level( CONTENTS_LEVEL2 ); break; - case 2: filter_level( CONTENTS_LEVEL3 ); break; - case 3: filter_level( CONTENTS_LEVEL4 ); break; - case 4: filter_level( CONTENTS_LEVEL5 ); break; - case 5: filter_level( CONTENTS_LEVEL6 ); break; - case 6: filter_level( CONTENTS_LEVEL7 ); break; - case 7: filter_level( CONTENTS_LEVEL8 ); break; - case 8: filter_stepon(); break; - case 9: filter_actorclip(); break; - case 10: filter_weaponclip(); break; - case 11: filter_nodraw(); break; - } - SceneChangeNotify(); -} - -std::size_t mIndex; + std::size_t mIndex; }; /** diff --git a/contrib/ufoaiplug/ufoai_level.cpp b/contrib/ufoaiplug/ufoai_level.cpp index c255c941..fad2c472 100644 --- a/contrib/ufoaiplug/ufoai_level.cpp +++ b/contrib/ufoaiplug/ufoai_level.cpp @@ -34,21 +34,21 @@ class Level; */ class EntityFindByClassname : public scene::Graph::Walker { -const char* m_name; -Entity*& m_entity; + const char* m_name; + Entity*& m_entity; public: -EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ - m_entity = 0; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_entity == 0 ) { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { - m_entity = entity; - } + EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ + m_entity = 0; + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_entity == 0 ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + m_entity = entity; + } + } + return true; } - return true; -} }; /** @@ -65,24 +65,24 @@ Entity* Scene_FindEntityByClass( const char* name ){ */ class EntityFindFlags : public scene::Graph::Walker { -const char *m_classname; -const char *m_flag; -int *m_count; + const char *m_classname; + const char *m_flag; + int *m_count; public: -EntityFindFlags( const char *classname, const char *flag, int *count ) : m_classname( classname ), m_flag( flag ), m_count( count ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - const char *str; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { - str = entity->getKeyValue( m_flag ); - if ( string_empty( str ) ) { - ( *m_count )++; - } + EntityFindFlags( const char *classname, const char *flag, int *count ) : m_classname( classname ), m_flag( flag ), m_count( count ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + const char *str; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { + str = entity->getKeyValue( m_flag ); + if ( string_empty( str ) ) { + ( *m_count )++; + } + } + return true; } - return true; -} }; @@ -91,32 +91,32 @@ bool pre( const scene::Path& path, scene::Instance& instance ) const { */ class EntityFindTeams : public scene::Graph::Walker { -const char *m_classname; -int *m_count; -int *m_team; + const char *m_classname; + int *m_count; + int *m_team; public: -EntityFindTeams( const char *classname, int *count, int *team ) : m_classname( classname ), m_count( count ), m_team( team ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - const char *str; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { - if ( m_count ) { - ( *m_count )++; - } - // now get the highest teamnum - if ( m_team ) { - str = entity->getKeyValue( "team" ); - if ( !string_empty( str ) ) { - if ( atoi( str ) > *m_team ) { - ( *m_team ) = atoi( str ); + EntityFindTeams( const char *classname, int *count, int *team ) : m_classname( classname ), m_count( count ), m_team( team ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + const char *str; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { + if ( m_count ) { + ( *m_count )++; + } + // now get the highest teamnum + if ( m_team ) { + str = entity->getKeyValue( "team" ); + if ( !string_empty( str ) ) { + if ( atoi( str ) > *m_team ) { + ( *m_team ) = atoi( str ); + } } } } + return true; } - return true; -} }; /** diff --git a/include/cullable.h b/include/cullable.h index 92029906..5a9d5682 100644 --- a/include/cullable.h +++ b/include/cullable.h @@ -41,35 +41,35 @@ class VolumeTest public: /// \brief Returns true if \p point intersects volume. -virtual bool TestPoint( const Vector3& point ) const = 0; + virtual bool TestPoint( const Vector3& point ) const = 0; /// \brief Returns true if \p segment intersects volume. -virtual bool TestLine( const Segment& segment ) const = 0; + virtual bool TestLine( const Segment& segment ) const = 0; /// \brief Returns true if \p plane faces towards volume. -virtual bool TestPlane( const Plane3& plane ) const = 0; + virtual bool TestPlane( const Plane3& plane ) const = 0; /// \brief Returns true if \p plane transformed by \p localToWorld faces the viewer. -virtual bool TestPlane( const Plane3& plane, const Matrix4& localToWorld ) const = 0; + virtual bool TestPlane( const Plane3& plane, const Matrix4& localToWorld ) const = 0; /// \brief Returns the intersection of \p aabb and volume. -virtual VolumeIntersectionValue TestAABB( const AABB& aabb ) const = 0; + virtual VolumeIntersectionValue TestAABB( const AABB& aabb ) const = 0; /// \brief Returns the intersection of \p aabb transformed by \p localToWorld and volume. -virtual VolumeIntersectionValue TestAABB( const AABB& aabb, const Matrix4& localToWorld ) const = 0; + virtual VolumeIntersectionValue TestAABB( const AABB& aabb, const Matrix4& localToWorld ) const = 0; -virtual bool fill() const = 0; + virtual bool fill() const = 0; -virtual const Matrix4& GetViewport() const = 0; -virtual const Matrix4& GetProjection() const = 0; -virtual const Matrix4& GetModelview() const = 0; + virtual const Matrix4& GetViewport() const = 0; + virtual const Matrix4& GetProjection() const = 0; + virtual const Matrix4& GetModelview() const = 0; -virtual const Matrix4& GetViewMatrix() const = 0; //viewproj -virtual const Vector3& getViewer() const = 0; -virtual const Vector3& getViewDir() const = 0; + virtual const Matrix4& GetViewMatrix() const = 0; //viewproj + virtual const Vector3& getViewer() const = 0; + virtual const Vector3& getViewDir() const = 0; }; class Cullable { public: -STRING_CONSTANT( Name, "Cullable" ); + STRING_CONSTANT( Name, "Cullable" ); -virtual VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const = 0; + virtual VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const = 0; }; diff --git a/include/editable.h b/include/editable.h index 3c5524a3..68ab150a 100644 --- a/include/editable.h +++ b/include/editable.h @@ -29,9 +29,9 @@ class Matrix4; class Editable { public: -STRING_CONSTANT( Name, "Editable" ); + STRING_CONSTANT( Name, "Editable" ); -virtual const Matrix4& getLocalPivot() const = 0; + virtual const Matrix4& getLocalPivot() const = 0; }; inline Editable* Node_getEditable( scene::Node& node ){ @@ -41,9 +41,9 @@ inline Editable* Node_getEditable( scene::Node& node ){ class Snappable { public: -STRING_CONSTANT( Name, "Snappable" ); + STRING_CONSTANT( Name, "Snappable" ); -virtual void snapto( float snap ) = 0; + virtual void snapto( float snap ) = 0; }; inline Snappable* Node_getSnappable( scene::Node& node ){ diff --git a/include/iarchive.h b/include/iarchive.h index dddf5579..118b6045 100644 --- a/include/iarchive.h +++ b/include/iarchive.h @@ -32,16 +32,16 @@ class ArchiveFile { public: /// \brief Destroys the file object. -virtual void release() = 0; + virtual void release() = 0; /// \brief Returns the size of the file data in bytes. -virtual std::size_t size() const = 0; + virtual std::size_t size() const = 0; /// \brief Returns the path to this file (relative to the filesystem root) -virtual const char* getName() const = 0; + virtual const char* getName() const = 0; /// \brief Returns the stream associated with this file. /// Subsequent calls return the same stream. /// The stream may be read forwards until it is exhausted. /// The stream remains valid for the lifetime of the file. -virtual InputStream& getInputStream() = 0; + virtual InputStream& getInputStream() = 0; }; class TextInputStream; @@ -51,23 +51,23 @@ class ArchiveTextFile { public: /// \brief Destroys the file object. -virtual void release() = 0; + virtual void release() = 0; /// \brief Returns the stream associated with this file. /// Subsequent calls return the same stream. /// The stream may be read forwards until it is exhausted. /// The stream remains valid for the lifetime of the file. -virtual TextInputStream& getInputStream() = 0; + virtual TextInputStream& getInputStream() = 0; }; class ScopedArchiveFile { -ArchiveFile& m_file; + ArchiveFile& m_file; public: -ScopedArchiveFile( ArchiveFile& file ) : m_file( file ){ -} -~ScopedArchiveFile(){ - m_file.release(); -} + ScopedArchiveFile( ArchiveFile& file ) : m_file( file ){ + } + ~ScopedArchiveFile(){ + m_file.release(); + } }; class CustomArchiveVisitor; @@ -76,33 +76,33 @@ class Archive { public: -class Visitor -{ -public: -virtual void visit( const char* name ) = 0; -}; + class Visitor + { + public: + virtual void visit( const char* name ) = 0; + }; -typedef CustomArchiveVisitor VisitorFunc; + typedef CustomArchiveVisitor VisitorFunc; -enum EMode -{ - eFiles = 0x01, - eDirectories = 0x02, - eFilesAndDirectories = 0x03, -}; + enum EMode + { + eFiles = 0x01, + eDirectories = 0x02, + eFilesAndDirectories = 0x03, + }; /// \brief Destroys the archive object. /// Any unreleased file object associated with the archive remains valid. */ -virtual void release() = 0; + virtual void release() = 0; /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. /// Name comparisons are case-insensitive. -virtual ArchiveFile* openFile( const char* name ) = 0; + virtual ArchiveFile* openFile( const char* name ) = 0; /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. /// Name comparisons are case-insensitive. -virtual ArchiveTextFile* openTextFile( const char* name ) = 0; + virtual ArchiveTextFile* openTextFile( const char* name ) = 0; /// Returns true if the file identified by \p name can be opened. /// Name comparisons are case-insensitive. -virtual bool containsFile( const char* name ) = 0; + virtual bool containsFile( const char* name ) = 0; /// \brief Performs a depth-first traversal of the archive tree starting at \p root. /// Traverses the entire tree if \p root is "". /// When a file is encountered, calls \c visitor.file passing the file name. @@ -110,32 +110,32 @@ virtual bool containsFile( const char* name ) = 0; /// Skips the directory if \c visitor.directory returned true. /// Root comparisons are case-insensitive. /// Names are mixed-case. -virtual void forEachFile( VisitorFunc visitor, const char* root ) = 0; + virtual void forEachFile( VisitorFunc visitor, const char* root ) = 0; }; class CustomArchiveVisitor { -Archive::Visitor* m_visitor; -Archive::EMode m_mode; -std::size_t m_depth; + Archive::Visitor* m_visitor; + Archive::EMode m_mode; + std::size_t m_depth; public: -CustomArchiveVisitor( Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth ) - : m_visitor( &visitor ), m_mode( mode ), m_depth( depth ){ -} -void file( const char* name ){ - if ( ( m_mode & Archive::eFiles ) != 0 ) { - m_visitor->visit( name ); + CustomArchiveVisitor( Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth ) + : m_visitor( &visitor ), m_mode( mode ), m_depth( depth ){ } -} -bool directory( const char* name, std::size_t depth ){ - if ( ( m_mode & Archive::eDirectories ) != 0 ) { - m_visitor->visit( name ); + void file( const char* name ){ + if ( ( m_mode & Archive::eFiles ) != 0 ) { + m_visitor->visit( name ); + } } - if ( depth == m_depth ) { - return true; + bool directory( const char* name, std::size_t depth ){ + if ( ( m_mode & Archive::eDirectories ) != 0 ) { + m_visitor->visit( name ); + } + if ( depth == m_depth ) { + return true; + } + return false; } - return false; -} }; typedef Archive* ( *PFN_OPENARCHIVE )( const char* name ); @@ -143,10 +143,10 @@ typedef Archive* ( *PFN_OPENARCHIVE )( const char* name ); class _QERArchiveTable { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "archive" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "archive" ); -PFN_OPENARCHIVE m_pfnOpenArchive; + PFN_OPENARCHIVE m_pfnOpenArchive; }; template diff --git a/include/ibrush.h b/include/ibrush.h index b66689bb..77273d0e 100644 --- a/include/ibrush.h +++ b/include/ibrush.h @@ -49,63 +49,63 @@ class Node; class IBrushFace { public: -virtual const char* GetShader() const = 0; -virtual void SetShader( const char* name ) = 0; -virtual const TextureProjection& GetTexdef() const = 0; -virtual void GetTexdef( TextureProjection& projection ) const = 0; -virtual void SetTexdef( const TextureProjection& projection ) = 0; -virtual void GetFlags( ContentsFlagsValue& flags ) const = 0; -virtual void SetFlags( const ContentsFlagsValue& flags ) = 0; -virtual void ShiftTexdef( float s, float t ) = 0; -virtual void ScaleTexdef( float s, float t ) = 0; -virtual void RotateTexdef( float angle ) = 0; -virtual void FitTexture( float s_repeat, float t_repeat ) = 0; -virtual bool isDetail() const = 0; -virtual void setDetail( bool detail ) = 0; + virtual const char* GetShader() const = 0; + virtual void SetShader( const char* name ) = 0; + virtual const TextureProjection& GetTexdef() const = 0; + virtual void GetTexdef( TextureProjection& projection ) const = 0; + virtual void SetTexdef( const TextureProjection& projection ) = 0; + virtual void GetFlags( ContentsFlagsValue& flags ) const = 0; + virtual void SetFlags( const ContentsFlagsValue& flags ) = 0; + virtual void ShiftTexdef( float s, float t ) = 0; + virtual void ScaleTexdef( float s, float t ) = 0; + virtual void RotateTexdef( float angle ) = 0; + virtual void FitTexture( float s_repeat, float t_repeat ) = 0; + virtual bool isDetail() const = 0; + virtual void setDetail( bool detail ) = 0; }; class IBrush { public: -STRING_CONSTANT( Name, "IBrush" ); -virtual void reserve( std::size_t count ) = 0; -virtual void clear() = 0; -virtual void copy( const IBrush& other ) = 0; -virtual IBrushFace* addPlane( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection ) = 0; -virtual const AABB& localAABB() const = 0; -virtual void removeEmptyFaces() = 0; + STRING_CONSTANT( Name, "IBrush" ); + virtual void reserve( std::size_t count ) = 0; + virtual void clear() = 0; + virtual void copy( const IBrush& other ) = 0; + virtual IBrushFace* addPlane( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection ) = 0; + virtual const AABB& localAABB() const = 0; + virtual void removeEmptyFaces() = 0; }; class IBrushFaceInstance { public: -virtual IBrushFace& getFace() = 0; -virtual const IBrushFace& getFace() const = 0; -virtual bool isSelected() const = 0; -virtual void setSelected( SelectionSystem::EComponentMode mode, bool select ) const = 0; + virtual IBrushFace& getFace() = 0; + virtual const IBrushFace& getFace() const = 0; + virtual bool isSelected() const = 0; + virtual void setSelected( SelectionSystem::EComponentMode mode, bool select ) const = 0; }; class IBrushInstance { public: -STRING_CONSTANT( Name, "IBrushInstance" ); -virtual void forEachFaceInstance( const BrushInstanceVisitor& visitor ) = 0; + STRING_CONSTANT( Name, "IBrushInstance" ); + virtual void forEachFaceInstance( const BrushInstanceVisitor& visitor ) = 0; }; #endif class _QERFaceData { public: -_QERFaceData() : m_shader( "" ), contents( 0 ), flags( 0 ), value( 0 ){ -} -Vector3 m_p0; -Vector3 m_p1; -Vector3 m_p2; -texdef_t m_texdef; -const char* m_shader; -int contents; -int flags; -int value; + _QERFaceData() : m_shader( "" ), contents( 0 ), flags( 0 ), value( 0 ){ + } + Vector3 m_p0; + Vector3 m_p1; + Vector3 m_p2; + texdef_t m_texdef; + const char* m_shader; + int contents; + int flags; + int value; }; typedef Callback1 BrushFaceDataCallback; @@ -113,13 +113,13 @@ typedef Callback1 BrushFaceDataCallback; class BrushCreator { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "brush" ); -virtual scene::Node& createBrush() = 0; -virtual EBrushType getFormat() const = 0; -virtual void toggleFormat( EBrushType type ) const = 0; -virtual void Brush_forEachFace( scene::Node& brush, const BrushFaceDataCallback& callback ) = 0; -virtual bool Brush_addFace( scene::Node& brush, const _QERFaceData& faceData ) = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "brush" ); + virtual scene::Node& createBrush() = 0; + virtual EBrushType getFormat() const = 0; + virtual void toggleFormat( EBrushType type ) const = 0; + virtual void Brush_forEachFace( scene::Node& brush, const BrushFaceDataCallback& callback ) = 0; + virtual bool Brush_addFace( scene::Node& brush, const _QERFaceData& faceData ) = 0; }; #include "modulesystem.h" diff --git a/include/icamera.h b/include/icamera.h index e9becbae..8a4bf9f9 100644 --- a/include/icamera.h +++ b/include/icamera.h @@ -36,15 +36,15 @@ class Matrix4; class CameraView { public: -virtual void setModelview( const Matrix4& modelview ) = 0; -virtual void setFieldOfView( float fieldOfView ) = 0; + virtual void setModelview( const Matrix4& modelview ) = 0; + virtual void setFieldOfView( float fieldOfView ) = 0; }; class CameraModel { public: -STRING_CONSTANT( Name, "CameraModel" ); -virtual void setCameraView( CameraView* view, const Callback& disconnect ) = 0; + STRING_CONSTANT( Name, "CameraModel" ); + virtual void setCameraView( CameraView* view, const Callback& disconnect ) = 0; }; template class BasicVector3; diff --git a/include/idatastream.h b/include/idatastream.h index 674c9fa9..bcce7e68 100644 --- a/include/idatastream.h +++ b/include/idatastream.h @@ -27,8 +27,8 @@ class StreamBase { public: -typedef std::size_t size_type; -typedef unsigned char byte_type; + typedef std::size_t size_type; + typedef unsigned char byte_type; }; /// \brief A read-only byte-stream. @@ -37,7 +37,7 @@ class InputStream : public StreamBase public: /// \brief Attempts to read the next \p length bytes from the stream to \p buffer. /// Returns the number of bytes actually stored in \p buffer. -virtual size_type read( byte_type* buffer, size_type length ) = 0; + virtual size_type read( byte_type* buffer, size_type length ) = 0; }; /// \brief A write-only byte-stream. @@ -46,28 +46,28 @@ class OutputStream : public StreamBase public: /// \brief Attempts to write \p length bytes to the stream from \p buffer. /// Returns the number of bytes actually read from \p buffer. -virtual size_type write( const byte_type* buffer, size_type length ) = 0; + virtual size_type write( const byte_type* buffer, size_type length ) = 0; }; class SeekableStream { public: -typedef int offset_type; -typedef std::size_t position_type; + typedef int offset_type; + typedef std::size_t position_type; -enum seekdir -{ - beg, - cur, - end, -}; + enum seekdir + { + beg, + cur, + end, + }; /// \brief Sets the current \p position of the stream relative to the start. -virtual position_type seek( position_type position ) = 0; + virtual position_type seek( position_type position ) = 0; /// \brief Sets the current \p position of the stream relative to either the start, end or current position. -virtual position_type seek( offset_type offset, seekdir direction ) = 0; + virtual position_type seek( offset_type offset, seekdir direction ) = 0; /// \brief Returns the current position of the stream. -virtual position_type tell() const = 0; + virtual position_type tell() const = 0; }; /// \brief A seekable read-only byte-stream. diff --git a/include/ieclass.h b/include/ieclass.h index a50b74a8..afab1de9 100644 --- a/include/ieclass.h +++ b/include/ieclass.h @@ -45,9 +45,9 @@ class ListAttributeType; class EntityClassCollector { public: -virtual void insert( EntityClass* eclass ) = 0; -virtual void insert( const char* name, const ListAttributeType& list ){ -} + virtual void insert( EntityClass* eclass ) = 0; + virtual void insert( const char* name, const ListAttributeType& list ){ + } }; struct EntityClassScanner @@ -81,7 +81,7 @@ typedef ModulesRef EClassModulesRef; class EntityClassVisitor { public: -virtual void visit( EntityClass* eclass ) = 0; + virtual void visit( EntityClass* eclass ) = 0; }; class ModuleObserver; diff --git a/include/ientity.h b/include/ientity.h index 9a9f7e25..3c569102 100644 --- a/include/ientity.h +++ b/include/ientity.h @@ -34,53 +34,53 @@ typedef Callback1 KeyObserver; class EntityKeyValue { public: -virtual const char* c_str() const = 0; -virtual void assign( const char* other ) = 0; -virtual void attach( const KeyObserver& observer ) = 0; -virtual void detach( const KeyObserver& observer ) = 0; + virtual const char* c_str() const = 0; + virtual void assign( const char* other ) = 0; + virtual void attach( const KeyObserver& observer ) = 0; + virtual void detach( const KeyObserver& observer ) = 0; }; class Entity { public: -STRING_CONSTANT( Name, "Entity" ); + STRING_CONSTANT( Name, "Entity" ); -class Observer -{ -public: -virtual void insert( const char* key, EntityKeyValue& value ) = 0; -virtual void erase( const char* key, EntityKeyValue& value ) = 0; -virtual void clear() { }; -}; + class Observer + { + public: + virtual void insert( const char* key, EntityKeyValue& value ) = 0; + virtual void erase( const char* key, EntityKeyValue& value ) = 0; + virtual void clear() { }; + }; -class Visitor -{ -public: -virtual void visit( const char* key, const char* value ) = 0; -}; + class Visitor + { + public: + virtual void visit( const char* key, const char* value ) = 0; + }; -virtual const EntityClass& getEntityClass() const = 0; -virtual void forEachKeyValue( Visitor& visitor ) const = 0; -virtual void setKeyValue( const char* key, const char* value ) = 0; -virtual const char* getKeyValue( const char* key ) const = 0; -virtual bool isContainer() const = 0; -virtual void attach( Observer& observer ) = 0; -virtual void detach( Observer& observer ) = 0; + virtual const EntityClass& getEntityClass() const = 0; + virtual void forEachKeyValue( Visitor& visitor ) const = 0; + virtual void setKeyValue( const char* key, const char* value ) = 0; + virtual const char* getKeyValue( const char* key ) const = 0; + virtual bool isContainer() const = 0; + virtual void attach( Observer& observer ) = 0; + virtual void detach( Observer& observer ) = 0; }; class EntityCopyingVisitor : public Entity::Visitor { -Entity& m_entity; + Entity& m_entity; public: -EntityCopyingVisitor( Entity& entity ) - : m_entity( entity ){ -} - -void visit( const char* key, const char* value ){ - if ( !string_equal( key, "classname" ) ) { - m_entity.setKeyValue( key, value ); + EntityCopyingVisitor( Entity& entity ) + : m_entity( entity ){ + } + + void visit( const char* key, const char* value ){ + if ( !string_equal( key, "classname" ) ) { + m_entity.setKeyValue( key, value ); + } } -} }; inline Entity* Node_getEntity( scene::Node& node ){ @@ -110,36 +110,36 @@ class Counter; class EntityCreator { public: -INTEGER_CONSTANT( Version, 2 ); -STRING_CONSTANT( Name, "entity" ); + INTEGER_CONSTANT( Version, 2 ); + STRING_CONSTANT( Name, "entity" ); -virtual scene::Node& createEntity( EntityClass* eclass ) = 0; + virtual scene::Node& createEntity( EntityClass* eclass ) = 0; -typedef void ( *KeyValueChangedFunc )(); -virtual void setKeyValueChangedFunc( KeyValueChangedFunc func ) = 0; + typedef void ( *KeyValueChangedFunc )(); + virtual void setKeyValueChangedFunc( KeyValueChangedFunc func ) = 0; -virtual void setCounter( Counter* counter ) = 0; + virtual void setCounter( Counter* counter ) = 0; -virtual void connectEntities( const scene::Path& e1, const scene::Path& e2, int index ) = 0; + virtual void connectEntities( const scene::Path& e1, const scene::Path& e2, int index ) = 0; -virtual void setLightRadii( bool lightRadii ) = 0; -virtual bool getLightRadii() = 0; -virtual void setShowNames( bool showNames ) = 0; -virtual bool getShowNames() = 0; -virtual void setShowBboxes( bool showBboxes ) = 0; -virtual bool getShowBboxes() = 0; -virtual void setShowConnections( bool showConnections ) = 0; -virtual bool getShowConnections() = 0; -virtual void setShowNamesDist( int dist ) = 0; -virtual int getShowNamesDist() = 0; -virtual void setShowNamesRatio( int ratio ) = 0; -virtual int getShowNamesRatio() = 0; -virtual void setShowTargetNames( bool showNames ) = 0; -virtual bool getShowTargetNames() = 0; -virtual void setShowAngles( bool showAngles ) = 0; -virtual bool getShowAngles() = 0; + virtual void setLightRadii( bool lightRadii ) = 0; + virtual bool getLightRadii() = 0; + virtual void setShowNames( bool showNames ) = 0; + virtual bool getShowNames() = 0; + virtual void setShowBboxes( bool showBboxes ) = 0; + virtual bool getShowBboxes() = 0; + virtual void setShowConnections( bool showConnections ) = 0; + virtual bool getShowConnections() = 0; + virtual void setShowNamesDist( int dist ) = 0; + virtual int getShowNamesDist() = 0; + virtual void setShowNamesRatio( int ratio ) = 0; + virtual int getShowNamesRatio() = 0; + virtual void setShowTargetNames( bool showNames ) = 0; + virtual bool getShowTargetNames() = 0; + virtual void setShowAngles( bool showAngles ) = 0; + virtual bool getShowAngles() = 0; -virtual void printStatistics() const = 0; + virtual void printStatistics() const = 0; }; #include "modulesystem.h" diff --git a/include/ifilesystem.h b/include/ifilesystem.h index 6bbc0db2..99e02ede 100644 --- a/include/ifilesystem.h +++ b/include/ifilesystem.h @@ -41,65 +41,65 @@ typedef struct _GSList GSList; class VirtualFileSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "VFS" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "VFS" ); /// \brief Adds a root search \p path. /// Called before \c initialise. -virtual void initDirectory( const char *path ) = 0; + virtual void initDirectory( const char *path ) = 0; /// \brief Initialises the filesystem. /// Called after all root search paths have been added. -virtual void initialise() = 0; + virtual void initialise() = 0; /// \brief Shuts down the filesystem. -virtual void shutdown() = 0; + virtual void shutdown() = 0; /// \brief Returns the file identified by \p filename opened in binary mode, or 0 if not found. /// The caller must \c release() the file returned if it is not 0. -virtual ArchiveFile* openFile( const char* filename ) = 0; + virtual ArchiveFile* openFile( const char* filename ) = 0; /// \brief Returns the file identified by \p filename opened in text mode, or 0 if not found. /// The caller must \c release() the file returned if it is not 0. -virtual ArchiveTextFile* openTextFile( const char* filename ) = 0; + virtual ArchiveTextFile* openTextFile( const char* filename ) = 0; /// \brief Opens the file identified by \p filename and reads it into \p buffer, or sets *\p buffer to 0 if not found. /// Returns the size of the buffer allocated, or undefined value if *\p buffer is 0; /// The caller must free the allocated buffer by calling \c freeFile /// \deprecated Deprecated - use \c openFile. -virtual std::size_t loadFile( const char *filename, void **buffer ) = 0; + virtual std::size_t loadFile( const char *filename, void **buffer ) = 0; /// \brief Frees the buffer returned by \c loadFile. /// \deprecated Deprecated. -virtual void freeFile( void *p ) = 0; + virtual void freeFile( void *p ) = 0; /// \brief Calls \p callback for each directory under \p basedir. -virtual void forEachDirectory( const char* basedir, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; + virtual void forEachDirectory( const char* basedir, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; /// \brief Calls \p callback for each file under \p basedir matching \p extension. /// Use "*" as \p extension to match all file extensions. -virtual void forEachFile( const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; + virtual void forEachFile( const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; /// \brief Returns a list containing the relative names of all the directories under \p basedir. /// The caller must free the returned list by calling \c clearFileDirList; /// \deprecated Deprecated - use \c forEachDirectory. -virtual GSList* getDirList( const char *basedir ) = 0; + virtual GSList* getDirList( const char *basedir ) = 0; /// \brief Returns a list containing the relative names of the files under \p basedir (\p extension can be "*" for all files). /// The caller must free the returned list by calling \c clearFileDirList. /// \deprecated Deprecated - use \c forEachFile. -virtual GSList* getFileList( const char *basedir, const char *extension ) = 0; + virtual GSList* getFileList( const char *basedir, const char *extension ) = 0; /// \brief Frees the \p list returned from \c getDirList or \c getFileList. /// \deprecated Deprecated. -virtual void clearFileDirList( GSList **list ) = 0; + virtual void clearFileDirList( GSList **list ) = 0; /// \brief Returns the absolute filename for a relative \p name, or "" if not found. -virtual const char* findFile( const char* name ) = 0; + virtual const char* findFile( const char* name ) = 0; /// \brief Returns the filesystem root for an absolute \p name, or "" if not found. /// This can be used to convert an absolute name to a relative name. -virtual const char* findRoot( const char* name ) = 0; + virtual const char* findRoot( const char* name ) = 0; /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the filesystem is initialised or shut down. -virtual void attach( ModuleObserver& observer ) = 0; + virtual void attach( ModuleObserver& observer ) = 0; /// \brief Detach an \p observer previously-attached by calling \c attach. -virtual void detach( ModuleObserver& observer ) = 0; + virtual void detach( ModuleObserver& observer ) = 0; -virtual Archive* getArchive( const char* archiveName, bool pakonly = true ) = 0; -virtual void forEachArchive( const ArchiveNameCallback& callback, bool pakonly = true, bool reverse = false ) = 0; + virtual Archive* getArchive( const char* archiveName, bool pakonly = true ) = 0; + virtual void forEachArchive( const ArchiveNameCallback& callback, bool pakonly = true, bool reverse = false ) = 0; }; #include "modulesystem.h" diff --git a/include/ifiletypes.h b/include/ifiletypes.h index 25d2cac9..e903d3e7 100644 --- a/include/ifiletypes.h +++ b/include/ifiletypes.h @@ -27,34 +27,34 @@ class filetype_t { public: -filetype_t() - : name( "" ), pattern( "" ){ -} -filetype_t( const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true ) - : name( _name ), pattern( _pattern ), can_load( _can_load ), can_import( _can_import ), can_save( _can_save ){ -} -const char* name; -const char* pattern; -bool can_load; -bool can_import; -bool can_save; + filetype_t() + : name( "" ), pattern( "" ){ + } + filetype_t( const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true ) + : name( _name ), pattern( _pattern ), can_load( _can_load ), can_import( _can_import ), can_save( _can_save ){ + } + const char* name; + const char* pattern; + bool can_load; + bool can_import; + bool can_save; }; class IFileTypeList { public: -virtual void addType( const char* moduleName, filetype_t type ) = 0; + virtual void addType( const char* moduleName, filetype_t type ) = 0; }; class IFileTypeRegistry { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "filetypes" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "filetypes" ); -virtual void addType( const char* moduleType, const char* moduleName, filetype_t type ) = 0; -virtual void getTypeList( const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false ) = 0; + virtual void addType( const char* moduleType, const char* moduleName, filetype_t type ) = 0; + virtual void getTypeList( const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false ) = 0; }; #include "modulesystem.h" diff --git a/include/ifilter.h b/include/ifilter.h index c5e2715d..2b088cb5 100644 --- a/include/ifilter.h +++ b/include/ifilter.h @@ -54,23 +54,23 @@ enum class Filter { public: -virtual void setActive( bool active ) = 0; + virtual void setActive( bool active ) = 0; }; class Filterable { public: -virtual void updateFiltered() = 0; + virtual void updateFiltered() = 0; }; class FilterSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "filters" ); -virtual void addFilter( Filter& filter, int mask ) = 0; -virtual void registerFilterable( Filterable& filterable ) = 0; -virtual void unregisterFilterable( Filterable& filterable ) = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "filters" ); + virtual void addFilter( Filter& filter, int mask ) = 0; + virtual void registerFilterable( Filterable& filterable ) = 0; + virtual void unregisterFilterable( Filterable& filterable ) = 0; }; #include "modulesystem.h" diff --git a/include/iglrender.h b/include/iglrender.h index 53e030b5..ac01bb93 100644 --- a/include/iglrender.h +++ b/include/iglrender.h @@ -31,84 +31,84 @@ class Matrix4; class GLProgram { public: -virtual void enable() = 0; -virtual void disable() = 0; -virtual void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ) = 0; + virtual void enable() = 0; + virtual void disable() = 0; + virtual void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ) = 0; }; class OpenGLFogState { public: -OpenGLFogState() : mode( GL_EXP ), density( 0 ), start( 0 ), end( 0 ), index( 0 ), colour( 1, 1, 1, 1 ){ -} -GLenum mode; -GLfloat density; -GLfloat start; -GLfloat end; -GLint index; -Vector4 colour; + OpenGLFogState() : mode( GL_EXP ), density( 0 ), start( 0 ), end( 0 ), index( 0 ), colour( 1, 1, 1, 1 ){ + } + GLenum mode; + GLfloat density; + GLfloat start; + GLfloat end; + GLint index; + Vector4 colour; }; //! A collection of opengl state information. class OpenGLState { public: -enum ESort -{ - eSortFirst = 0, - eSortOpaque = 1, - eSortMultiFirst = 2, - eSortMultiLast = 1023, - eSortOverbrighten = 1024, - eSortFullbright = 1025, - eSortTranslucent = 1026, - eSortHighlight = 1027, - eSortOverlayFirst = 1028, - eSortOverlayLast = 2047, - eSortText = 2048, - eSortControlFirst = 2050, - eSortControlLast = 3071, - eSortGUI0 = 3072, - eSortGUI1 = 3073, - eSortLast = 4096, -}; + enum ESort + { + eSortFirst = 0, + eSortOpaque = 1, + eSortMultiFirst = 2, + eSortMultiLast = 1023, + eSortOverbrighten = 1024, + eSortFullbright = 1025, + eSortTranslucent = 1026, + eSortHighlight = 1027, + eSortOverlayFirst = 1028, + eSortOverlayLast = 2047, + eSortText = 2048, + eSortControlFirst = 2050, + eSortControlLast = 3071, + eSortGUI0 = 3072, + eSortGUI1 = 3073, + eSortLast = 4096, + }; -unsigned int m_state; -std::size_t m_sort; -GLint m_texture; -GLint m_texture1; -GLint m_texture2; -GLint m_texture3; -GLint m_texture4; -GLint m_texture5; -GLint m_texture6; -GLint m_texture7; -Vector4 m_colour; -GLenum m_blend_src, m_blend_dst; -GLenum m_depthfunc; -GLenum m_alphafunc; -GLfloat m_alpharef; -GLfloat m_linewidth; -GLfloat m_pointsize; -GLint m_linestipple_factor; -GLushort m_linestipple_pattern; -OpenGLFogState m_fog; -GLProgram* m_program; + unsigned int m_state; + std::size_t m_sort; + GLint m_texture; + GLint m_texture1; + GLint m_texture2; + GLint m_texture3; + GLint m_texture4; + GLint m_texture5; + GLint m_texture6; + GLint m_texture7; + Vector4 m_colour; + GLenum m_blend_src, m_blend_dst; + GLenum m_depthfunc; + GLenum m_alphafunc; + GLfloat m_alpharef; + GLfloat m_linewidth; + GLfloat m_pointsize; + GLint m_linestipple_factor; + GLushort m_linestipple_pattern; + OpenGLFogState m_fog; + GLProgram* m_program; -OpenGLState() : m_program( 0 ){ -} + OpenGLState() : m_program( 0 ){ + } }; class OpenGLStateLibrary { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "openglshaderlibrary" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "openglshaderlibrary" ); -virtual void getDefaultState( OpenGLState& state ) const = 0; + virtual void getDefaultState( OpenGLState& state ) const = 0; -virtual void insert( const char* name, const OpenGLState& state ) = 0; -virtual void erase( const char* name ) = 0; + virtual void insert( const char* name, const OpenGLState& state ) = 0; + virtual void erase( const char* name ) = 0; }; #include "modulesystem.h" diff --git a/include/iimage.h b/include/iimage.h index c159e657..a071756c 100644 --- a/include/iimage.h +++ b/include/iimage.h @@ -29,20 +29,20 @@ typedef unsigned char byte; class Image { public: -virtual void release() = 0; -virtual byte* getRGBAPixels() const = 0; -virtual unsigned int getWidth() const = 0; -virtual unsigned int getHeight() const = 0; + virtual void release() = 0; + virtual byte* getRGBAPixels() const = 0; + virtual unsigned int getWidth() const = 0; + virtual unsigned int getHeight() const = 0; -virtual int getSurfaceFlags() const { - return 0; -} -virtual int getContentFlags() const { - return 0; -} -virtual int getValue() const { - return 0; -} + virtual int getSurfaceFlags() const { + return 0; + } + virtual int getContentFlags() const { + return 0; + } + virtual int getValue() const { + return 0; + } }; class ArchiveFile; diff --git a/include/imap.h b/include/imap.h index 8b8cf543..6ed35e9b 100644 --- a/include/imap.h +++ b/include/imap.h @@ -31,18 +31,18 @@ class TokenWriter; class MapImporter { public: -STRING_CONSTANT( Name, "MapImporter" ); + STRING_CONSTANT( Name, "MapImporter" ); -virtual bool importTokens( Tokeniser& tokeniser ) = 0; + virtual bool importTokens( Tokeniser& tokeniser ) = 0; }; /// \brief A node whose state can be exported to a token stream. class MapExporter { public: -STRING_CONSTANT( Name, "MapExporter" ); + STRING_CONSTANT( Name, "MapExporter" ); -virtual void exportTokens( TokenWriter& writer ) const = 0; + virtual void exportTokens( TokenWriter& writer ) const = 0; }; #include "iscenegraph.h" @@ -59,13 +59,13 @@ typedef void ( *GraphTraversalFunc )( scene::Node& root, const scene::Traversabl class MapFormat { public: -INTEGER_CONSTANT( Version, 2 ); -STRING_CONSTANT( Name, "map" ); + INTEGER_CONSTANT( Version, 2 ); + STRING_CONSTANT( Name, "map" ); /// \brief Read a map graph into \p root from \p outputStream, using \p entityTable to create entities. -virtual void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const = 0; + virtual void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const = 0; /// \brief Write the map graph obtained by applying \p traverse to \p root into \p outputStream. -virtual void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const = 0; + virtual void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const = 0; }; diff --git a/include/imodel.h b/include/imodel.h index d047e90a..94690f62 100644 --- a/include/imodel.h +++ b/include/imodel.h @@ -34,9 +34,9 @@ class ArchiveFile; class ModelLoader { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "model" ); -virtual scene::Node& loadModel( ArchiveFile& file ) = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "model" ); + virtual scene::Node& loadModel( ArchiveFile& file ) = 0; }; template diff --git a/include/ipatch.h b/include/ipatch.h index e9bee3d7..01996d3f 100644 --- a/include/ipatch.h +++ b/include/ipatch.h @@ -33,187 +33,187 @@ class Node; template class ArrayReference { -std::size_t m_size; -Element* m_data; + std::size_t m_size; + Element* m_data; public: -typedef Element value_type; -typedef value_type* iterator; -typedef const value_type* const_iterator; + typedef Element value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; -ArrayReference() - : m_size( 0 ), m_data( 0 ){ -} -ArrayReference( std::size_t size, Element* data ) - : m_size( size ), m_data( data ){ -} + ArrayReference() + : m_size( 0 ), m_data( 0 ){ + } + ArrayReference( std::size_t size, Element* data ) + : m_size( size ), m_data( data ){ + } -iterator begin(){ - return m_data; -} -const_iterator begin() const { - return m_data; -} -iterator end(){ - return m_data + m_size; -} -const_iterator end() const { - return m_data + m_size; -} + iterator begin(){ + return m_data; + } + const_iterator begin() const { + return m_data; + } + iterator end(){ + return m_data + m_size; + } + const_iterator end() const { + return m_data + m_size; + } -value_type& operator[]( std::size_t index ){ + value_type& operator[]( std::size_t index ){ #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -const value_type& operator[]( std::size_t index ) const { + return m_data[index]; + } + const value_type& operator[]( std::size_t index ) const { #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -value_type* data(){ - return m_data; -} -const value_type* data() const { - return m_data; -} -std::size_t size() const { - return m_size; -} -bool empty() const { - return m_size == 0; -} + return m_data[index]; + } + value_type* data(){ + return m_data; + } + const value_type* data() const { + return m_data; + } + std::size_t size() const { + return m_size; + } + bool empty() const { + return m_size == 0; + } }; #if 0 template class MatrixIterator { -Element* m_position; + Element* m_position; -void increment(){ - ++m_position; -} + void increment(){ + ++m_position; + } public: -typedef std::bidirectional_iterator_tag iterator_category; -typedef std::ptrdiff_t difference_type; -typedef difference_type distance_type; -typedef KeyValue value_type; -typedef value_type* pointer; -typedef value_type& reference; + typedef std::bidirectional_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + typedef difference_type distance_type; + typedef KeyValue value_type; + typedef value_type* pointer; + typedef value_type& reference; -MatrixIterator( Element* position ) : m_position( position ){ -} + MatrixIterator( Element* position ) : m_position( position ){ + } -Element* position(){ - return m_position; -} + Element* position(){ + return m_position; + } -bool operator==( const MatrixIterator& other ) const { - return m_position == other.m_position; -} -bool operator!=( const MatrixIterator& other ) const { - return !operator==( other ); -} -MatrixIterator& operator++(){ - increment(); - return *this; -} -MatrixIterator operator++( int ){ - MatrixIterator tmp = *this; - increment(); - return tmp; -} -value_type& operator*() const { - return m_position->m_value; -} -value_type* operator->() const { - return &( operator*() ); -} + bool operator==( const MatrixIterator& other ) const { + return m_position == other.m_position; + } + bool operator!=( const MatrixIterator& other ) const { + return !operator==( other ); + } + MatrixIterator& operator++(){ + increment(); + return *this; + } + MatrixIterator operator++( int ){ + MatrixIterator tmp = *this; + increment(); + return tmp; + } + value_type& operator*() const { + return m_position->m_value; + } + value_type* operator->() const { + return &( operator*() ); + } }; #endif template class Matrix { -std::size_t m_x, m_y; -Element* m_data; + std::size_t m_x, m_y; + Element* m_data; public: -typedef Element value_type; -typedef value_type* iterator; -typedef const value_type* const_iterator; + typedef Element value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; -Matrix() - : m_x( 0 ), m_y( 0 ), m_data( 0 ){ -} -Matrix( std::size_t x, std::size_t y, Element* data ) - : m_x( x ), m_y( y ), m_data( data ){ -} + Matrix() + : m_x( 0 ), m_y( 0 ), m_data( 0 ){ + } + Matrix( std::size_t x, std::size_t y, Element* data ) + : m_x( x ), m_y( y ), m_data( data ){ + } -iterator begin(){ - return m_data; -} -const_iterator begin() const { - return m_data; -} -iterator end(){ - return m_data + size(); -} -const_iterator end() const { - return m_data + size(); -} + iterator begin(){ + return m_data; + } + const_iterator begin() const { + return m_data; + } + iterator end(){ + return m_data + size(); + } + const_iterator end() const { + return m_data + size(); + } -value_type& operator[]( std::size_t index ){ + value_type& operator[]( std::size_t index ){ #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -const value_type& operator[]( std::size_t index ) const { + return m_data[index]; + } + const value_type& operator[]( std::size_t index ) const { #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -value_type& operator()( std::size_t x, std::size_t y ){ + return m_data[index]; + } + value_type& operator()( std::size_t x, std::size_t y ){ #if defined( _DEBUG ) - ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); + ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); #endif - return m_data[x * m_y + y]; -} -const value_type& operator()( std::size_t x, std::size_t y ) const { + return m_data[x * m_y + y]; + } + const value_type& operator()( std::size_t x, std::size_t y ) const { #if defined( _DEBUG ) - ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); + ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); #endif - return m_data[x * m_y + y]; -} -value_type* data(){ - return m_data; -} -const value_type* data() const { - return m_data; -} -std::size_t x() const { - return m_x; -} -std::size_t y() const { - return m_y; -} -std::size_t size() const { - return m_x * m_y; -} -bool empty() const { - return m_x == 0; -} + return m_data[x * m_y + y]; + } + value_type* data(){ + return m_data; + } + const value_type* data() const { + return m_data; + } + std::size_t x() const { + return m_x; + } + std::size_t y() const { + return m_y; + } + std::size_t size() const { + return m_x * m_y; + } + bool empty() const { + return m_x == 0; + } }; class PatchControl { public: -Vector3 m_vertex; -Vector2 m_texcoord; + Vector3 m_vertex; + Vector2 m_texcoord; }; typedef Matrix PatchControlMatrix; @@ -222,15 +222,15 @@ typedef Matrix PatchControlMatrix; class PatchCreator { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "patch" ); -virtual scene::Node& createPatch() = 0; -virtual void Patch_undoSave( scene::Node& patch ) const = 0; -virtual void Patch_resize( scene::Node& patch, std::size_t width, std::size_t height ) const = 0; -virtual PatchControlMatrix Patch_getControlPoints( scene::Node& patch ) const = 0; -virtual void Patch_controlPointsChanged( scene::Node& patch ) const = 0; -virtual const char* Patch_getShader( scene::Node& patch ) const = 0; -virtual void Patch_setShader( scene::Node& patch, const char* shader ) const = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "patch" ); + virtual scene::Node& createPatch() = 0; + virtual void Patch_undoSave( scene::Node& patch ) const = 0; + virtual void Patch_resize( scene::Node& patch, std::size_t width, std::size_t height ) const = 0; + virtual PatchControlMatrix Patch_getControlPoints( scene::Node& patch ) const = 0; + virtual void Patch_controlPointsChanged( scene::Node& patch ) const = 0; + virtual const char* Patch_getShader( scene::Node& patch ) const = 0; + virtual void Patch_setShader( scene::Node& patch, const char* shader ) const = 0; }; #include "modulesystem.h" diff --git a/include/ireference.h b/include/ireference.h index 359f487c..602c4f3f 100644 --- a/include/ireference.h +++ b/include/ireference.h @@ -34,16 +34,16 @@ class ModuleObserver; class Resource { public: -virtual bool load() = 0; -virtual bool save() = 0; -virtual void flush() = 0; -virtual void refresh() = 0; -virtual scene::Node* getNode() = 0; -virtual void setNode( scene::Node* node ) = 0; -virtual void attach( ModuleObserver& observer ) = 0; -virtual void detach( ModuleObserver& observer ) = 0; -virtual void realise() = 0; -virtual void unrealise() = 0; + virtual bool load() = 0; + virtual bool save() = 0; + virtual void flush() = 0; + virtual void refresh() = 0; + virtual scene::Node* getNode() = 0; + virtual void setNode( scene::Node* node ) = 0; + virtual void attach( ModuleObserver& observer ) = 0; + virtual void detach( ModuleObserver& observer ) = 0; + virtual void realise() = 0; + virtual void unrealise() = 0; }; class EntityCreator; @@ -51,13 +51,13 @@ class EntityCreator; class ReferenceCache { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "reference" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "reference" ); -virtual Resource* capture( const char* path ) = 0; -virtual void release( const char* path ) = 0; + virtual Resource* capture( const char* path ) = 0; + virtual void release( const char* path ) = 0; -virtual void setEntityCreator( EntityCreator& entityCreator ) = 0; + virtual void setEntityCreator( EntityCreator& entityCreator ) = 0; }; #include "modulesystem.h" diff --git a/include/irender.h b/include/irender.h index 658588a5..66738edd 100644 --- a/include/irender.h +++ b/include/irender.h @@ -66,24 +66,24 @@ class Shader; class RendererLight { public: -virtual Shader* getShader() const = 0; -virtual const AABB& aabb() const = 0; -virtual bool testAABB( const AABB& other ) const = 0; -virtual const Matrix4& rotation() const = 0; -virtual const Vector3& offset() const = 0; -virtual const Vector3& colour() const = 0; -virtual bool isProjected() const = 0; -virtual const Matrix4& projection() const = 0; + virtual Shader* getShader() const = 0; + virtual const AABB& aabb() const = 0; + virtual bool testAABB( const AABB& other ) const = 0; + virtual const Matrix4& rotation() const = 0; + virtual const Vector3& offset() const = 0; + virtual const Vector3& colour() const = 0; + virtual bool isProjected() const = 0; + virtual const Matrix4& projection() const = 0; }; class LightCullable { public: -virtual bool testLight( const RendererLight& light ) const = 0; -virtual void insertLight( const RendererLight& light ){ -} -virtual void clearLights(){ -} + virtual bool testLight( const RendererLight& light ) const = 0; + virtual void insertLight( const RendererLight& light ){ + } + virtual void clearLights(){ + } }; class Renderable; @@ -94,9 +94,9 @@ typedef Callback1 RendererLightCallback; class LightList { public: -virtual void evaluateLights() const = 0; -virtual void lightsChanged() const = 0; -virtual void forEachLight( const RendererLightCallback& callback ) const = 0; + virtual void evaluateLights() const = 0; + virtual void lightsChanged() const = 0; + virtual void forEachLight( const RendererLightCallback& callback ) const = 0; }; const int c_attr_TexCoord0 = 1; @@ -106,7 +106,7 @@ const int c_attr_Binormal = 4; class OpenGLRenderable { public: -virtual void render( RenderStateFlags state ) const = 0; + virtual void render( RenderStateFlags state ) const = 0; }; class Matrix4; @@ -116,42 +116,42 @@ class ModuleObserver; class Shader { public: -virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0 ) = 0; -virtual void incrementUsed() = 0; -virtual void decrementUsed() = 0; -virtual void attach( ModuleObserver& observer ) = 0; -virtual void detach( ModuleObserver& observer ) = 0; -virtual qtexture_t& getTexture() const = 0; -virtual unsigned int getFlags() const = 0; + virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0 ) = 0; + virtual void incrementUsed() = 0; + virtual void decrementUsed() = 0; + virtual void attach( ModuleObserver& observer ) = 0; + virtual void detach( ModuleObserver& observer ) = 0; + virtual qtexture_t& getTexture() const = 0; + virtual unsigned int getFlags() const = 0; }; class ShaderCache { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "renderstate" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "renderstate" ); -virtual Shader* capture( const char* name ) = 0; -virtual void release( const char* name ) = 0; -/*! Render all Shader objects. */ -virtual void render( RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3( 0, 0, 0 ) ) = 0; + virtual Shader* capture( const char* name ) = 0; + virtual void release( const char* name ) = 0; + /*! Render all Shader objects. */ + virtual void render( RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3( 0, 0, 0 ) ) = 0; -virtual void realise() = 0; -virtual void unrealise() = 0; + virtual void realise() = 0; + virtual void unrealise() = 0; -virtual bool lightingSupported() const = 0; -virtual bool useShaderLanguage() const = 0; + virtual bool lightingSupported() const = 0; + virtual bool useShaderLanguage() const = 0; -virtual const LightList& attach( LightCullable& cullable ) = 0; -virtual void detach( LightCullable& cullable ) = 0; -virtual void changed( LightCullable& cullable ) = 0; -virtual void attach( RendererLight& light ) = 0; -virtual void detach( RendererLight& light ) = 0; -virtual void changed( RendererLight& light ) = 0; + virtual const LightList& attach( LightCullable& cullable ) = 0; + virtual void detach( LightCullable& cullable ) = 0; + virtual void changed( LightCullable& cullable ) = 0; + virtual void attach( RendererLight& light ) = 0; + virtual void detach( RendererLight& light ) = 0; + virtual void changed( RendererLight& light ) = 0; -virtual void attachRenderable( const Renderable& renderable ) = 0; -virtual void detachRenderable( const Renderable& renderable ) = 0; -virtual void forEachRenderable( const RenderableCallback& callback ) const = 0; + virtual void attachRenderable( const Renderable& renderable ) = 0; + virtual void detachRenderable( const Renderable& renderable ) = 0; + virtual void forEachRenderable( const RenderableCallback& callback ) const = 0; }; #include "modulesystem.h" diff --git a/include/iscenegraph.h b/include/iscenegraph.h index 6b28b0fc..71cc8bf6 100644 --- a/include/iscenegraph.h +++ b/include/iscenegraph.h @@ -70,121 +70,121 @@ typedef Stack Path; class Graph { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "scenegraph" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "scenegraph" ); -class Walker -{ -public: + class Walker + { + public: /// \brief Called before traversing the first child-instance of 'instance'. If the return value is false, the children of the current instance are not traversed. -virtual bool pre( const Path& path, Instance& instance ) const = 0; + virtual bool pre( const Path& path, Instance& instance ) const = 0; /// \brief Called after traversing the last child-instance of 'instance'. -virtual void post( const Path& path, Instance& instance ) const { -} -}; + virtual void post( const Path& path, Instance& instance ) const { + } + }; /// \brief Returns the root-node of the graph. -virtual Node& root() = 0; + virtual Node& root() = 0; /// \brief Sets the root-node of the graph to be 'node'. -virtual void insert_root( Node& root ) = 0; + virtual void insert_root( Node& root ) = 0; /// \brief Clears the root-node of the graph. -virtual void erase_root() = 0; + virtual void erase_root() = 0; /// \brief Traverses all nodes in the graph depth-first, starting from the root node. -virtual void traverse( const Walker& walker ) = 0; + virtual void traverse( const Walker& walker ) = 0; /// \brief Traverses all nodes in the graph depth-first, starting from 'start'. -virtual void traverse_subgraph( const Walker& walker, const Path& start ) = 0; + virtual void traverse_subgraph( const Walker& walker, const Path& start ) = 0; /// \brief Returns the instance at the location identified by 'path', or 0 if it does not exist. -virtual scene::Instance* find( const Path& path ) = 0; + virtual scene::Instance* find( const Path& path ) = 0; /// \brief Invokes all scene-changed callbacks. Called when any part of the scene changes the way it will appear when the scene is rendered. /// \todo Move to a separate class. -virtual void sceneChanged() = 0; + virtual void sceneChanged() = 0; /// \brief Add a \p callback to be invoked when the scene changes. /// \todo Move to a separate class. -virtual void addSceneChangedCallback( const SignalHandler& handler ) = 0; + virtual void addSceneChangedCallback( const SignalHandler& handler ) = 0; /// \brief Invokes all bounds-changed callbacks. Called when the bounds of any instance in the scene change. /// \todo Move to a separate class. -virtual void boundsChanged() = 0; + virtual void boundsChanged() = 0; /// \brief Add a \p callback to be invoked when the bounds of any instance in the scene change. -virtual SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ) = 0; + virtual SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ) = 0; /// \brief Remove a \p callback to be invoked when the bounds of any instance in the scene change. -virtual void removeBoundsChangedCallback( SignalHandlerId id ) = 0; + virtual void removeBoundsChangedCallback( SignalHandlerId id ) = 0; -virtual TypeId getNodeTypeId( const char* name ) = 0; -virtual TypeId getInstanceTypeId( const char* name ) = 0; + virtual TypeId getNodeTypeId( const char* name ) = 0; + virtual TypeId getInstanceTypeId( const char* name ) = 0; }; class Traversable { public: -STRING_CONSTANT( Name, "scene::Traversable" ); + STRING_CONSTANT( Name, "scene::Traversable" ); -class Observer -{ -public: + class Observer + { + public: /// \brief Called when a node is added to the container. -virtual void insert( Node& node ) = 0; + virtual void insert( Node& node ) = 0; /// \brief Called when a node is removed from the container. -virtual void erase( Node& node ) = 0; -}; + virtual void erase( Node& node ) = 0; + }; -class Walker -{ -public: + class Walker + { + public: /// \brief Called before traversing the first child-node of 'node'. If the return value is false, the children of the current node are not traversed. -virtual bool pre( Node& node ) const = 0; + virtual bool pre( Node& node ) const = 0; /// \brief Called after traversing the last child-node of 'node'. -virtual void post( Node& node ) const { -} -}; + virtual void post( Node& node ) const { + } + }; /// \brief Adds a node to the container. -virtual void insert( Node& node ) = 0; + virtual void insert( Node& node ) = 0; /// \brief Removes a node from the container. -virtual void erase( Node& node ) = 0; + virtual void erase( Node& node ) = 0; /// \brief Traverses the subgraphs rooted at each node in the container, depth-first. -virtual void traverse( const Walker& walker ) = 0; + virtual void traverse( const Walker& walker ) = 0; /// \brief Returns true if the container contains no nodes. -virtual bool empty() const = 0; + virtual bool empty() const = 0; }; class Instantiable { public: -STRING_CONSTANT( Name, "scene::Instantiable" ); + STRING_CONSTANT( Name, "scene::Instantiable" ); -class Observer -{ -public: + class Observer + { + public: /// \brief Called when an instance is added to the container. -virtual void insert( scene::Instance* instance ) = 0; + virtual void insert( scene::Instance* instance ) = 0; /// \brief Called when an instance is removed from the container. -virtual void erase( scene::Instance* instance ) = 0; -}; + virtual void erase( scene::Instance* instance ) = 0; + }; -class Visitor -{ -public: -virtual void visit( Instance& instance ) const = 0; -}; + class Visitor + { + public: + virtual void visit( Instance& instance ) const = 0; + }; /// \brief Returns a new instance uniquely identified by 'path'. -virtual scene::Instance* create( const scene::Path& path, scene::Instance* parent ) = 0; + virtual scene::Instance* create( const scene::Path& path, scene::Instance* parent ) = 0; /// \brief Calls Visitor::visit(instance) for each instance in the container. -virtual void forEachInstance( const Visitor& visitor ) = 0; + virtual void forEachInstance( const Visitor& visitor ) = 0; /// \brief Adds an instance to the container. -virtual void insert( Observer* observer, const Path& path, scene::Instance* instance ) = 0; + virtual void insert( Observer* observer, const Path& path, scene::Instance* instance ) = 0; /// \brief Returns an instance removed from the container. -virtual scene::Instance* erase( Observer* observer, const Path& path ) = 0; + virtual scene::Instance* erase( Observer* observer, const Path& path ) = 0; }; class Cloneable { public: -STRING_CONSTANT( Name, "scene::Cloneable" ); + STRING_CONSTANT( Name, "scene::Cloneable" ); /// \brief Returns a copy of itself. -virtual scene::Node& clone() const = 0; + virtual scene::Node& clone() const = 0; }; } diff --git a/include/iscriplib.h b/include/iscriplib.h index c4f96c37..559daa56 100644 --- a/include/iscriplib.h +++ b/include/iscriplib.h @@ -33,13 +33,13 @@ class Tokeniser { public: -virtual void release() = 0; -virtual void nextLine() = 0; -virtual const char* getToken() = 0; -virtual void ungetToken() = 0; -virtual std::size_t getLine() const = 0; -virtual std::size_t getColumn() const = 0; -virtual bool bufferContains( const char* str ) = 0; + virtual void release() = 0; + virtual void nextLine() = 0; + virtual const char* getToken() = 0; + virtual void ungetToken() = 0; + virtual std::size_t getLine() const = 0; + virtual std::size_t getColumn() const = 0; + virtual bool bufferContains( const char* str ) = 0; }; class TextInputStream; @@ -47,13 +47,13 @@ class TextInputStream; class TokenWriter { public: -virtual void release() = 0; -virtual void nextLine() = 0; -virtual void writeToken( const char* token ) = 0; -virtual void writeString( const char* string ) = 0; -virtual void writeInteger( int i ) = 0; -virtual void writeUnsigned( std::size_t i ) = 0; -virtual void writeFloat( double f ) = 0; + virtual void release() = 0; + virtual void nextLine() = 0; + virtual void writeToken( const char* token ) = 0; + virtual void writeString( const char* string ) = 0; + virtual void writeInteger( int i ) = 0; + virtual void writeUnsigned( std::size_t i ) = 0; + virtual void writeFloat( double f ) = 0; }; class TextOutputStream; diff --git a/include/iselection.h b/include/iselection.h index dcf77910..e3aefcd7 100644 --- a/include/iselection.h +++ b/include/iselection.h @@ -33,10 +33,10 @@ class View; class Selectable { public: -STRING_CONSTANT( Name, "Selectable" ); + STRING_CONSTANT( Name, "Selectable" ); -virtual void setSelected( bool select ) = 0; -virtual bool isSelected() const = 0; + virtual void setSelected( bool select ) = 0; + virtual bool isSelected() const = 0; }; namespace scene @@ -47,7 +47,7 @@ class Instance; class InstanceSelectionObserver { public: -virtual void onSelectedChanged( scene::Instance& instance ) = 0; + virtual void onSelectedChanged( scene::Instance& instance ) = 0; }; template class BasicVector3; @@ -64,76 +64,76 @@ typedef SignalHandler1 SelectionChangeHandler; class SelectionSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "selection" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "selection" ); -enum EMode -{ - eEntity, - ePrimitive, - eComponent, -}; + enum EMode + { + eEntity, + ePrimitive, + eComponent, + }; -enum EComponentMode -{ - eDefault, - eVertex, - eEdge, - eFace, -}; + enum EComponentMode + { + eDefault, + eVertex, + eEdge, + eFace, + }; -enum EManipulatorMode -{ - eTranslate, - eRotate, - eScale, - eSkew, - eDrag, - eClip, - eBuild, - eUV, -}; + enum EManipulatorMode + { + eTranslate, + eRotate, + eScale, + eSkew, + eDrag, + eClip, + eBuild, + eUV, + }; -virtual void SetMode( EMode mode ) = 0; -virtual EMode Mode() const = 0; -virtual void SetComponentMode( EComponentMode mode ) = 0; -virtual EComponentMode ComponentMode() const = 0; -virtual void SetManipulatorMode( EManipulatorMode mode ) = 0; -virtual EManipulatorMode ManipulatorMode() const = 0; + virtual void SetMode( EMode mode ) = 0; + virtual EMode Mode() const = 0; + virtual void SetComponentMode( EComponentMode mode ) = 0; + virtual EComponentMode ComponentMode() const = 0; + virtual void SetManipulatorMode( EManipulatorMode mode ) = 0; + virtual EManipulatorMode ManipulatorMode() const = 0; -virtual SelectionChangeCallback getObserver( EMode mode ) = 0; -virtual std::size_t countSelected() const = 0; -virtual std::size_t countSelectedComponents() const = 0; -virtual void countSelectedStuff( std::size_t& brushes, std::size_t& patches, std::size_t& entities ) const = 0; -virtual void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ) = 0; -virtual void onComponentSelection( scene::Instance& instance, const Selectable& selectable ) = 0; -virtual scene::Instance& firstSelected() const = 0; -virtual scene::Instance& ultimateSelected() const = 0; -virtual scene::Instance& penultimateSelected() const = 0; -virtual void setSelectedAll( bool selected ) = 0; -virtual void setSelectedAllComponents( bool selected ) = 0; + virtual SelectionChangeCallback getObserver( EMode mode ) = 0; + virtual std::size_t countSelected() const = 0; + virtual std::size_t countSelectedComponents() const = 0; + virtual void countSelectedStuff( std::size_t& brushes, std::size_t& patches, std::size_t& entities ) const = 0; + virtual void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ) = 0; + virtual void onComponentSelection( scene::Instance& instance, const Selectable& selectable ) = 0; + virtual scene::Instance& firstSelected() const = 0; + virtual scene::Instance& ultimateSelected() const = 0; + virtual scene::Instance& penultimateSelected() const = 0; + virtual void setSelectedAll( bool selected ) = 0; + virtual void setSelectedAllComponents( bool selected ) = 0; -class Visitor -{ -public: -virtual void visit( scene::Instance& instance ) const = 0; -}; -virtual void foreachSelected( const Visitor& visitor ) const = 0; -virtual void foreachSelectedComponent( const Visitor& visitor ) const = 0; + class Visitor + { + public: + virtual void visit( scene::Instance& instance ) const = 0; + }; + virtual void foreachSelected( const Visitor& visitor ) const = 0; + virtual void foreachSelectedComponent( const Visitor& visitor ) const = 0; -virtual void addSelectionChangeCallback( const SelectionChangeHandler& handler ) = 0; + virtual void addSelectionChangeCallback( const SelectionChangeHandler& handler ) = 0; -virtual void NudgeManipulator( const Vector3& nudge, const Vector3& view ) = 0; + virtual void NudgeManipulator( const Vector3& nudge, const Vector3& view ) = 0; -virtual void translateSelected( const Vector3& translation ) = 0; -virtual void rotateSelected( const Quaternion& rotation, bool snapOrigin = false ) = 0; -virtual void scaleSelected( const Vector3& scaling, bool snapOrigin = false ) = 0; -virtual void repeatTransforms( const Callback& clone ) = 0; + virtual void translateSelected( const Vector3& translation ) = 0; + virtual void rotateSelected( const Quaternion& rotation, bool snapOrigin = false ) = 0; + virtual void scaleSelected( const Vector3& scaling, bool snapOrigin = false ) = 0; + virtual void repeatTransforms( const Callback& clone ) = 0; -virtual void pivotChanged() const = 0; -virtual void setCustomTransformOrigin( const Vector3& origin, const bool set[3] ) const = 0; + virtual void pivotChanged() const = 0; + virtual void setCustomTransformOrigin( const Vector3& origin, const bool set[3] ) const = 0; -virtual const AABB& getBoundsSelected() const = 0; /* object bounds */ + virtual const AABB& getBoundsSelected() const = 0; /* object bounds */ }; #include "modulesystem.h" diff --git a/include/ishaders.h b/include/ishaders.h index 326e25c7..fe2e8bd1 100644 --- a/include/ishaders.h +++ b/include/ishaders.h @@ -58,19 +58,19 @@ const BlendFactor BLEND_SRC_ALPHA_SATURATE = 10; class BlendFunc { public: -BlendFunc( BlendFactor src, BlendFactor dst ) : m_src( src ), m_dst( dst ){ -} -BlendFactor m_src; -BlendFactor m_dst; + BlendFunc( BlendFactor src, BlendFactor dst ) : m_src( src ), m_dst( dst ){ + } + BlendFactor m_src; + BlendFactor m_dst; }; class ShaderLayer { public: -virtual qtexture_t* texture() const = 0; -virtual BlendFunc blendFunc() const = 0; -virtual bool clampToBorder() const = 0; -virtual float alphaTest() const = 0; + virtual qtexture_t* texture() const = 0; + virtual BlendFunc blendFunc() const = 0; + virtual bool clampToBorder() const = 0; + virtual float alphaTest() const = 0; }; typedef Callback1 ShaderLayerCallback; @@ -79,51 +79,51 @@ typedef Callback1 ShaderLayerCallback; class IShader { public: -enum EAlphaFunc -{ - eAlways, - eEqual, - eLess, - eGreater, - eLEqual, - eGEqual, -}; -enum ECull -{ - eCullNone, - eCullBack, -}; + enum EAlphaFunc + { + eAlways, + eEqual, + eLess, + eGreater, + eLEqual, + eGEqual, + }; + enum ECull + { + eCullNone, + eCullBack, + }; // Increment the number of references to this object -virtual void IncRef() = 0; + virtual void IncRef() = 0; // Decrement the reference count -virtual void DecRef() = 0; + virtual void DecRef() = 0; // get/set the qtexture_t* Radiant uses to represent this shader object -virtual qtexture_t* getTexture() const = 0; -virtual qtexture_t* getDiffuse() const = 0; -virtual qtexture_t* getBump() const = 0; -virtual qtexture_t* getSpecular() const = 0; + virtual qtexture_t* getTexture() const = 0; + virtual qtexture_t* getDiffuse() const = 0; + virtual qtexture_t* getBump() const = 0; + virtual qtexture_t* getSpecular() const = 0; // get shader name -virtual const char* getName() const = 0; -virtual bool IsInUse() const = 0; -virtual void SetInUse( bool bInUse ) = 0; + virtual const char* getName() const = 0; + virtual bool IsInUse() const = 0; + virtual void SetInUse( bool bInUse ) = 0; // get the editor flags (QER_NOCARVE QER_TRANS) -virtual int getFlags() const = 0; + virtual int getFlags() const = 0; // get the transparency value -virtual float getTrans() const = 0; + virtual float getTrans() const = 0; // test if it's a true shader, or a default shader created to wrap around a texture -virtual bool IsDefault() const = 0; + virtual bool IsDefault() const = 0; // get the alphaFunc -virtual void getAlphaFunc( EAlphaFunc *func, float *ref ) = 0; -virtual BlendFunc getBlendFunc() const = 0; + virtual void getAlphaFunc( EAlphaFunc *func, float *ref ) = 0; + virtual BlendFunc getBlendFunc() const = 0; // get the cull type -virtual ECull getCull() = 0; + virtual ECull getCull() = 0; // get shader file name (ie the file where this one is defined) -virtual const char* getShaderFileName() const = 0; + virtual const char* getShaderFileName() const = 0; -virtual const ShaderLayer* firstLayer() const = 0; -virtual void forEachLayer( const ShaderLayerCallback& layer ) const = 0; + virtual const ShaderLayer* firstLayer() const = 0; + virtual void forEachLayer( const ShaderLayerCallback& layer ) const = 0; -virtual qtexture_t* lightFalloffImage() const = 0; + virtual qtexture_t* lightFalloffImage() const = 0; }; typedef struct _GSList GSList; @@ -134,34 +134,34 @@ class ModuleObserver; class ShaderSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "shaders" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "shaders" ); // NOTE: shader and texture names used must be full path. // Shaders usable as textures have prefix equal to getTexturePrefix() -virtual void realise() = 0; -virtual void unrealise() = 0; -virtual void refresh() = 0; + virtual void realise() = 0; + virtual void unrealise() = 0; + virtual void refresh() = 0; // activate the shader for a given name and return it // will return the default shader if name is not found -virtual IShader* getShaderForName( const char* name ) = 0; + virtual IShader* getShaderForName( const char* name ) = 0; -virtual void foreachShaderName( const ShaderNameCallback& callback ) = 0; + virtual void foreachShaderName( const ShaderNameCallback& callback ) = 0; // iterate over the list of active shaders -virtual void beginActiveShadersIterator() = 0; -virtual bool endActiveShadersIterator() = 0; -virtual IShader* dereferenceActiveShadersIterator() = 0; -virtual void incrementActiveShadersIterator() = 0; + virtual void beginActiveShadersIterator() = 0; + virtual bool endActiveShadersIterator() = 0; + virtual IShader* dereferenceActiveShadersIterator() = 0; + virtual void incrementActiveShadersIterator() = 0; -virtual void setActiveShadersChangedNotify( const Callback& notify ) = 0; + virtual void setActiveShadersChangedNotify( const Callback& notify ) = 0; -virtual void attach( ModuleObserver& observer ) = 0; -virtual void detach( ModuleObserver& observer ) = 0; + virtual void attach( ModuleObserver& observer ) = 0; + virtual void detach( ModuleObserver& observer ) = 0; -virtual void setLightingEnabled( bool enabled ) = 0; + virtual void setLightingEnabled( bool enabled ) = 0; -virtual const char* getTexturePrefix() const = 0; + virtual const char* getTexturePrefix() const = 0; }; #include "modulesystem.h" diff --git a/include/itexdef.h b/include/itexdef.h index 9d01847f..08ab4d9e 100644 --- a/include/itexdef.h +++ b/include/itexdef.h @@ -25,17 +25,17 @@ class texdef_t { public: -float shift[2]; -float rotate; -float scale[2]; + float shift[2]; + float rotate; + float scale[2]; -texdef_t(){ - shift[0] = 0; - shift[1] = 0; - rotate = 0; - scale[0] = 1; - scale[1] = 1; -} + texdef_t(){ + shift[0] = 0; + shift[1] = 0; + rotate = 0; + scale[0] = 1; + scale[1] = 1; + } }; #endif diff --git a/include/itextstream.h b/include/itextstream.h index 53e61b68..a625e453 100644 --- a/include/itextstream.h +++ b/include/itextstream.h @@ -34,7 +34,7 @@ class TextInputStream public: /// \brief Attempts to read the next \p length characters from the stream to \p buffer. /// Returns the number of characters actually stored in \p buffer. -virtual std::size_t read( char* buffer, std::size_t length ) = 0; + virtual std::size_t read( char* buffer, std::size_t length ) = 0; }; /// \brief A write-only character-stream. @@ -43,7 +43,7 @@ class TextOutputStream public: /// \brief Attempts to write \p length characters to the stream from \p buffer. /// Returns the number of characters actually read from \p buffer. -virtual std::size_t write( const char* buffer, std::size_t length ) = 0; + virtual std::size_t write( const char* buffer, std::size_t length ) = 0; }; /// \brief Calls the overloaded function ostream_write() to perform text formatting specific to the type being written. @@ -68,25 +68,25 @@ inline TextOutputStream& operator<<( TextOutputStream& ostream, const T& t ){ class NullOutputStream : public TextOutputStream { public: -std::size_t write( const char*, std::size_t length ){ - return length; -} + std::size_t write( const char*, std::size_t length ){ + return length; + } }; class OutputStreamHolder { -NullOutputStream m_nullOutputStream; -TextOutputStream* m_outputStream; + NullOutputStream m_nullOutputStream; + TextOutputStream* m_outputStream; public: -OutputStreamHolder() - : m_outputStream( &m_nullOutputStream ){ -} -void setOutputStream( TextOutputStream& outputStream ){ - m_outputStream = &outputStream; -} -TextOutputStream& getOutputStream(){ - return *m_outputStream; -} + OutputStreamHolder() + : m_outputStream( &m_nullOutputStream ){ + } + void setOutputStream( TextOutputStream& outputStream ){ + m_outputStream = &outputStream; + } + TextOutputStream& getOutputStream(){ + return *m_outputStream; + } }; typedef Static GlobalOutputStream; diff --git a/include/itextures.h b/include/itextures.h index cc91399d..a07c6d49 100644 --- a/include/itextures.h +++ b/include/itextures.h @@ -29,16 +29,16 @@ struct qtexture_t; class LoadImageCallback { -typedef Image* ( *LoadFunc )( void* environment, const char* name ); + typedef Image* ( *LoadFunc )( void* environment, const char* name ); public: -void* m_environment; -LoadFunc m_func; + void* m_environment; + LoadFunc m_func; -LoadImageCallback( void* environment, LoadFunc func ) : m_environment( environment ), m_func( func ){ -} -Image* loadImage( const char* name ) const { - return m_func( m_environment, name ); -} + LoadImageCallback( void* environment, LoadFunc func ) : m_environment( environment ), m_func( func ){ + } + Image* loadImage( const char* name ) const { + return m_func( m_environment, name ); + } }; inline bool operator==( const LoadImageCallback& self, const LoadImageCallback& other ){ @@ -46,28 +46,28 @@ inline bool operator==( const LoadImageCallback& self, const LoadImageCallback& } inline bool operator<( const LoadImageCallback& self, const LoadImageCallback& other ){ return self.m_environment < other.m_environment || - ( !( other.m_environment < self.m_environment ) && self.m_func < other.m_func ); + ( !( other.m_environment < self.m_environment ) && self.m_func < other.m_func ); } class TexturesCacheObserver { public: -virtual void unrealise() = 0; -virtual void realise() = 0; + virtual void unrealise() = 0; + virtual void realise() = 0; }; class TexturesCache { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "textures" ); -virtual LoadImageCallback defaultLoader() const = 0; -virtual Image* loadImage( const char* name ) = 0; -virtual qtexture_t* capture( const char* name ) = 0; -virtual qtexture_t* capture( const LoadImageCallback& load, const char* name ) = 0; -virtual void release( qtexture_t* texture ) = 0; -virtual void attach( TexturesCacheObserver& observer ) = 0; -virtual void detach( TexturesCacheObserver& observer ) = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "textures" ); + virtual LoadImageCallback defaultLoader() const = 0; + virtual Image* loadImage( const char* name ) = 0; + virtual qtexture_t* capture( const char* name ) = 0; + virtual qtexture_t* capture( const LoadImageCallback& load, const char* name ) = 0; + virtual void release( qtexture_t* texture ) = 0; + virtual void attach( TexturesCacheObserver& observer ) = 0; + virtual void detach( TexturesCacheObserver& observer ) = 0; }; #include "modulesystem.h" diff --git a/include/itoolbar.h b/include/itoolbar.h index 62d82b6e..a83f5524 100644 --- a/include/itoolbar.h +++ b/include/itoolbar.h @@ -28,19 +28,19 @@ class IToolbarButton { public: -enum EType -{ - eSpace, - eButton, - eToggleButton, - eRadioButton, -}; + enum EType + { + eSpace, + eButton, + eToggleButton, + eRadioButton, + }; -virtual const char* getImage() const = 0; -virtual const char* getText() const = 0; -virtual const char* getTooltip() const = 0; -virtual EType getType() const = 0; -virtual void activate() const = 0; + virtual const char* getImage() const = 0; + virtual const char* getText() const = 0; + virtual const char* getTooltip() const = 0; + virtual EType getType() const = 0; + virtual void activate() const = 0; }; typedef std::size_t ( *PFN_TOOLBARBUTTONCOUNT )(); diff --git a/include/iundo.h b/include/iundo.h index eb1e8681..c13a6242 100644 --- a/include/iundo.h +++ b/include/iundo.h @@ -32,60 +32,60 @@ class UndoMemento { public: -virtual void release() = 0; -virtual ~UndoMemento() { -} + virtual void release() = 0; + virtual ~UndoMemento() { + } }; class Undoable { public: -virtual UndoMemento* exportState() const = 0; -virtual void importState( const UndoMemento* state ) = 0; -virtual ~Undoable() { -} + virtual UndoMemento* exportState() const = 0; + virtual void importState( const UndoMemento* state ) = 0; + virtual ~Undoable() { + } }; class UndoObserver { public: -virtual void save( Undoable* undoable ) = 0; -virtual ~UndoObserver() { -} + virtual void save( Undoable* undoable ) = 0; + virtual ~UndoObserver() { + } }; class UndoTracker { public: -virtual void clear() = 0; -virtual void begin() = 0; -virtual void undo() = 0; -virtual void redo() = 0; -virtual ~UndoTracker() { -} + virtual void clear() = 0; + virtual void begin() = 0; + virtual void undo() = 0; + virtual void redo() = 0; + virtual ~UndoTracker() { + } }; class UndoSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "undo" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "undo" ); -virtual UndoObserver* observer( Undoable* undoable ) = 0; -virtual void release( Undoable* undoable ) = 0; + virtual UndoObserver* observer( Undoable* undoable ) = 0; + virtual void release( Undoable* undoable ) = 0; -virtual std::size_t size() const = 0; -virtual void start() = 0; -virtual void finish( const char* command ) = 0; -virtual void undo() = 0; -virtual void redo() = 0; -virtual void clear() = 0; + virtual std::size_t size() const = 0; + virtual void start() = 0; + virtual void finish( const char* command ) = 0; + virtual void undo() = 0; + virtual void redo() = 0; + virtual void clear() = 0; -virtual void trackerAttach( UndoTracker& tracker ) = 0; -virtual void trackerDetach( UndoTracker& tracker ) = 0; + virtual void trackerAttach( UndoTracker& tracker ) = 0; + virtual void trackerDetach( UndoTracker& tracker ) = 0; -virtual ~UndoSystem() { -} + virtual ~UndoSystem() { + } }; #include "modulesystem.h" @@ -104,14 +104,14 @@ inline UndoSystem& GlobalUndoSystem(){ class UndoableCommand { -const char* m_command; + const char* m_command; public: -UndoableCommand( const char* command ) : m_command( command ){ - GlobalUndoSystem().start(); -} -~UndoableCommand(){ - GlobalUndoSystem().finish( m_command ); -} + UndoableCommand( const char* command ) : m_command( command ){ + GlobalUndoSystem().start(); + } + ~UndoableCommand(){ + GlobalUndoSystem().finish( m_command ); + } }; diff --git a/include/mapfile.h b/include/mapfile.h index 4f5f1a74..d5f8b735 100644 --- a/include/mapfile.h +++ b/include/mapfile.h @@ -38,13 +38,13 @@ const std::size_t VARIABLE_IS_NOT_USED MAPFILE_MAX_CHANGES = std::numeric_limits class MapFile { public: -STRING_CONSTANT( Name, "MapFile" ); + STRING_CONSTANT( Name, "MapFile" ); -virtual void save() = 0; -virtual bool saved() const = 0; -virtual void changed() = 0; -virtual void setChangedCallback( const Callback& changed ) = 0; -virtual std::size_t changes() const = 0; + virtual void save() = 0; + virtual bool saved() const = 0; + virtual void changed() = 0; + virtual void setChangedCallback( const Callback& changed ) = 0; + virtual std::size_t changes() const = 0; }; #include "scenelib.h" diff --git a/include/modelskin.h b/include/modelskin.h index bb5922ee..ac2f486d 100644 --- a/include/modelskin.h +++ b/include/modelskin.h @@ -28,10 +28,10 @@ class SkinRemap { public: -const char* m_from; -const char* m_to; -SkinRemap( const char* from, const char* to ) : m_from( from ), m_to( to ){ -} + const char* m_from; + const char* m_to; + SkinRemap( const char* from, const char* to ) : m_from( from ), m_to( to ){ + } }; typedef Callback1 SkinRemapCallback; @@ -40,36 +40,36 @@ class ModuleObserver; class ModelSkin { public: -STRING_CONSTANT( Name, "ModelSkin" ); + STRING_CONSTANT( Name, "ModelSkin" ); /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the skin is loaded or unloaded. -virtual void attach( ModuleObserver& observer ) = 0; + virtual void attach( ModuleObserver& observer ) = 0; /// \brief Detach an \p observer previously-attached by calling \c attach. -virtual void detach( ModuleObserver& observer ) = 0; + virtual void detach( ModuleObserver& observer ) = 0; /// \brief Returns true if this skin is currently loaded. -virtual bool realised() const = 0; + virtual bool realised() const = 0; /// \brief Returns the shader identifier that \p name remaps to, or "" if not found or not realised. -virtual const char* getRemap( const char* name ) const = 0; + virtual const char* getRemap( const char* name ) const = 0; /// \brief Calls \p callback for each remap pair. Has no effect if not realised. -virtual void forEachRemap( const SkinRemapCallback& callback ) const = 0; + virtual void forEachRemap( const SkinRemapCallback& callback ) const = 0; }; class SkinnedModel { public: -STRING_CONSTANT( Name, "SkinnedModel" ); + STRING_CONSTANT( Name, "SkinnedModel" ); /// \brief Instructs the skinned model to update its skin. -virtual void skinChanged() = 0; + virtual void skinChanged() = 0; }; class ModelSkinCache { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "modelskin" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "modelskin" ); /// \brief Increments the reference count of and returns a reference to the skin uniquely identified by 'name'. -virtual ModelSkin& capture( const char* name ) = 0; + virtual ModelSkin& capture( const char* name ) = 0; /// \brief Decrements the reference-count of the skin uniquely identified by 'name'. -virtual void release( const char* name ) = 0; + virtual void release( const char* name ) = 0; }; diff --git a/include/moduleobserver.h b/include/moduleobserver.h index 496d6f2e..1ded4202 100644 --- a/include/moduleobserver.h +++ b/include/moduleobserver.h @@ -25,8 +25,8 @@ class ModuleObserver { public: -virtual void unrealise() = 0; -virtual void realise() = 0; + virtual void unrealise() = 0; + virtual void realise() = 0; }; #endif diff --git a/include/modulesystem.h b/include/modulesystem.h index a9a76dec..c6f2a9ae 100644 --- a/include/modulesystem.h +++ b/include/modulesystem.h @@ -42,9 +42,9 @@ class Module { public: -virtual void capture() = 0; -virtual void release() = 0; -virtual void* getTable() = 0; + virtual void capture() = 0; + virtual void release() = 0; + virtual void* getTable() = 0; }; inline void* Module_getTable( Module& module ){ @@ -57,38 +57,38 @@ class DebugMessageHandler; class ModuleServer { public: -class Visitor -{ -public: -virtual void visit( const char* name, Module& module ) const = 0; -}; + class Visitor + { + public: + virtual void visit( const char* name, Module& module ) const = 0; + }; -virtual void setError( bool error ) = 0; -virtual bool getError() const = 0; + virtual void setError( bool error ) = 0; + virtual bool getError() const = 0; -virtual TextOutputStream& getOutputStream() = 0; -virtual TextOutputStream& getWarningStream() = 0; -virtual TextOutputStream& getErrorStream() = 0; -virtual DebugMessageHandler& getDebugMessageHandler() = 0; + virtual TextOutputStream& getOutputStream() = 0; + virtual TextOutputStream& getWarningStream() = 0; + virtual TextOutputStream& getErrorStream() = 0; + virtual DebugMessageHandler& getDebugMessageHandler() = 0; -virtual void registerModule( const char* type, int version, const char* name, Module& module ) = 0; -virtual Module* findModule( const char* type, int version, const char* name ) const = 0; -virtual void foreachModule( const char* type, int version, const Visitor& visitor ) = 0; + virtual void registerModule( const char* type, int version, const char* name, Module& module ) = 0; + virtual Module* findModule( const char* type, int version, const char* name ) const = 0; + virtual void foreachModule( const char* type, int version, const Visitor& visitor ) = 0; }; class ModuleServerHolder { -ModuleServer* m_server; + ModuleServer* m_server; public: -ModuleServerHolder() - : m_server( 0 ){ -} -void set( ModuleServer& server ){ - m_server = &server; -} -ModuleServer& get(){ - return *m_server; -} + ModuleServerHolder() + : m_server( 0 ){ + } + void set( ModuleServer& server ){ + m_server = &server; + } + ModuleServer& get(){ + return *m_server; + } }; typedef Static GlobalModuleServer; @@ -112,104 +112,104 @@ template class Modules { public: -class Visitor -{ -public: -virtual void visit( const char* name, const Type& table ) const = 0; -}; + class Visitor + { + public: + virtual void visit( const char* name, const Type& table ) const = 0; + }; -virtual Type* findModule( const char* name ) = 0; -virtual void foreachModule( const Visitor& visitor ) = 0; + virtual Type* findModule( const char* name ) = 0; + virtual void foreachModule( const Visitor& visitor ) = 0; }; template class ModuleRef { -Module* m_module; -Type* m_table; + Module* m_module; + Type* m_table; public: -ModuleRef( const char* name ) : m_table( 0 ){ - if ( !globalModuleServer().getError() ) { - m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); - if ( m_module == 0 ) { - globalModuleServer().setError( true ); - globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; - } - else - { - m_module->capture(); - if ( !globalModuleServer().getError() ) { - m_table = static_cast( m_module->getTable() ); + ModuleRef( const char* name ) : m_table( 0 ){ + if ( !globalModuleServer().getError() ) { + m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( m_module == 0 ) { + globalModuleServer().setError( true ); + globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + } + else + { + m_module->capture(); + if ( !globalModuleServer().getError() ) { + m_table = static_cast( m_module->getTable() ); + } } } } -} -~ModuleRef(){ - if ( m_module != 0 ) { - m_module->release(); + ~ModuleRef(){ + if ( m_module != 0 ) { + m_module->release(); + } } -} -Type* getTable(){ + Type* getTable(){ #if defined( _DEBUG ) - ASSERT_MESSAGE( m_table != 0, "ModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); + ASSERT_MESSAGE( m_table != 0, "ModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); #endif - return m_table; -} + return m_table; + } }; template class SingletonModuleRef { -Module* m_module; -Type* m_table; + Module* m_module; + Type* m_table; public: -SingletonModuleRef() - : m_module( 0 ), m_table( 0 ){ -} - -bool initialised() const { - return m_module != 0; -} - -void initialise( const char* name ){ - m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); - if ( m_module == 0 ) { - globalModuleServer().setError( true ); - globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + SingletonModuleRef() + : m_module( 0 ), m_table( 0 ){ } -} -Type* getTable(){ + bool initialised() const { + return m_module != 0; + } + + void initialise( const char* name ){ + m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( m_module == 0 ) { + globalModuleServer().setError( true ); + globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + } + } + + Type* getTable(){ #if defined( _DEBUG ) - ASSERT_MESSAGE( m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); + ASSERT_MESSAGE( m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); #endif - return m_table; -} -void capture(){ - if ( initialised() ) { - m_module->capture(); - m_table = static_cast( m_module->getTable() ); + return m_table; } -} -void release(){ - if ( initialised() ) { - m_module->release(); + void capture(){ + if ( initialised() ) { + m_module->capture(); + m_table = static_cast( m_module->getTable() ); + } + } + void release(){ + if ( initialised() ) { + m_module->release(); + } } -} }; template class GlobalModule { -static SingletonModuleRef m_instance; + static SingletonModuleRef m_instance; public: -static SingletonModuleRef& instance(){ - return m_instance; -} -static Type& getTable(){ - return *m_instance.getTable(); -} + static SingletonModuleRef& instance(){ + return m_instance; + } + static Type& getTable(){ + return *m_instance.getTable(); + } }; template @@ -220,18 +220,18 @@ template class GlobalModuleRef { public: -GlobalModuleRef( const char* name = "*" ){ - if ( !globalModuleServer().getError() ) { - GlobalModule::instance().initialise( name ); + GlobalModuleRef( const char* name = "*" ){ + if ( !globalModuleServer().getError() ) { + GlobalModule::instance().initialise( name ); + } + GlobalModule::instance().capture(); + } + ~GlobalModuleRef(){ + GlobalModule::instance().release(); + } + Type& getTable(){ + return GlobalModule::getTable(); } - GlobalModule::instance().capture(); -} -~GlobalModuleRef(){ - GlobalModule::instance().release(); -} -Type& getTable(){ - return GlobalModule::getTable(); -} }; #endif diff --git a/include/nameable.h b/include/nameable.h index bbc6f899..04145d79 100644 --- a/include/nameable.h +++ b/include/nameable.h @@ -30,11 +30,11 @@ typedef Callback1 NameCallback; class Nameable { public: -STRING_CONSTANT( Name, "Nameable" ); + STRING_CONSTANT( Name, "Nameable" ); -virtual const char* name() const = 0; -virtual void attach( const NameCallback& callback ) = 0; -virtual void detach( const NameCallback& callback ) = 0; + virtual const char* name() const = 0; + virtual void attach( const NameCallback& callback ) = 0; + virtual void detach( const NameCallback& callback ) = 0; }; diff --git a/include/namespace.h b/include/namespace.h index 9a00793c..bcb76e14 100644 --- a/include/namespace.h +++ b/include/namespace.h @@ -31,19 +31,19 @@ typedef Callback1 NameCallbackCallback; class Namespace { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "namespace" ); -virtual void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ) = 0; -virtual void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ) = 0; -virtual void makeUnique( const char* name, const NameCallback& setName ) const = 0; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "namespace" ); + virtual void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ) = 0; + virtual void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ) = 0; + virtual void makeUnique( const char* name, const NameCallback& setName ) const = 0; }; class Namespaced { public: -STRING_CONSTANT( Name, "Namespaced" ); + STRING_CONSTANT( Name, "Namespaced" ); -virtual void setNamespace( Namespace& space ) = 0; + virtual void setNamespace( Namespace& space ) = 0; }; #include "modulesystem.h" diff --git a/include/preferencesystem.cpp b/include/preferencesystem.cpp index 6152cb14..a45f9c32 100644 --- a/include/preferencesystem.cpp +++ b/include/preferencesystem.cpp @@ -58,28 +58,28 @@ void SavePrefs( PreferenceDictionary& preferences, const char* filename ){ class StringPreference { public: -class Observer -{ -public: -virtual void onChanged() = 0; -}; + class Observer + { + public: + virtual void onChanged() = 0; + }; private: -CopiedString m_string; -Observer& m_observer; + CopiedString m_string; + Observer& m_observer; public: -StringPreference( Observer& observer ) - : m_observer( observer ){ -} -void importString( const char* value ){ - m_string = value; - m_observer.onChanged(); -} -typedef MemberCaller1 ImportStringCaller; -void exportString( StringImportCallback& importer ){ - importer( m_string.c_str() ); -} -typedef MemberCaller1 ExportStringCaller; + StringPreference( Observer& observer ) + : m_observer( observer ){ + } + void importString( const char* value ){ + m_string = value; + m_observer.onChanged(); + } + typedef MemberCaller1 ImportStringCaller; + void exportString( StringImportCallback& importer ){ + importer( m_string.c_str() ); + } + typedef MemberCaller1 ExportStringCaller; }; inline void int_export( int i, StringImportCallback& importer ){ @@ -95,79 +95,79 @@ inline int int_import( const char* value ){ class IntPreference { public: -class Observer -{ -public: -virtual void onChanged() = 0; -}; + class Observer + { + public: + virtual void onChanged() = 0; + }; private: -int m_int; -Observer& m_observer; + int m_int; + Observer& m_observer; public: -IntPreference( Observer& observer ) - : m_observer( observer ){ -} -void importString( const char* value ){ - m_int = int_import( value ); - m_observer.onChanged(); -} -typedef MemberCaller1 ImportStringCaller; -void exportString( StringImportCallback& importer ){ - int_export( m_int, importer ); -} -typedef MemberCaller1 ExportStringCaller; + IntPreference( Observer& observer ) + : m_observer( observer ){ + } + void importString( const char* value ){ + m_int = int_import( value ); + m_observer.onChanged(); + } + typedef MemberCaller1 ImportStringCaller; + void exportString( StringImportCallback& importer ){ + int_export( m_int, importer ); + } + typedef MemberCaller1 ExportStringCaller; }; class IntPreferenceImporter { -int& m_i; + int& m_i; public: -IntPreferenceImporter( int& i ) - : m_i( i ){ -} -void importString( const char* value ){ - m_i = int_import( value ); -} + IntPreferenceImporter( int& i ) + : m_i( i ){ + } + void importString( const char* value ){ + m_i = int_import( value ); + } }; class TestPrefs { public: -TestPrefs(){ - PreferenceDictionary preferences; + TestPrefs(){ + PreferenceDictionary preferences; + + class StringObserver : public StringPreference::Observer + { + public: + void onChanged(){ + int bleh = 0; + } + } string_observer; + StringPreference string1( string_observer ); + string1.importString( "twenty-three" ); + + class IntObserver : public IntPreference::Observer + { + public: + void onChanged(){ + int bleh = 0; + } + + } int_observer; + IntPreference int1( int_observer ); + int1.importString( "23" ); + + preferences.registerPreference( "string1", StringPreference::ImportStringCaller( string1 ), StringPreference::ExportStringCaller( string1 ) ); + preferences.registerPreference( "int1", IntPreference::ImportStringCaller( int1 ), IntPreference::ExportStringCaller( int1 ) ); + + LoadPrefs( preferences, "test.pref" ); + SavePrefs( preferences, "test.pref" ); - class StringObserver : public StringPreference::Observer - { -public: - void onChanged(){ - int bleh = 0; } - } string_observer; - StringPreference string1( string_observer ); - string1.importString( "twenty-three" ); - - class IntObserver : public IntPreference::Observer - { -public: - void onChanged(){ - int bleh = 0; - } - - } int_observer; - IntPreference int1( int_observer ); - int1.importString( "23" ); - - preferences.registerPreference( "string1", StringPreference::ImportStringCaller( string1 ), StringPreference::ExportStringCaller( string1 ) ); - preferences.registerPreference( "int1", IntPreference::ImportStringCaller( int1 ), IntPreference::ExportStringCaller( int1 ) ); - - LoadPrefs( preferences, "test.pref" ); - SavePrefs( preferences, "test.pref" ); - -} }; #if 0 diff --git a/include/preferencesystem.h b/include/preferencesystem.h index 45678024..ad5c6884 100644 --- a/include/preferencesystem.h +++ b/include/preferencesystem.h @@ -31,10 +31,10 @@ typedef Callback1 StringExportCallback; class PreferenceSystem { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "preferences" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "preferences" ); -virtual void registerPreference( const char* name, const StringImportCallback& importer, const StringExportCallback& exporter ) = 0; + virtual void registerPreference( const char* name, const StringImportCallback& importer, const StringExportCallback& exporter ) = 0; }; #include "modulesystem.h" diff --git a/include/qerplugin.h b/include/qerplugin.h index 4f63a35f..eb242ccc 100644 --- a/include/qerplugin.h +++ b/include/qerplugin.h @@ -81,7 +81,7 @@ typedef char* ( *PFN_QERAPP_DIRDIALOG )( GtkWidget *parent, const char* title /* template class BasicVector3; typedef BasicVector3 Vector3; typedef bool ( *PFN_QERAPP_COLORDIALOG )( GtkWidget *parent, Vector3& color, - const char* title /* = "Choose Color"*/ ); + const char* title /* = "Choose Color"*/ ); // load a .bmp file and create a GtkImage widget from it // NOTE: 'filename' is relative to /plugins/bitmaps/ diff --git a/include/renderable.h b/include/renderable.h index 0cae9b77..a0adacc8 100644 --- a/include/renderable.h +++ b/include/renderable.h @@ -32,29 +32,29 @@ class Matrix4; class Renderer { public: -enum EHighlightMode -{ - eFace = 1 << 0, - /*! Full highlighting. */ - ePrimitive = 1 << 1, - ePrimitiveWire = 1 << 2, //always draw wire for primitives - eFaceWire = 1 << 3, //wire for selected faces -}; + enum EHighlightMode + { + eFace = 1 << 0, + /*! Full highlighting. */ + ePrimitive = 1 << 1, + ePrimitiveWire = 1 << 2, //always draw wire for primitives + eFaceWire = 1 << 3, //wire for selected faces + }; -enum EStyle -{ - eWireframeOnly, - eFullMaterials, -}; + enum EStyle + { + eWireframeOnly, + eFullMaterials, + }; -virtual void PushState() = 0; -virtual void PopState() = 0; -virtual void SetState( Shader* state, EStyle mode ) = 0; -virtual EStyle getStyle() const = 0; -virtual void Highlight( EHighlightMode mode, bool bEnable = true ) = 0; -virtual void setLights( const LightList& lights ){ -} -virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ) = 0; + virtual void PushState() = 0; + virtual void PopState() = 0; + virtual void SetState( Shader* state, EStyle mode ) = 0; + virtual EStyle getStyle() const = 0; + virtual void Highlight( EHighlightMode mode, bool bEnable = true ) = 0; + virtual void setLights( const LightList& lights ){ + } + virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ) = 0; }; class VolumeTest; @@ -62,14 +62,14 @@ class VolumeTest; class Renderable { public: -STRING_CONSTANT( Name, "Renderable" ); + STRING_CONSTANT( Name, "Renderable" ); -virtual void renderSolid( Renderer& renderer, const VolumeTest& volume ) const = 0; -virtual void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const = 0; -virtual void renderComponents( Renderer&, const VolumeTest& ) const { -} -virtual void viewChanged() const { -} + virtual void renderSolid( Renderer& renderer, const VolumeTest& volume ) const = 0; + virtual void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const = 0; + virtual void renderComponents( Renderer&, const VolumeTest& ) const { + } + virtual void viewChanged() const { + } }; #endif diff --git a/include/selectable.h b/include/selectable.h index 4256897f..16716f98 100644 --- a/include/selectable.h +++ b/include/selectable.h @@ -30,65 +30,65 @@ class SelectionIntersection { -float m_depth; -float m_distance; -float m_depth2; -bool m_indirect; + float m_depth; + float m_distance; + float m_depth2; + bool m_indirect; public: -SelectionIntersection() : m_depth( 1 ), m_distance( 2 ), m_depth2( -1 ), m_indirect( true ){ -} -SelectionIntersection( float depth, float distance ) : m_depth( depth ), m_distance( distance ), m_depth2( -1 ), m_indirect( distance != 0.f ){ -} -SelectionIntersection( float depth, float distance, float depth2 ) : m_depth( depth ), m_distance( distance ), m_depth2( depth2 ), m_indirect( distance != 0.f ){ -} -bool operator<( const SelectionIntersection& other ) const { - if( m_indirect != other.m_indirect ){ - return other.m_indirect; //m_distance < other.m_distance; + SelectionIntersection() : m_depth( 1 ), m_distance( 2 ), m_depth2( -1 ), m_indirect( true ){ } - else if( m_indirect && other.m_indirect ){ - if( fabs( m_distance - other.m_distance ) > 1e-3f /*0.00002f*/ ){ - return m_distance < other.m_distance; + SelectionIntersection( float depth, float distance ) : m_depth( depth ), m_distance( distance ), m_depth2( -1 ), m_indirect( distance != 0.f ){ + } + SelectionIntersection( float depth, float distance, float depth2 ) : m_depth( depth ), m_distance( distance ), m_depth2( depth2 ), m_indirect( distance != 0.f ){ + } + bool operator<( const SelectionIntersection& other ) const { + if( m_indirect != other.m_indirect ){ + return other.m_indirect; //m_distance < other.m_distance; } - else if( fabs( m_depth - other.m_depth ) > 1e-6f ){ + else if( m_indirect && other.m_indirect ){ + if( fabs( m_distance - other.m_distance ) > 1e-3f /*0.00002f*/ ){ + return m_distance < other.m_distance; + } + else if( fabs( m_depth - other.m_depth ) > 1e-6f ){ + return m_depth < other.m_depth; + } + else{ + return m_depth2 > other.m_depth2; + } + } + else if( m_depth != other.m_depth ){ return m_depth < other.m_depth; } - else{ - return m_depth2 > other.m_depth2; - } - } - else if( m_depth != other.m_depth ){ - return m_depth < other.m_depth; - } - return false; -} -bool equalEpsilon( const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon ) const { - if( m_indirect != other.m_indirect ){ return false; } - else if( m_indirect && other.m_indirect ){ + bool equalEpsilon( const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon ) const { + if( m_indirect != other.m_indirect ){ + return false; + } + else if( m_indirect && other.m_indirect ){ #if 1 - return float_equal_epsilon( m_distance, other.m_distance, distanceEpsilon ) - && float_equal_epsilon( m_depth, other.m_depth, depthEpsilon ) - && float_equal_epsilon( m_depth2, other.m_depth2, 3e-7f ); + return float_equal_epsilon( m_distance, other.m_distance, distanceEpsilon ) + && float_equal_epsilon( m_depth, other.m_depth, depthEpsilon ) + && float_equal_epsilon( m_depth2, other.m_depth2, 3e-7f ); #else - return ( m_distance == other.m_distance ) - && ( m_depth == other.m_depth ) - && ( m_depth2 == other.m_depth2 ); + return ( m_distance == other.m_distance ) + && ( m_depth == other.m_depth ) + && ( m_depth2 == other.m_depth2 ); #endif + } + return float_equal_epsilon( m_distance, other.m_distance, distanceEpsilon ) + && float_equal_epsilon( m_depth, other.m_depth, depthEpsilon ) + && float_equal_epsilon( m_depth2, other.m_depth2, depthEpsilon ); + } + float depth() const { + return m_depth; + } + float distance() const { + return m_distance; + } + bool valid() const { + return depth() < 1; } - return float_equal_epsilon( m_distance, other.m_distance, distanceEpsilon ) - && float_equal_epsilon( m_depth, other.m_depth, depthEpsilon ) - && float_equal_epsilon( m_depth2, other.m_depth2, depthEpsilon ); -} -float depth() const { - return m_depth; -} -float distance() const { - return m_distance; -} -bool valid() const { - return depth() < 1; -} }; // returns true if self is closer than other @@ -108,119 +108,119 @@ inline void assign_if_closer( SelectionIntersection& best, const SelectionInters class VertexPointer { -typedef const unsigned char* byte_pointer; + typedef const unsigned char* byte_pointer; public: -typedef float elem_type; -typedef const elem_type* pointer; -typedef const elem_type& reference; + typedef float elem_type; + typedef const elem_type* pointer; + typedef const elem_type& reference; -class iterator -{ -public: -iterator() {} -iterator( byte_pointer vertices, std::size_t stride ) - : m_iter( vertices ), m_stride( stride ) {} + class iterator + { + public: + iterator() {} + iterator( byte_pointer vertices, std::size_t stride ) + : m_iter( vertices ), m_stride( stride ) {} -bool operator==( const iterator& other ) const { - return m_iter == other.m_iter; -} -bool operator!=( const iterator& other ) const { - return !operator==( other ); -} + bool operator==( const iterator& other ) const { + return m_iter == other.m_iter; + } + bool operator!=( const iterator& other ) const { + return !operator==( other ); + } -iterator operator+( std::size_t i ){ - return iterator( m_iter + i * m_stride, m_stride ); -} -iterator operator+=( std::size_t i ){ - m_iter += i * m_stride; - return *this; -} -iterator& operator++(){ - m_iter += m_stride; - return *this; -} -iterator operator++( int ){ - iterator tmp = *this; - m_iter += m_stride; - return tmp; -} -reference operator*() const { - return *reinterpret_cast( m_iter ); -} -private: -byte_pointer m_iter; -std::size_t m_stride; -}; + iterator operator+( std::size_t i ){ + return iterator( m_iter + i * m_stride, m_stride ); + } + iterator operator+=( std::size_t i ){ + m_iter += i * m_stride; + return *this; + } + iterator& operator++(){ + m_iter += m_stride; + return *this; + } + iterator operator++( int ){ + iterator tmp = *this; + m_iter += m_stride; + return tmp; + } + reference operator*() const { + return *reinterpret_cast( m_iter ); + } + private: + byte_pointer m_iter; + std::size_t m_stride; + }; -VertexPointer( pointer vertices, std::size_t stride ) - : m_vertices( reinterpret_cast( vertices ) ), m_stride( stride ) {} + VertexPointer( pointer vertices, std::size_t stride ) + : m_vertices( reinterpret_cast( vertices ) ), m_stride( stride ) {} -iterator begin() const { - return iterator( m_vertices, m_stride ); -} + iterator begin() const { + return iterator( m_vertices, m_stride ); + } -reference operator[]( std::size_t i ) const { - return *reinterpret_cast( m_vertices + m_stride * i ); -} + reference operator[]( std::size_t i ) const { + return *reinterpret_cast( m_vertices + m_stride * i ); + } private: -byte_pointer m_vertices; -std::size_t m_stride; + byte_pointer m_vertices; + std::size_t m_stride; }; class IndexPointer { public: -typedef unsigned int index_type; -typedef const index_type* pointer; + typedef unsigned int index_type; + typedef const index_type* pointer; -class iterator -{ -public: -iterator( pointer iter ) : m_iter( iter ) {} + class iterator + { + public: + iterator( pointer iter ) : m_iter( iter ) {} -bool operator==( const iterator& other ) const { - return m_iter == other.m_iter; -} -bool operator!=( const iterator& other ) const { - return !operator==( other ); -} + bool operator==( const iterator& other ) const { + return m_iter == other.m_iter; + } + bool operator!=( const iterator& other ) const { + return !operator==( other ); + } -iterator operator+( std::size_t i ){ - return m_iter + i; -} -iterator operator+=( std::size_t i ){ - return m_iter += i; -} -iterator operator++(){ - return ++m_iter; -} -iterator operator++( int ){ - return m_iter++; -} -const index_type& operator*() const { - return *m_iter; -} -private: -void increment(){ - ++m_iter; -} -pointer m_iter; -}; + iterator operator+( std::size_t i ){ + return m_iter + i; + } + iterator operator+=( std::size_t i ){ + return m_iter += i; + } + iterator operator++(){ + return ++m_iter; + } + iterator operator++( int ){ + return m_iter++; + } + const index_type& operator*() const { + return *m_iter; + } + private: + void increment(){ + ++m_iter; + } + pointer m_iter; + }; -IndexPointer( pointer indices, std::size_t count ) - : m_indices( indices ), m_finish( indices + count ) {} + IndexPointer( pointer indices, std::size_t count ) + : m_indices( indices ), m_finish( indices + count ) {} -iterator begin() const { - return m_indices; -} -iterator end() const { - return m_finish; -} + iterator begin() const { + return m_indices; + } + iterator end() const { + return m_finish; + } private: -pointer m_indices; -pointer m_finish; + pointer m_indices; + pointer m_finish; }; class Matrix4; @@ -229,19 +229,19 @@ class VolumeTest; class SelectionTest { public: -virtual void BeginMesh( const Matrix4& localToWorld, bool twoSided = false ) = 0; -virtual const VolumeTest& getVolume() const = 0; -//virtual const Vector3& getNear() const = 0; -//virtual const Vector3& getFar() const = 0; -virtual const Matrix4& getScreen2world() const = 0; -virtual void TestPoint( const Vector3& point, SelectionIntersection& best ) = 0; -virtual void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best, const DoubleVector3 planepoints[3] ) = 0; -virtual void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; -virtual void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; -virtual void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; -virtual void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; -virtual void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; -virtual void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; + virtual void BeginMesh( const Matrix4& localToWorld, bool twoSided = false ) = 0; + virtual const VolumeTest& getVolume() const = 0; +// virtual const Vector3& getNear() const = 0; +// virtual const Vector3& getFar() const = 0; + virtual const Matrix4& getScreen2world() const = 0; + virtual void TestPoint( const Vector3& point, SelectionIntersection& best ) = 0; + virtual void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best, const DoubleVector3 planepoints[3] ) = 0; + virtual void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; + virtual void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; + virtual void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; + virtual void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; + virtual void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; + virtual void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; }; class Selectable; @@ -249,9 +249,9 @@ class Selectable; class Selector { public: -virtual void pushSelectable( Selectable& selectable ) = 0; -virtual void popSelectable() = 0; -virtual void addIntersection( const SelectionIntersection& intersection ) = 0; + virtual void pushSelectable( Selectable& selectable ) = 0; + virtual void popSelectable() = 0; + virtual void addIntersection( const SelectionIntersection& intersection ) = 0; }; inline void Selector_add( Selector& selector, Selectable& selectable ){ @@ -271,9 +271,9 @@ class VolumeTest; class SelectionTestable { public: -STRING_CONSTANT( Name, "SelectionTestable" ); + STRING_CONSTANT( Name, "SelectionTestable" ); -virtual void testSelect( Selector& selector, SelectionTest& test ) = 0; + virtual void testSelect( Selector& selector, SelectionTest& test ) = 0; }; inline SelectionTestable* Instance_getSelectionTestable( scene::Instance& instance ){ @@ -288,22 +288,22 @@ typedef Callback1 PlaneCallback; class SelectedPlanes { public: -virtual bool contains( const Plane3& plane ) const = 0; + virtual bool contains( const Plane3& plane ) const = 0; }; /// \todo Support localToWorld. class PlaneSelectable { public: -STRING_CONSTANT( Name, "PlaneSelectable" ); + STRING_CONSTANT( Name, "PlaneSelectable" ); -virtual void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ) = 0; -virtual void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ) = 0; + virtual void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ) = 0; + virtual void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ) = 0; -virtual void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const = 0; -virtual void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const = 0; -virtual void selectByPlane( const Plane3& plane ) = 0; -virtual void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const = 0; + virtual void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const = 0; + virtual void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const = 0; + virtual void selectByPlane( const Plane3& plane ) = 0; + virtual void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const = 0; }; diff --git a/include/windowobserver.h b/include/windowobserver.h index b72d0820..19381eb4 100644 --- a/include/windowobserver.h +++ b/include/windowobserver.h @@ -79,13 +79,13 @@ typedef Vector2 WindowVector; class WindowObserver { public: -virtual void release() = 0; -virtual void onSizeChanged( int width, int height ) = 0; -virtual void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; -virtual void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; -virtual void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ) = 0; -virtual void onModifierDown( ModifierFlags modifier ) = 0; -virtual void onModifierUp( ModifierFlags modifier ) = 0; + virtual void release() = 0; + virtual void onSizeChanged( int width, int height ) = 0; + virtual void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; + virtual void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; + virtual void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ) = 0; + virtual void onModifierDown( ModifierFlags modifier ) = 0; + virtual void onModifierUp( ModifierFlags modifier ) = 0; }; #endif diff --git a/libs/archivelib.h b/libs/archivelib.h index 2f69734d..a56afa66 100644 --- a/libs/archivelib.h +++ b/libs/archivelib.h @@ -35,35 +35,35 @@ template class SingleByteInputStream { -typedef typename InputStreamType::byte_type byte_type; + typedef typename InputStreamType::byte_type byte_type; -InputStreamType& m_inputStream; -byte_type m_buffer[SIZE]; -byte_type* m_cur; -byte_type* m_end; + InputStreamType& m_inputStream; + byte_type m_buffer[SIZE]; + byte_type* m_cur; + byte_type* m_end; public: -SingleByteInputStream( InputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer + SIZE ), m_end( m_cur ){ -} -bool readByte( byte_type& b ){ - if ( m_cur == m_end ) { - if ( m_end != m_buffer + SIZE ) { - return false; - } - - m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); - m_cur = m_buffer; - - if ( m_end == m_buffer ) { - return false; - } + SingleByteInputStream( InputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer + SIZE ), m_end( m_cur ){ } + bool readByte( byte_type& b ){ + if ( m_cur == m_end ) { + if ( m_end != m_buffer + SIZE ) { + return false; + } - b = *m_cur++; + m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); + m_cur = m_buffer; - return true; -} + if ( m_end == m_buffer ) { + return false; + } + } + + b = *m_cur++; + + return true; + } }; /// \brief A binary-to-text wrapper around an InputStream. @@ -71,153 +71,153 @@ bool readByte( byte_type& b ){ template class BinaryToTextInputStream : public TextInputStream { -SingleByteInputStream m_inputStream; + SingleByteInputStream m_inputStream; public: -BinaryToTextInputStream( BinaryInputStreamType& inputStream ) : m_inputStream( inputStream ){ -} -std::size_t read( char* buffer, std::size_t length ){ - char* p = buffer; - for (;; ) - { - if ( length != 0 && m_inputStream.readByte( *reinterpret_cast( p ) ) ) { - if ( *p != '\r' ) { - ++p; - --length; + BinaryToTextInputStream( BinaryInputStreamType& inputStream ) : m_inputStream( inputStream ){ + } + std::size_t read( char* buffer, std::size_t length ){ + char* p = buffer; + for (;; ) + { + if ( length != 0 && m_inputStream.readByte( *reinterpret_cast( p ) ) ) { + if ( *p != '\r' ) { + ++p; + --length; + } + } + else + { + return p - buffer; } } - else - { - return p - buffer; - } } -} }; /// \brief An ArchiveFile which is stored uncompressed as part of a larger archive file. class StoredArchiveFile : public ArchiveFile { -CopiedString m_name; -FileInputStream m_filestream; -SubFileInputStream m_substream; -FileInputStream::size_type m_size; + CopiedString m_name; + FileInputStream m_filestream; + SubFileInputStream m_substream; + FileInputStream::size_type m_size; public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; + typedef FileInputStream::size_type size_type; + typedef FileInputStream::position_type position_type; -StoredArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) - : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_size( file_size ){ -} + StoredArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) + : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_size( file_size ){ + } -static StoredArchiveFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ){ - return New().scalar( name, archiveName, position, stream_size, file_size ); -} + static StoredArchiveFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ){ + return New().scalar( name, archiveName, position, stream_size, file_size ); + } -void release(){ - Delete().scalar( this ); -} -size_type size() const { - return m_size; -} -const char* getName() const { - return m_name.c_str(); -} -InputStream& getInputStream(){ - return m_substream; -} + void release(){ + Delete().scalar( this ); + } + size_type size() const { + return m_size; + } + const char* getName() const { + return m_name.c_str(); + } + InputStream& getInputStream(){ + return m_substream; + } }; /// \brief An ArchiveTextFile which is stored uncompressed as part of a larger archive file. class StoredArchiveTextFile : public ArchiveTextFile { -CopiedString m_name; -FileInputStream m_filestream; -SubFileInputStream m_substream; -BinaryToTextInputStream m_textStream; + CopiedString m_name; + FileInputStream m_filestream; + SubFileInputStream m_substream; + BinaryToTextInputStream m_textStream; public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; + typedef FileInputStream::size_type size_type; + typedef FileInputStream::position_type position_type; -StoredArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) - : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_textStream( m_substream ){ -} + StoredArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) + : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_textStream( m_substream ){ + } -static StoredArchiveTextFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size ){ - return New().scalar( name, archiveName, position, stream_size ); -} + static StoredArchiveTextFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size ){ + return New().scalar( name, archiveName, position, stream_size ); + } -void release(){ - Delete().scalar( this ); -} -const char* getName() const { - return m_name.c_str(); -} -TextInputStream& getInputStream(){ - return m_textStream; -} + void release(){ + Delete().scalar( this ); + } + const char* getName() const { + return m_name.c_str(); + } + TextInputStream& getInputStream(){ + return m_textStream; + } }; /// \brief An ArchiveFile which is stored as a single file on disk. class DirectoryArchiveFile final : public ArchiveFile { -CopiedString m_name; -FileInputStream m_istream; -FileInputStream::size_type m_size; + CopiedString m_name; + FileInputStream m_istream; + FileInputStream::size_type m_size; public: -typedef FileInputStream::size_type size_type; + typedef FileInputStream::size_type size_type; -DirectoryArchiveFile( const char* name, const char* filename ) - : m_name( name ), m_istream( filename ){ - if ( !failed() ) { - m_istream.seek( 0, FileInputStream::end ); - m_size = m_istream.tell(); - m_istream.seek( 0 ); + DirectoryArchiveFile( const char* name, const char* filename ) + : m_name( name ), m_istream( filename ){ + if ( !failed() ) { + m_istream.seek( 0, FileInputStream::end ); + m_size = m_istream.tell(); + m_istream.seek( 0 ); + } + else + { + m_size = 0; + } } - else - { - m_size = 0; + bool failed() const { + return m_istream.failed(); } -} -bool failed() const { - return m_istream.failed(); -} -void release(){ - delete this; -} -size_type size() const { - return m_size; -} -const char* getName() const { - return m_name.c_str(); -} -InputStream& getInputStream(){ - return m_istream; -} + void release(){ + delete this; + } + size_type size() const { + return m_size; + } + const char* getName() const { + return m_name.c_str(); + } + InputStream& getInputStream(){ + return m_istream; + } }; /// \brief An ArchiveTextFile which is stored as a single file on disk. class DirectoryArchiveTextFile final : public ArchiveTextFile { -CopiedString m_name; -TextFileInputStream m_inputStream; + CopiedString m_name; + TextFileInputStream m_inputStream; public: -DirectoryArchiveTextFile( const char* name, const char* filename ) - : m_name( name ), m_inputStream( filename ){ -} -bool failed() const { - return m_inputStream.failed(); -} + DirectoryArchiveTextFile( const char* name, const char* filename ) + : m_name( name ), m_inputStream( filename ){ + } + bool failed() const { + return m_inputStream.failed(); + } -void release(){ - delete this; -} -const char* getName() const { - return m_name.c_str(); -} -TextInputStream& getInputStream(){ - return m_inputStream; -} + void release(){ + delete this; + } + const char* getName() const { + return m_name.c_str(); + } + TextInputStream& getInputStream(){ + return m_inputStream; + } }; diff --git a/libs/cmdlib/cmdlib.cpp b/libs/cmdlib/cmdlib.cpp index 8aeba8f4..44cda8cd 100644 --- a/libs/cmdlib/cmdlib.cpp +++ b/libs/cmdlib/cmdlib.cpp @@ -115,17 +115,17 @@ bool Q_Exec( const char *cmd, char *cmdline, const char *execdir, bool bCreateCo } if ( CreateProcess( - pCmd, - pCmdline, - NULL, - NULL, - FALSE, - dwCreationFlags, - NULL, - execdir, - &startupinfo, - &ProcessInformation - ) ) { + pCmd, + pCmdline, + NULL, + NULL, + FALSE, + dwCreationFlags, + NULL, + execdir, + &startupinfo, + &ProcessInformation + ) ) { if ( waitfor ) { WaitForSingleObject( ProcessInformation.hProcess, INFINITE ); } diff --git a/libs/container/array.cpp b/libs/container/array.cpp index 8ce77f50..93aebcf7 100644 --- a/libs/container/array.cpp +++ b/libs/container/array.cpp @@ -25,10 +25,10 @@ namespace { class Bleh { -Array m_array; + Array m_array; public: -Bleh() : m_array( 16 ){ -} + Bleh() : m_array( 16 ){ + } }; void testAutoArray(){ diff --git a/libs/container/array.h b/libs/container/array.h index c359df15..71ae6d02 100644 --- a/libs/container/array.h +++ b/libs/container/array.h @@ -38,123 +38,123 @@ template > class Array : public Allocator { -std::size_t m_size; -Element* m_data; + std::size_t m_size; + Element* m_data; -Element* construct( std::size_t size ){ + Element* construct( std::size_t size ){ #if 1 - return New( *this ).vector( size ); + return New( *this ).vector( size ); #else - return new Element[size]; + return new Element[size]; #endif -} -template -Element* construct( std::size_t size, const T1& value ){ - return New( *this ).vector( size, value ); -} -void destroy( Element* data, std::size_t size ){ + } + template + Element* construct( std::size_t size, const T1& value ){ + return New( *this ).vector( size, value ); + } + void destroy( Element* data, std::size_t size ){ #if 1 - Delete( *this ).vector( data, size ); + Delete( *this ).vector( data, size ); #else - delete[] data; + delete[] data; #endif -} + } public: -typedef Element value_type; -typedef value_type* iterator; -typedef const value_type* const_iterator; + typedef Element value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; -Array() - : m_size( 0 ), m_data( 0 ){ -} -Array( std::size_t size ) - : m_size( size ), m_data( construct( size ) ){ -} -template -Array( std::size_t size, const T1& value ) - : m_size( size ), m_data( construct( size, value ) ){ -} -Array( const Array& other ) - : Allocator( other ), m_size( other.size() ), m_data( construct( m_size ) ){ - std::copy( other.begin(), other.end(), begin() ); -} -template -Array( Iterator start, Iterator finish ) - : m_size( std::distance( start, finish ) ), m_data( construct( m_size ) ){ - std::copy( start, finish, begin() ); -} -~Array(){ - destroy( m_data, m_size ); -} - -Array& operator=( const Array& other ){ - if ( other.size() == size() ) { + Array() + : m_size( 0 ), m_data( 0 ){ + } + Array( std::size_t size ) + : m_size( size ), m_data( construct( size ) ){ + } + template + Array( std::size_t size, const T1& value ) + : m_size( size ), m_data( construct( size, value ) ){ + } + Array( const Array& other ) + : Allocator( other ), m_size( other.size() ), m_data( construct( m_size ) ){ std::copy( other.begin(), other.end(), begin() ); } - else - { - Array temp( other ); - temp.swap( *this ); + template + Array( Iterator start, Iterator finish ) + : m_size( std::distance( start, finish ) ), m_data( construct( m_size ) ){ + std::copy( start, finish, begin() ); + } + ~Array(){ + destroy( m_data, m_size ); } - return *this; -} -void swap( Array& other ){ - std::swap( m_size, other.m_size ); - std::swap( m_data, other.m_data ); -} + Array& operator=( const Array& other ){ + if ( other.size() == size() ) { + std::copy( other.begin(), other.end(), begin() ); + } + else + { + Array temp( other ); + temp.swap( *this ); + } + return *this; + } -iterator begin(){ - return m_data; -} -const_iterator begin() const { - return m_data; -} -iterator end(){ - return m_data + m_size; -} -const_iterator end() const { - return m_data + m_size; -} + void swap( Array& other ){ + std::swap( m_size, other.m_size ); + std::swap( m_data, other.m_data ); + } -value_type& operator[]( std::size_t index ){ + iterator begin(){ + return m_data; + } + const_iterator begin() const { + return m_data; + } + iterator end(){ + return m_data + m_size; + } + const_iterator end() const { + return m_data + m_size; + } + + value_type& operator[]( std::size_t index ){ #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -const value_type& operator[]( std::size_t index ) const { + return m_data[index]; + } + const value_type& operator[]( std::size_t index ) const { #if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; -} -value_type* data(){ - return m_data; -} -const value_type* data() const { - return m_data; -} -std::size_t size() const { - return m_size; -} -bool empty() const { - return m_size == 0; -} + return m_data[index]; + } + value_type* data(){ + return m_data; + } + const value_type* data() const { + return m_data; + } + std::size_t size() const { + return m_size; + } + bool empty() const { + return m_size == 0; + } -void resize( std::size_t count ){ - if ( count != size() ) { - Array temp( count ); - temp.swap( *this ); + void resize( std::size_t count ){ + if ( count != size() ) { + Array temp( count ); + temp.swap( *this ); + } } -} -void resize( std::size_t count, const value_type& value ){ - if ( count != size() ) { - Array temp( count, value ); - temp.swap( *this ); + void resize( std::size_t count, const value_type& value ){ + if ( count != size() ) { + Array temp( count, value ); + temp.swap( *this ); + } } -} }; namespace std diff --git a/libs/container/cache.h b/libs/container/cache.h index 880a7a7a..ddf99622 100644 --- a/libs/container/cache.h +++ b/libs/container/cache.h @@ -30,57 +30,57 @@ template class DefaultCreationPolicy { public: -Type* construct( const Parameter& parameter ){ - return New().scalar( parameter ); -} -void destroy( Type* p ){ - Delete().scalar( p ); -} + Type* construct( const Parameter& parameter ){ + return New().scalar( parameter ); + } + void destroy( Type* p ){ + Delete().scalar( p ); + } }; template class SharedValue { -typedef Type value_type; -typedef value_type* pointer; -typedef value_type& reference; + typedef Type value_type; + typedef value_type* pointer; + typedef value_type& reference; -std::size_t m_count; -pointer m_value; + std::size_t m_count; + pointer m_value; public: -SharedValue() - : m_count( 0 ), m_value( 0 ){ -} -~SharedValue(){ - ASSERT_MESSAGE( m_count == 0, "destroying a referenced object\n" ); -} -void set( pointer value ){ - m_value = value; -} -pointer get(){ - return m_value; -} -std::size_t increment(){ - return ++m_count; -} -std::size_t decrement(){ - ASSERT_MESSAGE( !empty(), "destroying a non-existent object\n" ); - return --m_count; -} -std::size_t count(){ - return m_count; -} -bool empty(){ - return m_count == 0; -} -reference operator*() const { - ASSERT_NOTNULL( m_value ); - return *m_value; -} -pointer operator->() const { - return &( operator*() ); -} + SharedValue() + : m_count( 0 ), m_value( 0 ){ + } + ~SharedValue(){ + ASSERT_MESSAGE( m_count == 0, "destroying a referenced object\n" ); + } + void set( pointer value ){ + m_value = value; + } + pointer get(){ + return m_value; + } + std::size_t increment(){ + return ++m_count; + } + std::size_t decrement(){ + ASSERT_MESSAGE( !empty(), "destroying a non-existent object\n" ); + return --m_count; + } + std::size_t count(){ + return m_count; + } + bool empty(){ + return m_count == 0; + } + reference operator*() const { + ASSERT_NOTNULL( m_value ); + return *m_value; + } + pointer operator->() const { + return &( operator*() ); + } }; @@ -95,83 +95,83 @@ pointer operator->() const { template, typename CreationPolicy = DefaultCreationPolicy > class HashedCache : public CreationPolicy { -typedef SharedValue Element; -typedef HashTable map_type; + typedef SharedValue Element; + typedef HashTable map_type; -map_type m_map; + map_type m_map; public: -explicit HashedCache( const CreationPolicy& creation = CreationPolicy() ) - : CreationPolicy( creation ), m_map( 256 ){ -} -~HashedCache(){ - ASSERT_MESSAGE( empty(), "HashedCache::~HashedCache: not empty" ); -} - -typedef typename map_type::iterator iterator; -typedef typename map_type::value_type value_type; - -iterator begin(){ - return m_map.begin(); -} -iterator end(){ - return m_map.end(); -} - -bool empty() const { - return m_map.empty(); -} - -iterator find( const Key& key ){ - return m_map.find( key ); -} - -void capture( iterator i ){ - ( *i ).value.increment(); -} -void release( iterator i ){ - if ( ( *i ).value.decrement() == 0 ) { - CreationPolicy::destroy( ( *i ).value.get() ); - m_map.erase( i ); + explicit HashedCache( const CreationPolicy& creation = CreationPolicy() ) + : CreationPolicy( creation ), m_map( 256 ){ + } + ~HashedCache(){ + ASSERT_MESSAGE( empty(), "HashedCache::~HashedCache: not empty" ); + } + + typedef typename map_type::iterator iterator; + typedef typename map_type::value_type value_type; + + iterator begin(){ + return m_map.begin(); + } + iterator end(){ + return m_map.end(); + } + + bool empty() const { + return m_map.empty(); + } + + iterator find( const Key& key ){ + return m_map.find( key ); + } + + void capture( iterator i ){ + ( *i ).value.increment(); + } + void release( iterator i ){ + if ( ( *i ).value.decrement() == 0 ) { + CreationPolicy::destroy( ( *i ).value.get() ); + m_map.erase( i ); + } } -} #if 1 -Element& capture( const Key& key ){ + Element& capture( const Key& key ){ #if 0 - Element& elem = m_map[key]; - if ( elem.increment() == 1 ) { - elem.set( CreationPolicy::construct( key ) ); - } - return elem; + Element& elem = m_map[key]; + if ( elem.increment() == 1 ) { + elem.set( CreationPolicy::construct( key ) ); + } + return elem; #else - iterator i = m_map.insert( key, Element() ); - if ( ( *i ).value.increment() == 1 ) { - ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); - } - return ( *i ).value; + iterator i = m_map.insert( key, Element() ); + if ( ( *i ).value.increment() == 1 ) { + ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); + } + return ( *i ).value; #endif -} + } #else -value_type& capture( const Key& key ){ - iterator i = m_map.find( key ); - if ( i == m_map.end() ) { - i = m_map.insert( key, Element() ); - ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); + value_type& capture( const Key& key ){ + iterator i = m_map.find( key ); + if ( i == m_map.end() ) { + i = m_map.insert( key, Element() ); + ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); + } + ( *i ).value.increment(); + return ( *i ); } - ( *i ).value.increment(); - return ( *i ); -} #endif -void release( const Key& key ){ - iterator i = m_map.find( key ); - ASSERT_MESSAGE( i != m_map.end(), "releasing a non-existent object\n" ); - release( i ); -} + void release( const Key& key ){ + iterator i = m_map.find( key ); + ASSERT_MESSAGE( i != m_map.end(), "releasing a non-existent object\n" ); + release( i ); + } -void clear(){ - m_map.clear(); -} + void clear(){ + m_map.clear(); + } }; diff --git a/libs/container/container.h b/libs/container/container.h index ab04b609..b7a2ea39 100644 --- a/libs/container/container.h +++ b/libs/container/container.h @@ -31,29 +31,29 @@ template class Single { -Type* m_value; + Type* m_value; public: -Single() : m_value( 0 ){ -} -bool empty(){ - return m_value == 0; -} -Type* insert( const Type& other ){ - m_value = new Type( other ); - return m_value; -} -void clear(){ - delete m_value; - m_value = 0; -} -Type& get(){ - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; -} -const Type& get() const { - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; -} + Single() : m_value( 0 ){ + } + bool empty(){ + return m_value == 0; + } + Type* insert( const Type& other ){ + m_value = new Type( other ); + return m_value; + } + void clear(){ + delete m_value; + m_value = 0; + } + Type& get(){ + //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); + return *m_value; + } + const Type& get() const { + //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); + return *m_value; + } }; @@ -63,106 +63,106 @@ const Type& get() const { template class UnsortedSet { -typedef typename std::list Values; -Values m_values; + typedef typename std::list Values; + Values m_values; public: -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; -typedef typename Values::reverse_iterator reverse_iterator; -typedef typename Values::const_reverse_iterator const_reverse_iterator; + typedef typename Values::iterator iterator; + typedef typename Values::const_iterator const_iterator; + typedef typename Values::reverse_iterator reverse_iterator; + typedef typename Values::const_reverse_iterator const_reverse_iterator; private: -struct Compare{ - using is_transparent = void; + struct Compare{ + using is_transparent = void; - bool operator()( const const_iterator& one, const const_iterator& other ) const { - return *one < *other; + bool operator()( const const_iterator& one, const const_iterator& other ) const { + return *one < *other; + } + bool operator()( const Value& va, const const_iterator& it ) const { + return va < *it; + } + bool operator()( const const_iterator& it, const Value& va ) const { + return *it < va; + } + }; + std::set m_set; // store sorted iterators for fast lookup + void init_set(){ // only load set, when lookup is needed + if( m_set.empty() ) + for( const_iterator it = begin(); it != end(); ++it ) + m_set.emplace( it ); } - bool operator()( const Value& va, const const_iterator& it ) const { - return va < *it; - } - bool operator()( const const_iterator& it, const Value& va ) const { - return *it < va; - } -}; -std::set m_set; // store sorted iterators for fast lookup -void init_set(){ // only load set, when lookup is needed - if( m_set.empty() ) - for( const_iterator it = begin(); it != end(); ++it ) - m_set.emplace( it ); -} public: -UnsortedSet() = default; -UnsortedSet( const UnsortedSet& other ) : m_values( other.m_values ), m_set(){ -} -UnsortedSet( UnsortedSet&& ) noexcept = default; -UnsortedSet& operator=( const UnsortedSet& other ){ - m_values = other.m_values; - m_set.clear(); - return *this; -} -UnsortedSet& operator=( UnsortedSet&& ) noexcept = default; + UnsortedSet() = default; + UnsortedSet( const UnsortedSet& other ) : m_values( other.m_values ), m_set(){ + } + UnsortedSet( UnsortedSet&& ) noexcept = default; + UnsortedSet& operator=( const UnsortedSet& other ){ + m_values = other.m_values; + m_set.clear(); + return *this; + } + UnsortedSet& operator=( UnsortedSet&& ) noexcept = default; -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} -reverse_iterator rbegin(){ - return m_values.rbegin(); -} -const_reverse_iterator rbegin() const { - return m_values.rbegin(); -} -reverse_iterator rend(){ - return m_values.rend(); -} -const_reverse_iterator rend() const { - return m_values.rend(); -} + iterator begin(){ + return m_values.begin(); + } + const_iterator begin() const { + return m_values.begin(); + } + iterator end(){ + return m_values.end(); + } + const_iterator end() const { + return m_values.end(); + } + reverse_iterator rbegin(){ + return m_values.rbegin(); + } + const_reverse_iterator rbegin() const { + return m_values.rbegin(); + } + reverse_iterator rend(){ + return m_values.rend(); + } + const_reverse_iterator rend() const { + return m_values.rend(); + } -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); - m_set.clear(); -} + bool empty() const { + return m_values.empty(); + } + std::size_t size() const { + return m_values.size(); + } + void clear(){ + m_values.clear(); + m_set.clear(); + } -void swap( UnsortedSet& other ){ - std::swap( m_values, other.m_values ); - std::swap( m_set, other.m_set ); -} + void swap( UnsortedSet& other ){ + std::swap( m_values, other.m_values ); + std::swap( m_set, other.m_set ); + } -iterator insert( const Value& value ){ - init_set(); - m_values.push_back( value ); - const bool inserted = m_set.emplace( --end() ).second; - ASSERT_MESSAGE( inserted, "UnsortedSet::insert: already added" ); - return --end(); -} -void erase( const Value& value ){ - init_set(); - const auto it = m_set.find( value ); - ASSERT_MESSAGE( it != m_set.cend(), "UnsortedSet::erase: not found" ); - m_values.erase( *it ); - m_set.erase( it ); -} -const_iterator find( const Value& value ){ - init_set(); - const auto it = m_set.find( value ); - return it == m_set.cend()? end() : *it; -} + iterator insert( const Value& value ){ + init_set(); + m_values.push_back( value ); + const bool inserted = m_set.emplace( --end() ).second; + ASSERT_MESSAGE( inserted, "UnsortedSet::insert: already added" ); + return --end(); + } + void erase( const Value& value ){ + init_set(); + const auto it = m_set.find( value ); + ASSERT_MESSAGE( it != m_set.cend(), "UnsortedSet::erase: not found" ); + m_values.erase( *it ); + m_set.erase( it ); + } + const_iterator find( const Value& value ){ + init_set(); + const auto it = m_set.find( value ); + return it == m_set.cend()? end() : *it; + } }; namespace std @@ -181,143 +181,143 @@ inline void swap( UnsortedSet& self, UnsortedSet& other ){ template class UnsortedMap { -typedef typename std::list< std::pair > Values; -Values m_values; + typedef typename std::list< std::pair > Values; + Values m_values; public: -typedef typename Values::value_type value_type; -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; + typedef typename Values::value_type value_type; + typedef typename Values::iterator iterator; + typedef typename Values::const_iterator const_iterator; -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} + iterator begin(){ + return m_values.begin(); + } + const_iterator begin() const { + return m_values.begin(); + } + iterator end(){ + return m_values.end(); + } + const_iterator end() const { + return m_values.end(); + } -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); -} + bool empty() const { + return m_values.empty(); + } + std::size_t size() const { + return m_values.size(); + } + void clear(){ + m_values.clear(); + } -iterator insert( const value_type& value ){ - ASSERT_MESSAGE( find( value.first ) == end(), "UnsortedMap::insert: already added" ); - m_values.push_back( value ); - return --m_values.end(); -} -void erase( const Key& key ){ - iterator i = find( key ); - ASSERT_MESSAGE( i != end(), "UnsortedMap::erase: not found" ); - erase( i ); -} -void erase( iterator i ){ - m_values.erase( i ); -} -iterator find( const Key& key ){ - for ( iterator i = m_values.begin(); i != m_values.end(); ++i ) - { - if ( ( *i ).first == key ) { - return i; + iterator insert( const value_type& value ){ + ASSERT_MESSAGE( find( value.first ) == end(), "UnsortedMap::insert: already added" ); + m_values.push_back( value ); + return --m_values.end(); + } + void erase( const Key& key ){ + iterator i = find( key ); + ASSERT_MESSAGE( i != end(), "UnsortedMap::erase: not found" ); + erase( i ); + } + void erase( iterator i ){ + m_values.erase( i ); + } + iterator find( const Key& key ){ + for ( iterator i = m_values.begin(); i != m_values.end(); ++i ) + { + if ( ( *i ).first == key ) { + return i; + } } + return m_values.end(); } - return m_values.end(); -} -const_iterator find( const Key& key ) const { - for ( const_iterator i = m_values.begin(); i != m_values.end(); ++i ) - { - if ( ( *i ).first == key ) { - return i; + const_iterator find( const Key& key ) const { + for ( const_iterator i = m_values.begin(); i != m_values.end(); ++i ) + { + if ( ( *i ).first == key ) { + return i; + } } - } - return m_values.end(); -} - -Value& operator[]( const Key& key ){ - iterator i = find( key ); - if ( i != end() ) { - return ( *i ).second; + return m_values.end(); } - m_values.push_back( Values::value_type( key, Value() ) ); - return m_values.back().second; -} + Value& operator[]( const Key& key ){ + iterator i = find( key ); + if ( i != end() ) { + return ( *i ).second; + } + + m_values.push_back( Values::value_type( key, Value() ) ); + return m_values.back().second; + } }; /// An adaptor to assert when duplicate values are added, or non-existent values removed from a std::set. template class UniqueSet { -typedef std::set Values; -Values m_values; + typedef std::set Values; + Values m_values; public: -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; -typedef typename Values::reverse_iterator reverse_iterator; -typedef typename Values::const_reverse_iterator const_reverse_iterator; + typedef typename Values::iterator iterator; + typedef typename Values::const_iterator const_iterator; + typedef typename Values::reverse_iterator reverse_iterator; + typedef typename Values::const_reverse_iterator const_reverse_iterator; -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} -reverse_iterator rbegin(){ - return m_values.rbegin(); -} -const_reverse_iterator rbegin() const { - return m_values.rbegin(); -} -reverse_iterator rend(){ - return m_values.rend(); -} -const_reverse_iterator rend() const { - return m_values.rend(); -} + iterator begin(){ + return m_values.begin(); + } + const_iterator begin() const { + return m_values.begin(); + } + iterator end(){ + return m_values.end(); + } + const_iterator end() const { + return m_values.end(); + } + reverse_iterator rbegin(){ + return m_values.rbegin(); + } + const_reverse_iterator rbegin() const { + return m_values.rbegin(); + } + reverse_iterator rend(){ + return m_values.rend(); + } + const_reverse_iterator rend() const { + return m_values.rend(); + } -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); -} + bool empty() const { + return m_values.empty(); + } + std::size_t size() const { + return m_values.size(); + } + void clear(){ + m_values.clear(); + } -void swap( UniqueSet& other ){ - std::swap( m_values, other.m_values ); -} -iterator insert( const Value& value ){ - std::pair result = m_values.insert( value ); - ASSERT_MESSAGE( result.second, "UniqueSet::insert: already added" ); - return result.first; -} -void erase( const Value& value ){ - iterator i = find( value ); - ASSERT_MESSAGE( i != end(), "UniqueSet::erase: not found" ); - m_values.erase( i ); -} -iterator find( const Value& value ){ - return m_values.find( value ); -} + void swap( UniqueSet& other ){ + std::swap( m_values, other.m_values ); + } + iterator insert( const Value& value ){ + std::pair result = m_values.insert( value ); + ASSERT_MESSAGE( result.second, "UniqueSet::insert: already added" ); + return result.first; + } + void erase( const Value& value ){ + iterator i = find( value ); + ASSERT_MESSAGE( i != end(), "UniqueSet::erase: not found" ); + m_values.erase( i ); + } + iterator find( const Value& value ){ + return m_values.find( value ); + } }; namespace std @@ -333,38 +333,38 @@ inline void swap( UniqueSet& self, UniqueSet& other ){ template class ReferencePair { -Type* m_first; -Type* m_second; + Type* m_first; + Type* m_second; public: -ReferencePair() : m_first( 0 ), m_second( 0 ){ -} -void attach( Type& t ){ - ASSERT_MESSAGE( m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists" ); - if ( m_first == 0 ) { - m_first = &t; + ReferencePair() : m_first( 0 ), m_second( 0 ){ } - else if ( m_second == 0 ) { - m_second = &t; + void attach( Type& t ){ + ASSERT_MESSAGE( m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists" ); + if ( m_first == 0 ) { + m_first = &t; + } + else if ( m_second == 0 ) { + m_second = &t; + } } -} -void detach( Type& t ){ - ASSERT_MESSAGE( m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found" ); - if ( m_first == &t ) { - m_first = 0; + void detach( Type& t ){ + ASSERT_MESSAGE( m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found" ); + if ( m_first == &t ) { + m_first = 0; + } + else if ( m_second == &t ) { + m_second = 0; + } } - else if ( m_second == &t ) { - m_second = 0; + template + void forEach( const Functor& functor ){ + if ( m_second != 0 ) { + functor( *m_second ); + } + if ( m_first != 0 ) { + functor( *m_first ); + } } -} -template -void forEach( const Functor& functor ){ - if ( m_second != 0 ) { - functor( *m_second ); - } - if ( m_first != 0 ) { - functor( *m_first ); - } -} }; diff --git a/libs/container/hashfunc.h b/libs/container/hashfunc.h index 1362e5ac..c717623f 100644 --- a/libs/container/hashfunc.h +++ b/libs/container/hashfunc.h @@ -44,49 +44,49 @@ inline ub4 ub1x4_as_ub4_nocase( const ub1 bytes[4] ){ class ub1_default_traits { public: -static ub1 as_ub1( ub1 byte ){ - return byte; -} + static ub1 as_ub1( ub1 byte ){ + return byte; + } }; class ub1_nocase_traits { public: -static ub1 as_ub1( ub1 byte ){ - return ub1_as_ub1_nocase( byte ); -} + static ub1 as_ub1( ub1 byte ){ + return ub1_as_ub1_nocase( byte ); + } }; class ub1x4_default_traits { public: -static ub4 as_ub4( const ub1 bytes[4] ){ - return *reinterpret_cast( bytes ); -} + static ub4 as_ub4( const ub1 bytes[4] ){ + return *reinterpret_cast( bytes ); + } }; class ub1x4_nocase_traits { public: -static ub4 as_ub4( const ub1 bytes[4] ){ - return ub1x4_as_ub4_nocase( bytes ); -} + static ub4 as_ub4( const ub1 bytes[4] ){ + return ub1x4_as_ub4_nocase( bytes ); + } }; class ub4_default_traits { public: -static ub4 as_ub4( ub4 i ){ - return i; -} + static ub4 as_ub4( ub4 i ){ + return i; + } }; class ub4_nocase_traits { public: -static ub4 as_ub4( ub4 i ){ - return ub1x4_as_ub4_nocase( reinterpret_cast( &i ) ); -} + static ub4 as_ub4( ub4 i ){ + return ub1x4_as_ub4_nocase( reinterpret_cast( &i ) ); + } }; // lookup2.c @@ -176,12 +176,12 @@ static ub4 as_ub4( ub4 i ){ template inline ub4 hash( - const ub1 *k, /* the key */ - ub4 length, /* the length of the key */ - ub4 initval, /* the previous hash, or an arbitrary value */ - const UB1Traits& ub1traits, - const UB4x1Traits& ub4x1traits - ){ + const ub1 *k, /* the key */ + ub4 length, /* the length of the key */ + ub4 initval, /* the previous hash, or an arbitrary value */ + const UB1Traits& ub1traits, + const UB4x1Traits& ub4x1traits +){ ub4 a,b,c,len; /* Set up the internal state */ @@ -196,7 +196,8 @@ inline ub4 hash( b += ( k[4] + ( ( ub4 ) UB1Traits::as_ub1( k[5] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[6] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[7] ) << 24 ) ); c += ( k[8] + ( ( ub4 ) UB1Traits::as_ub1( k[9] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[10] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[11] ) << 24 ) ); mix( a,b,c ); - k += 12; len -= 12; + k += 12; + len -= 12; } /*------------------------------------- handle the last 11 bytes */ @@ -235,11 +236,11 @@ inline ub4 hash( */ template inline ub4 hash2( - const ub4 *k, /* the key */ - ub4 length, /* the length of the key, in ub4s */ - ub4 initval, /* the previous hash, or an arbitrary value */ - const UB4Traits& ub4traits - ){ + const ub4 *k, /* the key */ + ub4 length, /* the length of the key, in ub4s */ + ub4 initval, /* the previous hash, or an arbitrary value */ + const UB4Traits& ub4traits +){ ub4 a,b,c,len; /* Set up the internal state */ @@ -254,7 +255,8 @@ inline ub4 hash2( b += UB4Traits::as_ub4( k[1] ); c += UB4Traits::as_ub4( k[2] ); mix( a,b,c ); - k += 3; len -= 3; + k += 3; + len -= 3; } /*-------------------------------------- handle the last 2 ub4's */ @@ -340,51 +342,51 @@ inline std::size_t string_length_ub4( const char* string ){ template class HashKey { -Array m_key; -hash_t m_hash; + Array m_key; + hash_t m_hash; -void copy( const HashKey& other ){ - std::copy( other.m_key.begin(), other.m_key.end(), m_key.begin() ); - m_hash = other.m_hash; -} -void copy( const char* string ){ - strncpy( reinterpret_cast( m_key.data() ), string, m_key.size() ); - for ( Array::iterator i = m_key.begin(); i != m_key.end(); ++i ) - { - *i = UB4Traits::as_ub4( *i ); + void copy( const HashKey& other ){ + std::copy( other.m_key.begin(), other.m_key.end(), m_key.begin() ); + m_hash = other.m_hash; + } + void copy( const char* string ){ + strncpy( reinterpret_cast( m_key.data() ), string, m_key.size() ); + for ( Array::iterator i = m_key.begin(); i != m_key.end(); ++i ) + { + *i = UB4Traits::as_ub4( *i ); + } + m_hash = hash_ub4( m_key.data(), m_key.size(), ub4_default_traits() ); + } + bool equal( const HashKey& other ) const { + return m_hash == other.m_hash && m_key.size() == other.m_key.size() + && std::equal( m_key.begin(), m_key.end(), other.m_key.begin() ); } - m_hash = hash_ub4( m_key.data(), m_key.size(), ub4_default_traits() ); -} -bool equal( const HashKey& other ) const { - return m_hash == other.m_hash && m_key.size() == other.m_key.size() - && std::equal( m_key.begin(), m_key.end(), other.m_key.begin() ); -} public: -HashKey( const HashKey& other ) : m_key( other.m_key.size() ){ - copy( other ); -} -HashKey( const char* string ) : m_key( string_length_ub4( string ) ){ - copy( string ); -} -HashKey& operator=( const char* string ){ - m_key.resize( string_length_ub4( string ) ); - copy( string ); - return *this; -} -bool operator==( const HashKey& other ) const { - return equal( other ); -} -bool operator!=( const HashKey& other ) const { - return !equal( other ); -} -hash_t hash() const { - return m_hash; -} + HashKey( const HashKey& other ) : m_key( other.m_key.size() ){ + copy( other ); + } + HashKey( const char* string ) : m_key( string_length_ub4( string ) ){ + copy( string ); + } + HashKey& operator=( const char* string ){ + m_key.resize( string_length_ub4( string ) ); + copy( string ); + return *this; + } + bool operator==( const HashKey& other ) const { + return equal( other ); + } + bool operator!=( const HashKey& other ) const { + return !equal( other ); + } + hash_t hash() const { + return m_hash; + } #if 0 -const char* c_str() const { - return reinterpret_cast( m_key.data() ); -} + const char* c_str() const { + return reinterpret_cast( m_key.data() ); + } #endif }; diff --git a/libs/container/hashtable.h b/libs/container/hashtable.h index 2c5677ce..7e4d8227 100644 --- a/libs/container/hashtable.h +++ b/libs/container/hashtable.h @@ -111,49 +111,49 @@ struct BucketNode : public BucketNodeBase template class BucketIterator { -typedef BucketNode Node; -Node* m_node; + typedef BucketNode Node; + Node* m_node; -void increment(){ - m_node = m_node->getNext(); -} + void increment(){ + m_node = m_node->getNext(); + } public: -typedef std::forward_iterator_tag iterator_category; -typedef std::ptrdiff_t difference_type; -typedef difference_type distance_type; -typedef KeyValue value_type; -typedef value_type* pointer; -typedef value_type& reference; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + typedef difference_type distance_type; + typedef KeyValue value_type; + typedef value_type* pointer; + typedef value_type& reference; -BucketIterator( Node* node ) : m_node( node ){ -} + BucketIterator( Node* node ) : m_node( node ){ + } -Node* node(){ - return m_node; -} + Node* node(){ + return m_node; + } -bool operator==( const BucketIterator& other ) const { - return m_node == other.m_node; -} -bool operator!=( const BucketIterator& other ) const { - return !operator==( other ); -} -BucketIterator& operator++(){ - increment(); - return *this; -} -BucketIterator operator++( int ){ - BucketIterator tmp = *this; - increment(); - return tmp; -} -value_type& operator*() const { - return m_node->m_value; -} -value_type* operator->() const { - return &( operator*() ); -} + bool operator==( const BucketIterator& other ) const { + return m_node == other.m_node; + } + bool operator!=( const BucketIterator& other ) const { + return !operator==( other ); + } + BucketIterator& operator++(){ + increment(); + return *this; + } + BucketIterator operator++( int ){ + BucketIterator tmp = *this; + increment(); + return tmp; + } + value_type& operator*() const { + return m_node->m_value; + } + value_type* operator->() const { + return &( operator*() ); + } }; } @@ -175,236 +175,236 @@ value_type* operator->() const { template > class HashTable : private KeyEqual, private Hasher { -typedef typename Hasher::hash_type hash_type; -typedef HashTableDetail::KeyValue KeyValue; -typedef HashTableDetail::BucketNode BucketNode; + typedef typename Hasher::hash_type hash_type; + typedef HashTableDetail::KeyValue KeyValue; + typedef HashTableDetail::BucketNode BucketNode; -inline BucketNode* node_create( hash_type hash, const Key& key, const Value& value ){ - return new BucketNode( hash, key, value ); -} -inline void node_destroy( BucketNode* node ){ - delete node; -} + inline BucketNode* node_create( hash_type hash, const Key& key, const Value& value ){ + return new BucketNode( hash, key, value ); + } + inline void node_destroy( BucketNode* node ){ + delete node; + } -typedef BucketNode* Bucket; + typedef BucketNode* Bucket; -static Bucket* buckets_new( std::size_t count ){ - Bucket* buckets = new Bucket[count]; - std::uninitialized_fill( buckets, buckets + count, Bucket( 0 ) ); - return buckets; -} -static void buckets_delete( Bucket* buckets ){ - delete[] buckets; -} + static Bucket* buckets_new( std::size_t count ){ + Bucket* buckets = new Bucket[count]; + std::uninitialized_fill( buckets, buckets + count, Bucket( 0 ) ); + return buckets; + } + static void buckets_delete( Bucket* buckets ){ + delete[] buckets; + } -std::size_t m_bucketCount; -Bucket* m_buckets; -std::size_t m_size; -HashTableDetail::BucketNodeBase m_list; + std::size_t m_bucketCount; + Bucket* m_buckets; + std::size_t m_size; + HashTableDetail::BucketNodeBase m_list; -BucketNode* getFirst(){ - return static_cast( m_list.next ); -} -BucketNode* getLast(){ - return static_cast( &m_list ); -} + BucketNode* getFirst(){ + return static_cast( m_list.next ); + } + BucketNode* getLast(){ + return static_cast( &m_list ); + } public: -typedef KeyValue value_type; -typedef HashTableDetail::BucketIterator iterator; + typedef KeyValue value_type; + typedef HashTableDetail::BucketIterator iterator; private: -void initialise(){ - list_initialise( m_list ); -} -hash_type hashKey( const Key& key ){ - return Hasher::operator()( key ); -} + void initialise(){ + list_initialise( m_list ); + } + hash_type hashKey( const Key& key ){ + return Hasher::operator()( key ); + } -std::size_t getBucketId( hash_type hash ) const { - return hash & ( m_bucketCount - 1 ); -} -Bucket& getBucket( hash_type hash ){ - return m_buckets[getBucketId( hash )]; -} -BucketNode* bucket_find( Bucket bucket, hash_type hash, const Key& key ){ - std::size_t bucketId = getBucketId( hash ); - for ( iterator i( bucket ); i != end(); ++i ) - { - hash_type nodeHash = i.node()->m_hash; + std::size_t getBucketId( hash_type hash ) const { + return hash & ( m_bucketCount - 1 ); + } + Bucket& getBucket( hash_type hash ){ + return m_buckets[getBucketId( hash )]; + } + BucketNode* bucket_find( Bucket bucket, hash_type hash, const Key& key ){ + std::size_t bucketId = getBucketId( hash ); + for ( iterator i( bucket ); i != end(); ++i ) + { + hash_type nodeHash = i.node()->m_hash; - if ( getBucketId( nodeHash ) != bucketId ) { - return 0; + if ( getBucketId( nodeHash ) != bucketId ) { + return 0; + } + + if ( nodeHash == hash && KeyEqual::operator()( ( *i ).key, key ) ) { + return i.node(); + } } + return 0; + } + BucketNode* bucket_insert( Bucket& bucket, BucketNode* node ){ + // link node into list + node_link( node, bucket_next( bucket ) ); + bucket = node; + return node; + } + BucketNode* bucket_next( Bucket& bucket ){ + Bucket* end = m_buckets + m_bucketCount; + for ( Bucket* i = &bucket; i != end; ++i ) + { + if ( *i != 0 ) { + return *i; + } + } + return getLast(); + } - if ( nodeHash == hash && KeyEqual::operator()( ( *i ).key, key ) ) { - return i.node(); + void buckets_resize( std::size_t count ){ + BucketNode* first = getFirst(); + BucketNode* last = getLast(); + + buckets_delete( m_buckets ); + + m_bucketCount = count; + + m_buckets = buckets_new( m_bucketCount ); + initialise(); + + for ( BucketNode* i = first; i != last; ) + { + BucketNode* node = i; + i = i->getNext(); + bucket_insert( getBucket( ( *node ).m_hash ), node ); } } - return 0; -} -BucketNode* bucket_insert( Bucket& bucket, BucketNode* node ){ - // link node into list - node_link( node, bucket_next( bucket ) ); - bucket = node; - return node; -} -BucketNode* bucket_next( Bucket& bucket ){ - Bucket* end = m_buckets + m_bucketCount; - for ( Bucket* i = &bucket; i != end; ++i ) - { - if ( *i != 0 ) { - return *i; + void size_increment(){ + if ( m_size == m_bucketCount ) { + buckets_resize( m_bucketCount == 0 ? 8 : m_bucketCount << 1 ); } + ++m_size; } - return getLast(); -} - -void buckets_resize( std::size_t count ){ - BucketNode* first = getFirst(); - BucketNode* last = getLast(); - - buckets_delete( m_buckets ); - - m_bucketCount = count; - - m_buckets = buckets_new( m_bucketCount ); - initialise(); - - for ( BucketNode* i = first; i != last; ) - { - BucketNode* node = i; - i = i->getNext(); - bucket_insert( getBucket( ( *node ).m_hash ), node ); + void size_decrement(){ + --m_size; } -} -void size_increment(){ - if ( m_size == m_bucketCount ) { - buckets_resize( m_bucketCount == 0 ? 8 : m_bucketCount << 1 ); - } - ++m_size; -} -void size_decrement(){ - --m_size; -} -HashTable( const HashTable& other ); -HashTable& operator=( const HashTable& other ); + HashTable( const HashTable& other ); + HashTable& operator=( const HashTable& other ); public: -HashTable() : m_bucketCount( 0 ), m_buckets( 0 ), m_size( 0 ){ - initialise(); -} -HashTable( std::size_t bucketCount ) : m_bucketCount( HashTableDetail::next_power_of_two( bucketCount ) ), m_buckets( buckets_new( m_bucketCount ) ), m_size( 0 ){ - initialise(); -} -~HashTable(){ - for ( BucketNode* i = getFirst(); i != getLast(); ) - { - BucketNode* node = i; - i = i->getNext(); - node_destroy( node ); + HashTable() : m_bucketCount( 0 ), m_buckets( 0 ), m_size( 0 ){ + initialise(); + } + HashTable( std::size_t bucketCount ) : m_bucketCount( HashTableDetail::next_power_of_two( bucketCount ) ), m_buckets( buckets_new( m_bucketCount ) ), m_size( 0 ){ + initialise(); + } + ~HashTable(){ + for ( BucketNode* i = getFirst(); i != getLast(); ) + { + BucketNode* node = i; + i = i->getNext(); + node_destroy( node ); + } + buckets_delete( m_buckets ); } - buckets_delete( m_buckets ); -} -iterator begin(){ - return iterator( getFirst() ); -} -iterator end(){ - return iterator( getLast() ); -} + iterator begin(){ + return iterator( getFirst() ); + } + iterator end(){ + return iterator( getLast() ); + } -bool empty() const { - return m_size == 0; -} -std::size_t size() const { - return m_size; -} + bool empty() const { + return m_size == 0; + } + std::size_t size() const { + return m_size; + } /// \brief Returns an iterator pointing to the value associated with \p key if it is contained by the hash-table, else \c end(). -iterator find( const Key& key ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - return iterator( node ); + iterator find( const Key& key ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return iterator( node ); + } } } - } - return end(); -} + return end(); + } /// \brief Adds \p value to the hash-table associated with \p key if it does not exist. -iterator insert( const Key& key, const Value& value ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket& bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - return iterator( node ); + iterator insert( const Key& key, const Value& value ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket& bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return iterator( node ); + } } } - } - size_increment(); - return iterator( bucket_insert( getBucket( hash ), node_create( hash, key, value ) ) ); -} + size_increment(); + return iterator( bucket_insert( getBucket( hash ), node_create( hash, key, value ) ) ); + } /// \brief Removes the value pointed to by \p i from the hash-table. /// /// \p i must be a deferenceable iterator into the hash-table. -void erase( iterator i ){ - Bucket& bucket = getBucket( i.node()->m_hash ); - BucketNode* node = i.node(); + void erase( iterator i ){ + Bucket& bucket = getBucket( i.node()->m_hash ); + BucketNode* node = i.node(); - // if this was the last node in the bucket - if ( bucket == node ) { - bucket = ( node->getNext() == getLast() || &getBucket( node->getNext()->m_hash ) != &bucket ) ? 0 : node->getNext(); + // if this was the last node in the bucket + if ( bucket == node ) { + bucket = ( node->getNext() == getLast() || &getBucket( node->getNext()->m_hash ) != &bucket ) ? 0 : node->getNext(); + } + + node_unlink( node ); + ASSERT_MESSAGE( node != 0, "tried to erase a non-existent key/value" ); + node_destroy( node ); + + size_decrement(); } - node_unlink( node ); - ASSERT_MESSAGE( node != 0, "tried to erase a non-existent key/value" ); - node_destroy( node ); - - size_decrement(); -} - /// \brief Returns the value identified by \p key if it is contained by the hash-table, else inserts and returns a new default-constructed value associated with \p key. -Value& operator[]( const Key& key ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket& bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - return node->m_value.value; + Value& operator[]( const Key& key ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket& bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return node->m_value.value; + } } } + size_increment(); + return bucket_insert( getBucket( hash ), node_create( hash, key, Value() ) )->m_value.value; } - size_increment(); - return bucket_insert( getBucket( hash ), node_create( hash, key, Value() ) )->m_value.value; -} /// \brief Removes the value associated with \p key from the hash-table. -void erase( const Key& key ){ - erase( find( key ) ); -} + void erase( const Key& key ){ + erase( find( key ) ); + } /// \brief Swaps the contents of the hash-table with \p other. -void swap( HashTable& other ){ - std::swap( m_buckets, other.m_buckets ); - std::swap( m_bucketCount, other.m_bucketCount ); - std::swap( m_size, other.m_size ); - HashTableDetail::list_swap( m_list, other.m_list ); -} + void swap( HashTable& other ){ + std::swap( m_buckets, other.m_buckets ); + std::swap( m_bucketCount, other.m_bucketCount ); + std::swap( m_size, other.m_size ); + HashTableDetail::list_swap( m_list, other.m_list ); + } /// \brief Removes all values from the hash-table. -void clear(){ - HashTable tmp; - tmp.swap( *this ); -} + void clear(){ + HashTable tmp; + tmp.swap( *this ); + } }; #endif diff --git a/libs/container/stack.h b/libs/container/stack.h index 10040a74..d33d7b99 100644 --- a/libs/container/stack.h +++ b/libs/container/stack.h @@ -36,159 +36,159 @@ template class Stack : public DefaultAllocator { -typedef DefaultAllocator Allocator; + typedef DefaultAllocator Allocator; -enum -{ - DEFAULT_CAPACITY = 4, -}; + enum + { + DEFAULT_CAPACITY = 4, + }; -typedef Type* pointer; -typedef const Type* const_pointer; + typedef Type* pointer; + typedef const Type* const_pointer; public: -typedef const_pointer const_iterator; + typedef const_pointer const_iterator; private: -pointer m_data; -pointer m_end; -std::size_t m_capacity; + pointer m_data; + pointer m_end; + std::size_t m_capacity; -void insert( const Type& value ){ - Allocator::construct( m_end++, value ); -} -void insert_overflow( const Type& value ){ - const std::size_t new_capacity = ( m_capacity ) ? m_capacity + m_capacity : std::size_t( DEFAULT_CAPACITY ); - const pointer new_data = Allocator::allocate( new_capacity ); - const pointer new_end = std::copy( m_data, m_end, new_data ); - - destroy(); - Allocator::deallocate( m_data, m_capacity ); - - m_capacity = new_capacity; - m_data = new_data; - m_end = new_end; - insert( value ); -} -void destroy(){ - for ( pointer p = m_data; p != m_end; ++p ) - { - Allocator::destroy( p ); + void insert( const Type& value ){ + Allocator::construct( m_end++, value ); } -} -void construct( const Stack& other ){ - pointer p = m_data; - for ( const_iterator i = other.begin(); i != other.end(); ++i ) - { - Allocator::construct( p++, *i ); + void insert_overflow( const Type& value ){ + const std::size_t new_capacity = ( m_capacity ) ? m_capacity + m_capacity : std::size_t( DEFAULT_CAPACITY ); + const pointer new_data = Allocator::allocate( new_capacity ); + const pointer new_end = std::copy( m_data, m_end, new_data ); + + destroy(); + Allocator::deallocate( m_data, m_capacity ); + + m_capacity = new_capacity; + m_data = new_data; + m_end = new_end; + insert( value ); + } + void destroy(){ + for ( pointer p = m_data; p != m_end; ++p ) + { + Allocator::destroy( p ); + } + } + void construct( const Stack& other ){ + pointer p = m_data; + for ( const_iterator i = other.begin(); i != other.end(); ++i ) + { + Allocator::construct( p++, *i ); + } } -} public: -Stack() : - m_data( 0 ), - m_end( 0 ), - m_capacity( 0 ){ -} -Stack( const Type& value ) : - m_data( 0 ), - m_end( 0 ), - m_capacity( 0 ){ - push( value ); -} -Stack( const Stack& other ) : - DefaultAllocator( other ){ - m_capacity = other.m_capacity; - m_data = Allocator::allocate( m_capacity ); - construct( other ); - m_end = m_data + other.size(); -} -~Stack(){ - destroy(); - Allocator::deallocate( m_data, m_capacity ); -} - -const_iterator begin() const { - return m_data; -} -const_iterator end() const { - return m_end; -} - -bool empty() const { - return end() == begin(); -} -void clear(){ - destroy(); - m_end = m_data; -} - -std::size_t size() const { - return m_end - m_data; -} -Type operator[]( const std::size_t i ) const { - return m_data[i]; -} -/// \brief Pushes \p value onto the stack at the top element. If reserved storage is insufficient for the new element, this will invalidate all iterators. -void push( const Type& value ){ - if ( size() == m_capacity ) { - insert_overflow( value ); + Stack() : + m_data( 0 ), + m_end( 0 ), + m_capacity( 0 ){ } - else - { - insert( value ); + Stack( const Type& value ) : + m_data( 0 ), + m_end( 0 ), + m_capacity( 0 ){ + push( value ); } -} -/// \brief Removes the top element of the stack. -void pop(){ - Allocator::destroy( --m_end ); -} -/// \brief Returns the top element of the mutable stack. -Type& top(){ - return *( m_end - 1 ); -} -/// \brief Returns the top element of the non-mutable stack. -const Type& top() const { - return *( m_end - 1 ); -} -/// \brief Returns the element below the top element of the mutable stack. -Type& parent(){ - return *( m_end - 2 ); -} -/// \brief Returns the element below the top element of the non-mutable stack. -const Type& parent() const { - return *( m_end - 2 ); -} -/// \brief Swaps the values of this stack and \p other. -void swap( Stack& other ){ - std::swap( m_data, other.m_data ); - std::swap( m_end, other.m_end ); - std::swap( m_capacity, other.m_capacity ); -} -#if 1 // use copy-swap technique -Stack& operator=( const Stack& other ){ - Stack temp( other ); - temp.swap( *this ); - return *this; -} -#else // avoids memory allocation if capacity is already sufficient. -Stack& operator=( const Stack& other ){ - if ( &other != this ) { - destroy(); - - if ( other.size() > m_capacity ) { - Allocator::deallocate( m_data, m_capacity ); - m_capacity = other.m_capacity; - m_data = Allocator::allocate( m_capacity ); - } - m_end = m_data + other.size(); - + Stack( const Stack& other ) : + DefaultAllocator( other ){ + m_capacity = other.m_capacity; + m_data = Allocator::allocate( m_capacity ); construct( other ); + m_end = m_data + other.size(); + } + ~Stack(){ + destroy(); + Allocator::deallocate( m_data, m_capacity ); + } + + const_iterator begin() const { + return m_data; + } + const_iterator end() const { + return m_end; + } + + bool empty() const { + return end() == begin(); + } + void clear(){ + destroy(); + m_end = m_data; + } + + std::size_t size() const { + return m_end - m_data; + } + Type operator[]( const std::size_t i ) const { + return m_data[i]; + } +/// \brief Pushes \p value onto the stack at the top element. If reserved storage is insufficient for the new element, this will invalidate all iterators. + void push( const Type& value ){ + if ( size() == m_capacity ) { + insert_overflow( value ); + } + else + { + insert( value ); + } + } +/// \brief Removes the top element of the stack. + void pop(){ + Allocator::destroy( --m_end ); + } +/// \brief Returns the top element of the mutable stack. + Type& top(){ + return *( m_end - 1 ); + } +/// \brief Returns the top element of the non-mutable stack. + const Type& top() const { + return *( m_end - 1 ); + } +/// \brief Returns the element below the top element of the mutable stack. + Type& parent(){ + return *( m_end - 2 ); + } +/// \brief Returns the element below the top element of the non-mutable stack. + const Type& parent() const { + return *( m_end - 2 ); + } +/// \brief Swaps the values of this stack and \p other. + void swap( Stack& other ){ + std::swap( m_data, other.m_data ); + std::swap( m_end, other.m_end ); + std::swap( m_capacity, other.m_capacity ); + } +#if 1 // use copy-swap technique + Stack& operator=( const Stack& other ){ + Stack temp( other ); + temp.swap( *this ); + return *this; + } +#else // avoids memory allocation if capacity is already sufficient. + Stack& operator=( const Stack& other ){ + if ( &other != this ) { + destroy(); + + if ( other.size() > m_capacity ) { + Allocator::deallocate( m_data, m_capacity ); + m_capacity = other.m_capacity; + m_data = Allocator::allocate( m_capacity ); + } + m_end = m_data + other.size(); + + construct( other ); + } + return *this; } - return *this; -} #endif }; diff --git a/libs/convert.h b/libs/convert.h index 2ca82bf7..ca763806 100644 --- a/libs/convert.h +++ b/libs/convert.h @@ -83,19 +83,19 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const /// Obtain the global instance with globalCharacterSet(). class CharacterSet { -const char* m_charSet; + const char* m_charSet; public: -CharacterSet(){ - if ( g_get_charset( &m_charSet ) ) { - m_charSet = 0; + CharacterSet(){ + if ( g_get_charset( &m_charSet ) ) { + m_charSet = 0; + } + } + bool isUTF8() const { + return m_charSet == 0; + } + const char* get() const { + return m_charSet; } -} -bool isUTF8() const { - return m_charSet == 0; -} -const char* get() const { - return m_charSet; -} }; typedef LazyStatic GlobalCharacterSet; @@ -109,12 +109,12 @@ inline CharacterSet& globalCharacterSet(){ class UTF8CharacterToExtendedASCII { public: -UTF8Character m_utf8; -char m_c; -UTF8CharacterToExtendedASCII() : m_c( '\0' ){ -} -UTF8CharacterToExtendedASCII( const UTF8Character& utf8, char c ) : m_utf8( utf8 ), m_c( c ){ -} + UTF8Character m_utf8; + char m_c; + UTF8CharacterToExtendedASCII() : m_c( '\0' ){ + } + UTF8CharacterToExtendedASCII( const UTF8Character& utf8, char c ) : m_utf8( utf8 ), m_c( c ){ + } }; inline bool operator<( const UTF8CharacterToExtendedASCII& self, const UTF8CharacterToExtendedASCII& other ){ @@ -135,60 +135,60 @@ inline char extended_ascii_for_index( std::size_t i ){ /// Obtain the global instance with globalExtendedASCIICharacterSet(). class ExtendedASCIICharacterSet { -typedef char UTF8CharBuffer[6]; -UTF8CharBuffer m_converted[128]; -UTF8Character m_decodeMap[128]; -UTF8CharacterToExtendedASCII m_encodeMap[128]; + typedef char UTF8CharBuffer[6]; + UTF8CharBuffer m_converted[128]; + UTF8Character m_decodeMap[128]; + UTF8CharacterToExtendedASCII m_encodeMap[128]; public: -ExtendedASCIICharacterSet(){ - if ( !globalCharacterSet().isUTF8() ) { - GIConv descriptor = g_iconv_open( "UTF-8", globalCharacterSet().get() ); - for ( std::size_t i = 1; i < 128; ++i ) - { - char c = extended_ascii_for_index( i ); - char* inbuf = &c; - std::size_t inbytesleft = 1; - char* outbuf = m_converted[i]; - std::size_t outbytesleft = 6; - if ( g_iconv( descriptor, &inbuf, &inbytesleft, &outbuf, &outbytesleft ) != (size_t)( -1 ) ) { - UTF8Character utf8( m_converted[i] ); - m_decodeMap[i] = utf8; - m_encodeMap[i] = UTF8CharacterToExtendedASCII( utf8, c ); + ExtendedASCIICharacterSet(){ + if ( !globalCharacterSet().isUTF8() ) { + GIConv descriptor = g_iconv_open( "UTF-8", globalCharacterSet().get() ); + for ( std::size_t i = 1; i < 128; ++i ) + { + char c = extended_ascii_for_index( i ); + char* inbuf = &c; + std::size_t inbytesleft = 1; + char* outbuf = m_converted[i]; + std::size_t outbytesleft = 6; + if ( g_iconv( descriptor, &inbuf, &inbytesleft, &outbuf, &outbytesleft ) != (size_t)( -1 ) ) { + UTF8Character utf8( m_converted[i] ); + m_decodeMap[i] = utf8; + m_encodeMap[i] = UTF8CharacterToExtendedASCII( utf8, c ); + } } + g_iconv_close( descriptor ); + std::sort( m_encodeMap, m_encodeMap + 128 ); } - g_iconv_close( descriptor ); - std::sort( m_encodeMap, m_encodeMap + 128 ); } -} /// \brief Prints the (up to) 128 characters in the current extended-ascii character set. /// Useful for debugging. -void print() const { - globalOutputStream() << "UTF-8 conversion required from charset: " << globalCharacterSet().get() << "\n"; - for ( std::size_t i = 1; i < 128; ++i ) - { - if ( m_decodeMap[i].buffer != 0 ) { - globalOutputStream() << extended_ascii_for_index( i ) << " = " << m_decodeMap[i] << "\n"; + void print() const { + globalOutputStream() << "UTF-8 conversion required from charset: " << globalCharacterSet().get() << "\n"; + for ( std::size_t i = 1; i < 128; ++i ) + { + if ( m_decodeMap[i].buffer != 0 ) { + globalOutputStream() << extended_ascii_for_index( i ) << " = " << m_decodeMap[i] << "\n"; + } } } -} /// \brief Returns \p c decoded from extended-ascii to UTF-8. /// \p c must be an extended-ascii character. -const UTF8Character& decode( char c ) const { - ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); - ASSERT_MESSAGE( !char_is_ascii( c ), "decode: ascii character" ); - ASSERT_MESSAGE( m_decodeMap[extended_ascii_to_index( c )].buffer != 0, "decode: invalid character: " << HexChar( c ) ); - return m_decodeMap[extended_ascii_to_index( c )]; -} + const UTF8Character& decode( char c ) const { + ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); + ASSERT_MESSAGE( !char_is_ascii( c ), "decode: ascii character" ); + ASSERT_MESSAGE( m_decodeMap[extended_ascii_to_index( c )].buffer != 0, "decode: invalid character: " << HexChar( c ) ); + return m_decodeMap[extended_ascii_to_index( c )]; + } /// \brief Returns \p c encoded to extended-ascii from UTF-8. /// \p c must map to an extended-ascii character. -char encode( const UTF8Character& c ) const { - ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); - ASSERT_MESSAGE( !char_is_ascii( *c.buffer ), "encode: ascii character" ); - std::pair range - = std::equal_range( m_encodeMap, m_encodeMap + 128, UTF8CharacterToExtendedASCII( c, 0 ) ); - ASSERT_MESSAGE( range.first != range.second, "encode: invalid character: " << c ); - return ( *range.first ).m_c; -} + char encode( const UTF8Character& c ) const { + ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); + ASSERT_MESSAGE( !char_is_ascii( *c.buffer ), "encode: ascii character" ); + std::pair range + = std::equal_range( m_encodeMap, m_encodeMap + 128, UTF8CharacterToExtendedASCII( c, 0 ) ); + ASSERT_MESSAGE( range.first != range.second, "encode: invalid character: " << c ); + return ( *range.first ).m_c; + } }; typedef LazyStatic GlobalExtendedASCIICharacterSet; @@ -201,11 +201,11 @@ inline ExtendedASCIICharacterSet& globalExtendedASCIICharacterSet(){ class ConvertUTF8ToLocale { public: -StringRange m_range; -ConvertUTF8ToLocale( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ -} -ConvertUTF8ToLocale( const StringRange& range ) : m_range( range ){ -} + StringRange m_range; + ConvertUTF8ToLocale( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ + } + ConvertUTF8ToLocale( const StringRange& range ) : m_range( range ){ + } }; /// \brief Writes \p convert to \p ostream after encoding each character to extended-ascii from UTF-8. @@ -234,11 +234,11 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class ConvertLocaleToUTF8 { public: -StringRange m_range; -ConvertLocaleToUTF8( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ -} -ConvertLocaleToUTF8( const StringRange& range ) : m_range( range ){ -} + StringRange m_range; + ConvertLocaleToUTF8( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ + } + ConvertLocaleToUTF8( const StringRange& range ) : m_range( range ){ + } }; /// \brief Writes \p convert to \p ostream after decoding each character from extended-ascii to UTF-8. diff --git a/libs/debugging/debugging.h b/libs/debugging/debugging.h index c549a2f2..bf553f74 100644 --- a/libs/debugging/debugging.h +++ b/libs/debugging/debugging.h @@ -50,49 +50,49 @@ class DebugMessageHandler { public: -virtual TextOutputStream& getOutputStream() = 0; -virtual bool handleMessage() = 0; + virtual TextOutputStream& getOutputStream() = 0; + virtual bool handleMessage() = 0; }; class NullDebugMessageHandler : public NullOutputStream, public DebugMessageHandler { public: -virtual TextOutputStream& getOutputStream(){ - return *this; -} -virtual bool handleMessage(){ - return false; -} + virtual TextOutputStream& getOutputStream(){ + return *this; + } + virtual bool handleMessage(){ + return false; + } }; class DefaultDebugMessageHandler : public DebugMessageHandler { public: -virtual TextOutputStream& getOutputStream(){ - return globalErrorStream(); -} -virtual bool handleMessage(){ + virtual TextOutputStream& getOutputStream(){ + return globalErrorStream(); + } + virtual bool handleMessage(){ #if defined( _DEBUG ) - return false; // send debug-break + return false; // send debug-break #else - return true; + return true; #endif -} + } }; class DebugMessageHandlerRef : public DefaultDebugMessageHandler { -DebugMessageHandler* m_handler; + DebugMessageHandler* m_handler; public: -DebugMessageHandlerRef() - : m_handler( this ){ -} -void setHandler( DebugMessageHandler& handler ){ - m_handler = &handler; -} -DebugMessageHandler& getHandler(){ - return *m_handler; -} + DebugMessageHandlerRef() + : m_handler( this ){ + } + void setHandler( DebugMessageHandler& handler ){ + m_handler = &handler; + } + DebugMessageHandler& getHandler(){ + return *m_handler; + } }; typedef Static GlobalDebugMessageHandler; diff --git a/libs/dragplanes.h b/libs/dragplanes.h index ad700221..efd78f4c 100644 --- a/libs/dragplanes.h +++ b/libs/dragplanes.h @@ -31,323 +31,324 @@ // local must be a pure rotation inline Vector3 translation_to_local( const Vector3& translation, const Matrix4& local ){ return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3( matrix4_transposed( local ), translation ), - local - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( matrix4_transposed( local ), translation ), + local + ) + ); } // local must be a pure rotation inline Vector3 translation_from_local( const Vector3& translation, const Matrix4& local ){ return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3( local, translation ), - matrix4_transposed( local ) - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( local, translation ), + matrix4_transposed( local ) + ) + ); } class DragPlanes { -ObservedSelectable m_selectables[6]; + ObservedSelectable m_selectables[6]; public: -mutable AABB m_bounds; -DragPlanes( const SelectionChangeCallback& onchanged ) : m_selectables{ ObservedSelectable( onchanged ), - ObservedSelectable( onchanged ), - ObservedSelectable( onchanged ), - ObservedSelectable( onchanged ), - ObservedSelectable( onchanged ), - ObservedSelectable( onchanged ) }{ -} -bool isSelected() const { - for ( std::size_t i = 0; i < 6; ++i ) - if( m_selectables[i].isSelected() ) - return true; - return false; -} -void setSelected( bool selected ){ - for ( std::size_t i = 0; i < 6; ++i ) - m_selectables[i].setSelected( selected ); -} -void selectPlanes( const AABB& aabb, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback, const Matrix4& rotation = g_matrix4_identity ){ - Vector3 corners[8]; - aabb_corners_oriented( aabb, rotation, corners ); + mutable AABB m_bounds; + DragPlanes( const SelectionChangeCallback& onchanged ) : + m_selectables{ ObservedSelectable( onchanged ), + ObservedSelectable( onchanged ), + ObservedSelectable( onchanged ), + ObservedSelectable( onchanged ), + ObservedSelectable( onchanged ), + ObservedSelectable( onchanged ) }{ + } + bool isSelected() const { + for ( std::size_t i = 0; i < 6; ++i ) + if( m_selectables[i].isSelected() ) + return true; + return false; + } + void setSelected( bool selected ){ + for ( std::size_t i = 0; i < 6; ++i ) + m_selectables[i].setSelected( selected ); + } + void selectPlanes( const AABB& aabb, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback, const Matrix4& rotation = g_matrix4_identity ){ + Vector3 corners[8]; + aabb_corners_oriented( aabb, rotation, corners ); - Plane3 planes[6]; - aabb_planes_oriented( aabb, rotation, planes ); + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); - const std::size_t indices[24] = { - 2, 1, 5, 6, //+x //right - 3, 7, 4, 0, //-x //left - 1, 0, 4, 5, //+y //front - 3, 2, 6, 7, //-y //back - 0, 1, 2, 3, //+z //top - 7, 6, 5, 4, //-z //bottom - }; + const std::size_t indices[24] = { + 2, 1, 5, 6, //+x //right + 3, 7, 4, 0, //-x //left + 1, 0, 4, 5, //+y //front + 3, 2, 6, 7, //-y //back + 0, 1, 2, 3, //+z //top + 7, 6, 5, 4, //-z //bottom + }; - const Vector3 viewdir( test.getVolume().getViewDir() ); - double bestDot = 1; - ObservedSelectable* selectable = 0; - ObservedSelectable* selectable2 = 0; + const Vector3 viewdir( test.getVolume().getViewDir() ); + double bestDot = 1; + ObservedSelectable* selectable = 0; + ObservedSelectable* selectable2 = 0; - for ( std::size_t i = 0; i < 6; ++i ){ - const std::size_t index = i * 4; - const Vector3 centroid = vector3_mid( corners[indices[index]], corners[indices[index + 2]] ); - const Vector3 projected = vector4_projected( matrix4_transformed_vector4( test.getVolume().GetViewMatrix(), Vector4( centroid, 1 ) ) ); - const Vector3 closest_point = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, projected[2], 1 ) ) ); - if ( vector3_dot( planes[i].normal(), closest_point - corners[indices[index]] ) > 0 - && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 1]] ) > 0 - && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 2]] ) > 0 - && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 3]] ) > 0 ) { - const double dot = fabs( vector3_dot( planes[i].normal(), viewdir ) ); - const double diff = bestDot - dot; - if( diff > 0.03 ){ - bestDot = dot; - selectable = &m_selectables[i]; - selectable2 = 0; - } - else if( fabs( diff ) <= 0.03 ){ - selectable2 = &m_selectables[i]; + for ( std::size_t i = 0; i < 6; ++i ){ + const std::size_t index = i * 4; + const Vector3 centroid = vector3_mid( corners[indices[index]], corners[indices[index + 2]] ); + const Vector3 projected = vector4_projected( matrix4_transformed_vector4( test.getVolume().GetViewMatrix(), Vector4( centroid, 1 ) ) ); + const Vector3 closest_point = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, projected[2], 1 ) ) ); + if ( vector3_dot( planes[i].normal(), closest_point - corners[indices[index]] ) > 0 + && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 1]] ) > 0 + && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 2]] ) > 0 + && vector3_dot( planes[i].normal(), closest_point - corners[indices[index + 3]] ) > 0 ) { + const double dot = fabs( vector3_dot( planes[i].normal(), viewdir ) ); + const double diff = bestDot - dot; + if( diff > 0.03 ){ + bestDot = dot; + selectable = &m_selectables[i]; + selectable2 = 0; + } + else if( fabs( diff ) <= 0.03 ){ + selectable2 = &m_selectables[i]; + } } } + if( test.getVolume().fill() ) // select only plane in camera + selectable2 = 0; + for ( std::size_t i = 0; i < 6; ++i ) + if( &m_selectables[i] == selectable || &m_selectables[i] == selectable2 ){ + Selector_add( selector, m_selectables[i] ); + selectedPlaneCallback( planes[i] ); + } + m_bounds = aabb; } - if( test.getVolume().fill() ) // select only plane in camera - selectable2 = 0; - for ( std::size_t i = 0; i < 6; ++i ) - if( &m_selectables[i] == selectable || &m_selectables[i] == selectable2 ){ - Selector_add( selector, m_selectables[i] ); - selectedPlaneCallback( planes[i] ); - } - m_bounds = aabb; -} -void selectReversedPlanes( const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity ){ - Plane3 planes[6]; - aabb_planes_oriented( aabb, rotation, planes ); - for ( std::size_t i = 0; i < 6; ++i ) - if ( selectedPlanes.contains( plane3_flipped( planes[i] ) ) ) - Selector_add( selector, m_selectables[i] ); -} - -void bestPlaneDirect( const AABB& aabb, SelectionTest& test, Plane3& plane, SelectionIntersection& intersection, const Matrix4& rotation = g_matrix4_identity ) const { - AABB aabb_ = aabb; - for( std::size_t i = 0; i < 3; ++i ) /* make sides of flat patches more selectable */ - if( aabb_.extents[i] < 1 ) - aabb_.extents[i] = 4; - - Vector3 corners[8]; - aabb_corners_oriented( aabb_, rotation, corners ); - - Plane3 planes[6]; - aabb_planes_oriented( aabb_, rotation, planes ); - - const IndexPointer::index_type indices[24] = { - 2, 1, 5, 6, //+x //right - 3, 7, 4, 0, //-x //left - 1, 0, 4, 5, //+y //front - 3, 2, 6, 7, //-y //back - 0, 1, 2, 3, //+z //top - 7, 6, 5, 4, //-z //bottom - }; - - for ( std::size_t i = 0; i < 6; ++i ){ - const std::size_t index = i * 4; - SelectionIntersection intersection_new; - test.TestQuads( VertexPointer( reinterpret_cast( corners ), sizeof( Vector3 ) ), IndexPointer( &indices[index], 4 ), intersection_new ); - if( SelectionIntersection_closer( intersection_new, intersection ) ){ - intersection = intersection_new; - plane = planes[i]; - } + void selectReversedPlanes( const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity ){ + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); + for ( std::size_t i = 0; i < 6; ++i ) + if ( selectedPlanes.contains( plane3_flipped( planes[i] ) ) ) + Selector_add( selector, m_selectables[i] ); } - m_bounds = aabb; -} -void bestPlaneIndirect( const AABB& aabb, SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist, const Matrix4& rotation = g_matrix4_identity ) const { - Vector3 corners[8]; - aabb_corners_oriented( aabb, rotation, corners ); - Plane3 planes[6]; - aabb_planes_oriented( aabb, rotation, planes ); -/* - const std::size_t indices[24] = { - 2, 1, 5, 6, //+x //right - 3, 7, 4, 0, //-x //left - 1, 0, 4, 5, //+y //front - 3, 2, 6, 7, //-y //back - 0, 1, 2, 3, //+z //top - 7, 6, 5, 4, //-z //bottom - }; -*/ -/* + void bestPlaneDirect( const AABB& aabb, SelectionTest& test, Plane3& plane, SelectionIntersection& intersection, const Matrix4& rotation = g_matrix4_identity ) const { + AABB aabb_ = aabb; + for( std::size_t i = 0; i < 3; ++i ) /* make sides of flat patches more selectable */ + if( aabb_.extents[i] < 1 ) + aabb_.extents[i] = 4; - 0 ----- 1 - /| /| - / | / | - / | / | - 3 ----- 2 | - | 4|_|___|5 - | / | / - | / | / - |/ | / - 7|_____|/6 + Vector3 corners[8]; + aabb_corners_oriented( aabb_, rotation, corners ); - */ + Plane3 planes[6]; + aabb_planes_oriented( aabb_, rotation, planes ); - const std::size_t edges[24] = { - 0, 1, // x - 3, 2, - 7, 6, - 4, 5, - 2, 1, // y - 3, 0, - 6, 5, - 7, 4, - 4, 0, // z - 5, 1, - 6, 2, - 7, 3, - }; + const IndexPointer::index_type indices[24] = { + 2, 1, 5, 6, //+x //right + 3, 7, 4, 0, //-x //left + 1, 0, 4, 5, //+y //front + 3, 2, 6, 7, //-y //back + 0, 1, 2, 3, //+z //top + 7, 6, 5, 4, //-z //bottom + }; - const std::size_t adjacent_planes[24] = { - 4, 2, - 4, 3, - 5, 3, - 5, 2, - 4, 0, - 4, 1, - 5, 0, - 5, 1, - 1, 2, - 2, 0, - 0, 3, - 3, 1, - }; + for ( std::size_t i = 0; i < 6; ++i ){ + const std::size_t index = i * 4; + SelectionIntersection intersection_new; + test.TestQuads( VertexPointer( reinterpret_cast( corners ), sizeof( Vector3 ) ), IndexPointer( &indices[index], 4 ), intersection_new ); + if( SelectionIntersection_closer( intersection_new, intersection ) ){ + intersection = intersection_new; + plane = planes[i]; + } + } + m_bounds = aabb; + } + void bestPlaneIndirect( const AABB& aabb, SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist, const Matrix4& rotation = g_matrix4_identity ) const { + Vector3 corners[8]; + aabb_corners_oriented( aabb, rotation, corners ); - float dot = 1; - const bool some_extent_zero = aabb.extents[0] == 0 || aabb.extents[1] == 0 || aabb.extents[2] == 0; - for ( std::size_t i = 0; i < 24; ++++i ){ - Line line( corners[edges[i]], corners[edges[i + 1]] ); - if( aabb.extents[i / 8] != 0.f && matrix4_clip_line_by_nearplane( test.getVolume().GetViewMatrix(), line ) == 2 ){ - const Vector3 intersection_new = line_closest_point( line, g_vector3_identity ); - const float dist_new = vector3_length_squared( intersection_new ); - const float dot_new = fabs( vector3_dot( vector3_normalised( intersection_new ), vector3_normalised( line.end - line.start ) ) ); - //effective epsilon is rather big: optimized 32 bit build is using doubles implicitly (floats might be straightly checked for equality); same code in brush.h is cool with way smaller epsilon - if( dist - dist_new > 1e-2f // new dist noticeably smaller - || ( float_equal_epsilon( dist_new, dist, 1e-2f ) && dot_new < dot ) ){ // or ambiguous case. Resolve it by dot comparison - const Plane3& plane1 = planes[adjacent_planes[i]]; - const Plane3& plane2 = planes[adjacent_planes[i + 1]]; + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); + /* + const std::size_t indices[24] = { + 2, 1, 5, 6, //+x //right + 3, 7, 4, 0, //-x //left + 1, 0, 4, 5, //+y //front + 3, 2, 6, 7, //-y //back + 0, 1, 2, 3, //+z //top + 7, 6, 5, 4, //-z //bottom + }; + */ + /* - auto assign_plane = [&plane, &intersection, intersection_new, &dist, dist_new, &dot, dot_new]( const Plane3& plane_new ){ + 0 ----- 1 + /| /| + / | / | + / | / | + 3 ----- 2 | + | 4|_|___|5 + | / | / + | / | / + |/ | / + 7|_____|/6 + + */ + + const std::size_t edges[24] = { + 0, 1, // x + 3, 2, + 7, 6, + 4, 5, + 2, 1, // y + 3, 0, + 6, 5, + 7, 4, + 4, 0, // z + 5, 1, + 6, 2, + 7, 3, + }; + + const std::size_t adjacent_planes[24] = { + 4, 2, + 4, 3, + 5, 3, + 5, 2, + 4, 0, + 4, 1, + 5, 0, + 5, 1, + 1, 2, + 2, 0, + 0, 3, + 3, 1, + }; + + float dot = 1; + const bool some_extent_zero = aabb.extents[0] == 0 || aabb.extents[1] == 0 || aabb.extents[2] == 0; + for ( std::size_t i = 0; i < 24; ++++i ){ + Line line( corners[edges[i]], corners[edges[i + 1]] ); + if( aabb.extents[i / 8] != 0.f && matrix4_clip_line_by_nearplane( test.getVolume().GetViewMatrix(), line ) == 2 ){ + const Vector3 intersection_new = line_closest_point( line, g_vector3_identity ); + const float dist_new = vector3_length_squared( intersection_new ); + const float dot_new = fabs( vector3_dot( vector3_normalised( intersection_new ), vector3_normalised( line.end - line.start ) ) ); + //effective epsilon is rather big: optimized 32 bit build is using doubles implicitly (floats might be straightly checked for equality); same code in brush.h is cool with way smaller epsilon + if( dist - dist_new > 1e-2f // new dist noticeably smaller + || ( float_equal_epsilon( dist_new, dist, 1e-2f ) && dot_new < dot ) ){ // or ambiguous case. Resolve it by dot comparison + const Plane3& plane1 = planes[adjacent_planes[i]]; + const Plane3& plane2 = planes[adjacent_planes[i + 1]]; + + auto assign_plane = [&plane, &intersection, intersection_new, &dist, dist_new, &dot, dot_new]( const Plane3& plane_new ){ plane = plane_new; intersection = intersection_new; dist = dist_new; dot = dot_new; - }; + }; - if( test.getVolume().fill() ){ - if( plane3_distance_to_point( plane1, test.getVolume().getViewer() ) <= 0 ){ - if( aabb.extents[adjacent_planes[i] / 2] == 0 ) /* select the other, if zero bound */ - assign_plane( plane2 ); - else - assign_plane( plane1 ); - } - else if( plane3_distance_to_point( plane2, test.getVolume().getViewer() ) <= 0 ){ - if( aabb.extents[adjacent_planes[i + 1] / 2] == 0 ) /* select the other, if zero bound */ - assign_plane( plane1 ); - else - assign_plane( plane2 ); - } - } - else if( some_extent_zero || fabs( vector3_length_squared( line.end - line.start ) ) > 1e-3 ){ - if( fabs( vector3_dot( plane1.normal(), test.getVolume().getViewDir() ) ) < fabs( vector3_dot( plane2.normal(), test.getVolume().getViewDir() ) ) ){ - if( aabb.extents[adjacent_planes[i] / 2] == 0 ) /* select the other, if zero bound */ - assign_plane( plane2 ); - else - assign_plane( plane1 ); - } - else{ - if( aabb.extents[adjacent_planes[i + 1] / 2] == 0 ) /* select the other, if zero bound */ - assign_plane( plane1 ); - else - assign_plane( plane2 ); + if( test.getVolume().fill() ){ + if( plane3_distance_to_point( plane1, test.getVolume().getViewer() ) <= 0 ){ + if( aabb.extents[adjacent_planes[i] / 2] == 0 ) /* select the other, if zero bound */ + assign_plane( plane2 ); + else + assign_plane( plane1 ); + } + else if( plane3_distance_to_point( plane2, test.getVolume().getViewer() ) <= 0 ){ + if( aabb.extents[adjacent_planes[i + 1] / 2] == 0 ) /* select the other, if zero bound */ + assign_plane( plane1 ); + else + assign_plane( plane2 ); + } } + else if( some_extent_zero || fabs( vector3_length_squared( line.end - line.start ) ) > 1e-3 ){ + if( fabs( vector3_dot( plane1.normal(), test.getVolume().getViewDir() ) ) < fabs( vector3_dot( plane2.normal(), test.getVolume().getViewDir() ) ) ){ + if( aabb.extents[adjacent_planes[i] / 2] == 0 ) /* select the other, if zero bound */ + assign_plane( plane2 ); + else + assign_plane( plane1 ); + } + else{ + if( aabb.extents[adjacent_planes[i + 1] / 2] == 0 ) /* select the other, if zero bound */ + assign_plane( plane1 ); + else + assign_plane( plane2 ); + } + } } } } + m_bounds = aabb; } - m_bounds = aabb; -} -void selectByPlane( const AABB& aabb, const Plane3& plane, const Matrix4& rotation = g_matrix4_identity ){ - Plane3 planes[6]; - aabb_planes_oriented( aabb, rotation, planes ); + void selectByPlane( const AABB& aabb, const Plane3& plane, const Matrix4& rotation = g_matrix4_identity ){ + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); - for ( std::size_t i = 0; i < 6; ++i ){ - if( plane3_equal( plane, planes[i] ) || plane3_equal( plane, plane3_flipped( planes[i] ) ) ){ - m_selectables[i].setSelected( true ); - return; + for ( std::size_t i = 0; i < 6; ++i ){ + if( plane3_equal( plane, planes[i] ) || plane3_equal( plane, plane3_flipped( planes[i] ) ) ){ + m_selectables[i].setSelected( true ); + return; + } } } -} -void gatherPolygonsByPlane( const AABB& aabb, const Plane3& plane, std::vector>& polygons, const Matrix4& rotation = g_matrix4_identity ) const { - Vector3 corners[8]; - aabb_corners_oriented( aabb, rotation, corners ); + void gatherPolygonsByPlane( const AABB& aabb, const Plane3& plane, std::vector>& polygons, const Matrix4& rotation = g_matrix4_identity ) const { + Vector3 corners[8]; + aabb_corners_oriented( aabb, rotation, corners ); - Plane3 planes[6]; - aabb_planes_oriented( aabb, rotation, planes ); + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); - const std::size_t indices[24] = { - 2, 1, 5, 6, //+x //right - 3, 7, 4, 0, //-x //left - 1, 0, 4, 5, //+y //front - 3, 2, 6, 7, //-y //back - 0, 1, 2, 3, //+z //top - 7, 6, 5, 4, //-z //bottom - }; + const std::size_t indices[24] = { + 2, 1, 5, 6, //+x //right + 3, 7, 4, 0, //-x //left + 1, 0, 4, 5, //+y //front + 3, 2, 6, 7, //-y //back + 0, 1, 2, 3, //+z //top + 7, 6, 5, 4, //-z //bottom + }; - for ( std::size_t i = 0; i < 6; ++i ){ - if( plane3_equal( plane, planes[i] ) || plane3_equal( plane, plane3_flipped( planes[i] ) ) ){ - const std::size_t index = i * 4; - polygons.emplace_back( std::initializer_list( { corners[indices[index]], - corners[indices[index + 1]], - corners[indices[index + 2]], - corners[indices[index + 3]] } ) ); - return; + for ( std::size_t i = 0; i < 6; ++i ){ + if( plane3_equal( plane, planes[i] ) || plane3_equal( plane, plane3_flipped( planes[i] ) ) ){ + const std::size_t index = i * 4; + polygons.emplace_back( std::initializer_list( { corners[indices[index]], + corners[indices[index + 1]], + corners[indices[index + 2]], + corners[indices[index + 3]] } ) ); + return; + } } + } -} - -AABB evaluateResize( const Vector3& translation ) const { - Vector3 min = m_bounds.origin - m_bounds.extents; - Vector3 max = m_bounds.origin + m_bounds.extents; - for ( std::size_t i = 0; i < 3; ++i ) - if ( m_bounds.extents[i] != 0 ){ - if ( m_selectables[i * 2].isSelected() ) - max[i] += translation[i]; - if ( m_selectables[i * 2 + 1].isSelected() ) - min[i] += translation[i]; - } - return AABB( vector3_mid( min, max ), vector3_scaled( vector3_subtracted( max, min ), 0.5 ) ); -} -AABB evaluateResize( const Vector3& translation, const Matrix4& rotation ) const { - AABB aabb( evaluateResize( translation_to_local( translation, rotation ) ) ); - aabb.origin = m_bounds.origin + translation_from_local( aabb.origin - m_bounds.origin, rotation ); - return aabb; -} -Matrix4 evaluateTransform( const Vector3& translation ) const { - AABB aabb( evaluateResize( translation ) ); - Vector3 scale( - m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, - m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, - m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 + AABB evaluateResize( const Vector3& translation ) const { + Vector3 min = m_bounds.origin - m_bounds.extents; + Vector3 max = m_bounds.origin + m_bounds.extents; + for ( std::size_t i = 0; i < 3; ++i ) + if ( m_bounds.extents[i] != 0 ){ + if ( m_selectables[i * 2].isSelected() ) + max[i] += translation[i]; + if ( m_selectables[i * 2 + 1].isSelected() ) + min[i] += translation[i]; + } + return AABB( vector3_mid( min, max ), vector3_scaled( vector3_subtracted( max, min ), 0.5 ) ); + } + AABB evaluateResize( const Vector3& translation, const Matrix4& rotation ) const { + AABB aabb( evaluateResize( translation_to_local( translation, rotation ) ) ); + aabb.origin = m_bounds.origin + translation_from_local( aabb.origin - m_bounds.origin, rotation ); + return aabb; + } + Matrix4 evaluateTransform( const Vector3& translation ) const { + AABB aabb( evaluateResize( translation ) ); + Vector3 scale( + m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, + m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, + m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 ); - Matrix4 matrix( matrix4_translation_for_vec3( aabb.origin - m_bounds.origin ) ); - matrix4_pivoted_scale_by_vec3( matrix, scale, m_bounds.origin ); + Matrix4 matrix( matrix4_translation_for_vec3( aabb.origin - m_bounds.origin ) ); + matrix4_pivoted_scale_by_vec3( matrix, scale, m_bounds.origin ); - return matrix; -} + return matrix; + } }; diff --git a/libs/eclasslib.h b/libs/eclasslib.h index 4b1612b1..c143f476 100644 --- a/libs/eclasslib.h +++ b/libs/eclasslib.h @@ -38,48 +38,48 @@ typedef Vector3 Colour3; class ListAttributeType { -typedef std::pair ListItem; -typedef std::vector ListItems; -ListItems m_items; + typedef std::pair ListItem; + typedef std::vector ListItems; + ListItems m_items; public: -typedef ListItems::const_iterator const_iterator; -const_iterator begin() const { - return m_items.begin(); -} -const_iterator end() const { - return m_items.end(); -} - -const ListItem& operator[]( std::size_t i ) const { - return m_items[i]; -} -const_iterator findValue( const char* value ) const { - for ( ListItems::const_iterator i = m_items.begin(); i != m_items.end(); ++i ) - { - if ( string_equal( value, ( *i ).second.c_str() ) ) { - return i; - } + typedef ListItems::const_iterator const_iterator; + const_iterator begin() const { + return m_items.begin(); + } + const_iterator end() const { + return m_items.end(); } - return m_items.end(); -} -void push_back( const char* name, const char* value ){ - m_items.push_back( ListItems::value_type( name, value ) ); -} + const ListItem& operator[]( std::size_t i ) const { + return m_items[i]; + } + const_iterator findValue( const char* value ) const { + for ( ListItems::const_iterator i = m_items.begin(); i != m_items.end(); ++i ) + { + if ( string_equal( value, ( *i ).second.c_str() ) ) { + return i; + } + } + return m_items.end(); + } + + void push_back( const char* name, const char* value ){ + m_items.push_back( ListItems::value_type( name, value ) ); + } }; class EntityClassAttribute { public: -CopiedString m_type; -CopiedString m_name; -CopiedString m_value; -CopiedString m_description; -EntityClassAttribute(){ -} -EntityClassAttribute( const char* type, const char* name, const char* value = "", const char* description = "" ) : m_type( type ), m_name( name ), m_value( value ), m_description( description ){ -} + CopiedString m_type; + CopiedString m_name; + CopiedString m_value; + CopiedString m_description; + EntityClassAttribute(){ + } + EntityClassAttribute( const char* type, const char* name, const char* value = "", const char* description = "" ) : m_type( type ), m_name( name ), m_value( value ), m_description( description ){ + } }; typedef std::pair EntityClassAttributePair; @@ -107,57 +107,57 @@ inline bool classname_equal( const char* classname, const char* other ){ class EntityClass { private: -CopiedString m_name; + CopiedString m_name; public: -StringList m_parent; -bool fixedsize; -bool unknown; // wasn't found in source -bool miscmodel_is; // also definable via model attribute presence in xml .ent definition -CopiedString m_miscmodel_key; -bool has_angles; // definable via "angle"/"angles"/"direction" attribute presence in xml .ent definition, only affects rendering of group entities angles arrow now -Vector3 mins; -Vector3 maxs; + StringList m_parent; + bool fixedsize; + bool unknown; // wasn't found in source + bool miscmodel_is; // also definable via model attribute presence in xml .ent definition + CopiedString m_miscmodel_key; + bool has_angles; // definable via "angle"/"angles"/"direction" attribute presence in xml .ent definition, only affects rendering of group entities angles arrow now + Vector3 mins; + Vector3 maxs; -Colour3 color; -Shader* m_state_fill; -Shader* m_state_wire; -Shader* m_state_blend; + Colour3 color; + Shader* m_state_fill; + Shader* m_state_wire; + Shader* m_state_blend; -CopiedString m_comments; -char flagnames[MAX_FLAGS][32]; -const EntityClassAttribute* flagAttributes[MAX_FLAGS]; + CopiedString m_comments; + char flagnames[MAX_FLAGS][32]; + const EntityClassAttribute* flagAttributes[MAX_FLAGS]; -CopiedString m_modelpath; -CopiedString m_skin; + CopiedString m_modelpath; + CopiedString m_skin; -void ( *free )( EntityClass* ); + void ( *free )( EntityClass* ); -EntityClassAttributes m_attributes; + EntityClassAttributes m_attributes; -bool inheritanceResolved; -bool sizeSpecified; -bool colorSpecified; + bool inheritanceResolved; + bool sizeSpecified; + bool colorSpecified; -void name_set( const char* name_ ) { - m_name = name_; - miscmodel_is = ( string_equal_prefix_nocase( name(), "misc_" ) && string_equal_suffix_nocase( name(), "model" ) ) // misc_*model (also misc_model) - || classname_equal( name(), "model_static" ); -} -const char* name() const { - return m_name.c_str(); -} -const char* comments() const { - return m_comments.c_str(); -} -const char* modelpath() const { - return m_modelpath.c_str(); -} -const char* skin() const { - return m_skin.c_str(); -} -const char* miscmodel_key() const { - return m_miscmodel_key.c_str(); -} + void name_set( const char* name_ ) { + m_name = name_; + miscmodel_is = ( string_equal_prefix_nocase( name(), "misc_" ) && string_equal_suffix_nocase( name(), "model" ) ) // misc_*model (also misc_model) + || classname_equal( name(), "model_static" ); + } + const char* name() const { + return m_name.c_str(); + } + const char* comments() const { + return m_comments.c_str(); + } + const char* modelpath() const { + return m_modelpath.c_str(); + } + const char* skin() const { + return m_skin.c_str(); + } + const char* miscmodel_key() const { + return m_miscmodel_key.c_str(); + } }; inline const char* EntityClass_valueForKey( const EntityClass& entityClass, const char* key ){ diff --git a/libs/entitylib.h b/libs/entitylib.h index 1dffe27e..b0d42099 100644 --- a/libs/entitylib.h +++ b/libs/entitylib.h @@ -85,18 +85,18 @@ inline void arrow_draw( const Vector3& origin, const Vector3& direction_forward, class RenderableArrow : public OpenGLRenderable { -const Vector3& m_origin; -const Vector3& m_angles; + const Vector3& m_origin; + const Vector3& m_angles; public: -RenderableArrow( const Vector3& origin, const Vector3& angles ) - : m_origin( origin ), m_angles( angles ){ -} + RenderableArrow( const Vector3& origin, const Vector3& angles ) + : m_origin( origin ), m_angles( angles ){ + } -void render( RenderStateFlags state ) const { - Matrix4 mat = matrix4_rotation_for_euler_xyz_degrees( m_angles ); - arrow_draw( m_origin, matrix4_transformed_direction( mat, Vector3( 1, 0, 0 ) ), matrix4_transformed_direction( mat, Vector3( 0, 1, 0 ) ), matrix4_transformed_direction( mat, Vector3( 0, 0, 1 ) ) ); -} + void render( RenderStateFlags state ) const { + Matrix4 mat = matrix4_rotation_for_euler_xyz_degrees( m_angles ); + arrow_draw( m_origin, matrix4_transformed_direction( mat, Vector3( 1, 0, 0 ) ), matrix4_transformed_direction( mat, Vector3( 0, 1, 0 ) ), matrix4_transformed_direction( mat, Vector3( 0, 0, 1 ) ) ); + } }; @@ -283,24 +283,24 @@ inline void aabb_draw( const AABB& aabb, RenderStateFlags state ){ class RenderableSolidAABB : public OpenGLRenderable { -const AABB& m_aabb; + const AABB& m_aabb; public: -RenderableSolidAABB( const AABB& aabb ) : m_aabb( aabb ){ -} -void render( RenderStateFlags state ) const { - aabb_draw_solid( m_aabb, state ); -} + RenderableSolidAABB( const AABB& aabb ) : m_aabb( aabb ){ + } + void render( RenderStateFlags state ) const { + aabb_draw_solid( m_aabb, state ); + } }; class RenderableWireframeAABB : public OpenGLRenderable { -const AABB& m_aabb; + const AABB& m_aabb; public: -RenderableWireframeAABB( const AABB& aabb ) : m_aabb( aabb ){ -} -void render( RenderStateFlags state ) const { - aabb_draw_wire( m_aabb ); -} + RenderableWireframeAABB( const AABB& aabb ) : m_aabb( aabb ){ + } + void render( RenderStateFlags state ) const { + aabb_draw_wire( m_aabb ); + } }; @@ -310,80 +310,80 @@ void render( RenderStateFlags state ) const { /// - Provides undo support through the global undo system. class KeyValue final : public EntityKeyValue { -typedef UnsortedSet KeyObservers; + typedef UnsortedSet KeyObservers; -std::size_t m_refcount; -KeyObservers m_observers; -CopiedString m_string; -const char* m_empty; -ObservedUndoableObject m_undo; -static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; + std::size_t m_refcount; + KeyObservers m_observers; + CopiedString m_string; + const char* m_empty; + ObservedUndoableObject m_undo; + static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; public: -KeyValue( const char* string, const char* empty ) - : m_refcount( 0 ), m_string( string ), m_empty( empty ), m_undo( m_string, UndoImportCaller( *this ) ){ - notify(); -} -~KeyValue(){ - ASSERT_MESSAGE( m_observers.empty(), "KeyValue::~KeyValue: observers still attached" ); -} - -static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ - m_entityKeyValueChanged = func; -} - -void IncRef(){ - ++m_refcount; -} -void DecRef(){ - if ( --m_refcount == 0 ) { - delete this; - } -} - -void instanceAttach( MapFile* map ){ - m_undo.instanceAttach( map ); -} -void instanceDetach( MapFile* map ){ - m_undo.instanceDetach( map ); -} - -void attach( const KeyObserver& observer ){ - ( *m_observers.insert ( observer ) )( c_str() ); -} -void detach( const KeyObserver& observer ){ - observer( m_empty ); - m_observers.erase( observer ); -} -const char* c_str() const { - if ( string_empty( m_string.c_str() ) ) { - return m_empty; - } - return m_string.c_str(); -} -void assign( const char* other ){ - if ( !string_equal( m_string.c_str(), other ) ) { - m_undo.save(); - m_string = other; + KeyValue( const char* string, const char* empty ) + : m_refcount( 0 ), m_string( string ), m_empty( empty ), m_undo( m_string, UndoImportCaller( *this ) ){ notify(); } -} - -void notify(){ - m_entityKeyValueChanged(); - KeyObservers::reverse_iterator i = m_observers.rbegin(); - while ( i != m_observers.rend() ) - { - ( *i++ )( c_str() ); + ~KeyValue(){ + ASSERT_MESSAGE( m_observers.empty(), "KeyValue::~KeyValue: observers still attached" ); } -} -void importState( const CopiedString& string ){ - m_string = string; + static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ + m_entityKeyValueChanged = func; + } - notify(); -} -typedef MemberCaller1 UndoImportCaller; + void IncRef(){ + ++m_refcount; + } + void DecRef(){ + if ( --m_refcount == 0 ) { + delete this; + } + } + + void instanceAttach( MapFile* map ){ + m_undo.instanceAttach( map ); + } + void instanceDetach( MapFile* map ){ + m_undo.instanceDetach( map ); + } + + void attach( const KeyObserver& observer ){ + ( *m_observers.insert ( observer ) )( c_str() ); + } + void detach( const KeyObserver& observer ){ + observer( m_empty ); + m_observers.erase( observer ); + } + const char* c_str() const { + if ( string_empty( m_string.c_str() ) ) { + return m_empty; + } + return m_string.c_str(); + } + void assign( const char* other ){ + if ( !string_equal( m_string.c_str(), other ) ) { + m_undo.save(); + m_string = other; + notify(); + } + } + + void notify(){ + m_entityKeyValueChanged(); + KeyObservers::reverse_iterator i = m_observers.rbegin(); + while ( i != m_observers.rend() ) + { + ( *i++ )( c_str() ); + } + } + + void importState( const CopiedString& string ){ + m_string = string; + + notify(); + } + typedef MemberCaller1 UndoImportCaller; }; /// \brief An unsorted list of key/value pairs. @@ -514,7 +514,7 @@ public: ~EntityKeyValues(){ for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ) { - // post-increment to allow current element to be removed safely + // post-increment to allow current element to be removed safely ( *i++ )->clear(); } ASSERT_MESSAGE( m_observers.empty(), "EntityKeyValues::~EntityKeyValues: observers still attached" ); @@ -592,7 +592,7 @@ public: m_instanced = false; } - // entity + // entity EntityClass& getEntityClass() const { return *m_eclass; } @@ -604,7 +604,7 @@ public: } void setKeyValue( const char* key, const char* value ){ if ( value[0] == '\0' - /*|| string_equal(EntityClass_valueForKey(*m_eclass, key), value)*/ ) { // don't delete values equal to default + /*|| string_equal(EntityClass_valueForKey(*m_eclass, key), value)*/ ) { // don't delete values equal to default erase( key ); } else @@ -685,19 +685,19 @@ public: namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - inline void swap( ResourceReference& self, ResourceReference& other ){ - self.swap( other ); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap. +inline void swap( ResourceReference& self, ResourceReference& other ){ + self.swap( other ); +} } /// this is only correct for radiant 2d views matrices inline bool aabb_fits_view( const AABB& aabb, const Matrix4& modelview, const Matrix4& viewport, int ratio ){ const AABB transformed_bounds = aabb_for_oriented_aabb( - AABB( aabb.origin, Vector3( std::max( aabb.extents[0], 8.f ), std::max( aabb.extents[1], 8.f ), std::max( aabb.extents[2], 8.f ) ) ), - modelview - ); + AABB( aabb.origin, Vector3( std::max( aabb.extents[0], 8.f ), std::max( aabb.extents[1], 8.f ), std::max( aabb.extents[2], 8.f ) ) ), + modelview + ); //return ( aabb.extents[0] / viewport[0] ) > 0.25f || ( aabb.extents[1] / viewport[5] ) > 0.25f; return ( viewport[0] + viewport[5] ) / ( transformed_bounds.extents[0] + transformed_bounds.extents[1] ) < ratio; diff --git a/libs/entityxml.h b/libs/entityxml.h index 89a9406f..923f6eaa 100644 --- a/libs/entityxml.h +++ b/libs/entityxml.h @@ -28,50 +28,50 @@ class entity_import : public XMLImporter { -Entity& m_entity; + Entity& m_entity; public: -entity_import( Entity& entity ) - : m_entity( entity ){ -} -void pushElement( const XMLElement& element ){ - if ( strcmp( element.name(), "epair" ) == 0 ) { - m_entity.setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); + entity_import( Entity& entity ) + : m_entity( entity ){ + } + void pushElement( const XMLElement& element ){ + if ( strcmp( element.name(), "epair" ) == 0 ) { + m_entity.setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); + } + } + void popElement( const char* name ){ + } + std::size_t write( const char* data, std::size_t length ){ + return length; } -} -void popElement( const char* name ){ -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} }; class entity_export : public XMLExporter { -class ExportXMLVisitor : public Entity::Visitor -{ -XMLImporter& m_importer; -public: -ExportXMLVisitor( XMLImporter& importer ) : m_importer( importer ){ -} -void visit( const char* key, const char* value ){ - StaticElement element( "epair" ); - element.insertAttribute( "key", key ); - element.insertAttribute( "value", value ); - m_importer.pushElement( element ); - m_importer.popElement( element.name() ); -} -}; + class ExportXMLVisitor : public Entity::Visitor + { + XMLImporter& m_importer; + public: + ExportXMLVisitor( XMLImporter& importer ) : m_importer( importer ){ + } + void visit( const char* key, const char* value ){ + StaticElement element( "epair" ); + element.insertAttribute( "key", key ); + element.insertAttribute( "value", value ); + m_importer.pushElement( element ); + m_importer.popElement( element.name() ); + } + }; -const Entity& m_entity; + const Entity& m_entity; public: -entity_export( const Entity& entity ) : m_entity( entity ){ -} -void exportXML( XMLImporter& observer ){ - ExportXMLVisitor visitor( observer ); + entity_export( const Entity& entity ) : m_entity( entity ){ + } + void exportXML( XMLImporter& observer ){ + ExportXMLVisitor visitor( observer ); - m_entity.forEachKeyValue( visitor ); -} + m_entity.forEachKeyValue( visitor ); + } }; inline void entity_copy( Entity& entity, const Entity& other ){ @@ -84,13 +84,13 @@ template class EntityConstruction { public: -typedef EntityClass* type; -static type get( const EntityType& entity ){ - return &entity.getEntity().getEntityClass(); -} -static void copy( EntityType& entity, const EntityType& other ){ - entity_copy( entity.getEntity(), other.getEntity() ); -} + typedef EntityClass* type; + static type get( const EntityType& entity ){ + return &entity.getEntity().getEntityClass(); + } + static void copy( EntityType& entity, const EntityType& other ){ + entity_copy( entity.getEntity(), other.getEntity() ); + } }; diff --git a/libs/fs_filesystem.h b/libs/fs_filesystem.h index 5cd42a63..d80a42f1 100644 --- a/libs/fs_filesystem.h +++ b/libs/fs_filesystem.h @@ -46,115 +46,115 @@ inline unsigned int path_get_depth( const char* path ){ template class GenericFileSystem { -class Path -{ -CopiedString m_path; -unsigned int m_depth; -public: -Path( const char* path ) - : m_path( path ), m_depth( path_get_depth( c_str() ) ){ -} -Path( StringRange range ) - : m_path( range ), m_depth( path_get_depth( c_str() ) ){ -} -bool operator<( const Path& other ) const { - return string_less_nocase( c_str(), other.c_str() ); -} -unsigned int depth() const { - return m_depth; -} -const char* c_str() const { - return m_path.c_str(); -} -}; + class Path + { + CopiedString m_path; + unsigned int m_depth; + public: + Path( const char* path ) + : m_path( path ), m_depth( path_get_depth( c_str() ) ){ + } + Path( StringRange range ) + : m_path( range ), m_depth( path_get_depth( c_str() ) ){ + } + bool operator<( const Path& other ) const { + return string_less_nocase( c_str(), other.c_str() ); + } + unsigned int depth() const { + return m_depth; + } + const char* c_str() const { + return m_path.c_str(); + } + }; -class Entry -{ -file_type* m_file; -public: -Entry() : m_file( 0 ){ -} -Entry( file_type* file ) : m_file( file ){ -} -file_type* file() const { - return m_file; -} -bool is_directory() const { - return file() == 0; -} -}; + class Entry + { + file_type* m_file; + public: + Entry() : m_file( 0 ){ + } + Entry( file_type* file ) : m_file( file ){ + } + file_type* file() const { + return m_file; + } + bool is_directory() const { + return file() == 0; + } + }; -typedef std::map Entries; -Entries m_entries; + typedef std::map Entries; + Entries m_entries; public: -typedef typename Entries::iterator iterator; -typedef typename Entries::value_type value_type; -typedef Entry entry_type; + typedef typename Entries::iterator iterator; + typedef typename Entries::value_type value_type; + typedef Entry entry_type; -iterator begin(){ - return m_entries.begin(); -} -iterator end(){ - return m_entries.end(); -} + iterator begin(){ + return m_entries.begin(); + } + iterator end(){ + return m_entries.end(); + } /// \brief Returns the file at \p path. /// Creates all directories below \p path if they do not exist. /// O(log n) on average. -entry_type& operator[]( const Path& path ){ - { - const char* end = path_remove_directory( path.c_str() ); - while ( end[0] != '\0' ) + entry_type& operator[]( const Path& path ){ { - Path dir( StringRange( path.c_str(), end ) ); - m_entries.insert( value_type( dir, Entry( 0 ) ) ); - end = path_remove_directory( end ); + const char* end = path_remove_directory( path.c_str() ); + while ( end[0] != '\0' ) + { + Path dir( StringRange( path.c_str(), end ) ); + m_entries.insert( value_type( dir, Entry( 0 ) ) ); + end = path_remove_directory( end ); + } } - } - return m_entries[path]; -} + return m_entries[path]; + } /// \brief Returns the file at \p path or end() if not found. -iterator find( const Path& path ){ - return m_entries.find( path ); -} + iterator find( const Path& path ){ + return m_entries.find( path ); + } -iterator begin( const char* root ){ - if ( root[0] == '\0' ) { - return m_entries.begin(); + iterator begin( const char* root ){ + if ( root[0] == '\0' ) { + return m_entries.begin(); + } + iterator i = m_entries.find( root ); + if ( i == m_entries.end() ) { + return i; + } + return ++i; } - iterator i = m_entries.find( root ); - if ( i == m_entries.end() ) { - return i; - } - return ++i; -} /// \brief Performs a depth-first traversal of the file-system subtree rooted at \p root. /// Traverses the entire tree if \p root is "". /// Calls \p visitor.file() with the path to each file relative to the filesystem root. /// Calls \p visitor.directory() with the path to each directory relative to the filesystem root. -template -void traverse( visitor_type visitor, const char* root ){ - unsigned int start_depth = path_get_depth( root ); - unsigned int skip_depth = 0; - for ( iterator i = begin( root ); i != end() && i->first.depth() > start_depth; ++i ) - { - if ( i->first.depth() == skip_depth ) { - skip_depth = 0; - } - if ( skip_depth == 0 ) { - if ( !i->second.is_directory() ) { - visitor.file( i->first.c_str() ); + template + void traverse( visitor_type visitor, const char* root ){ + unsigned int start_depth = path_get_depth( root ); + unsigned int skip_depth = 0; + for ( iterator i = begin( root ); i != end() && i->first.depth() > start_depth; ++i ) + { + if ( i->first.depth() == skip_depth ) { + skip_depth = 0; } - else if ( visitor.directory( i->first.c_str(), i->first.depth() - start_depth ) ) { - skip_depth = i->first.depth(); + if ( skip_depth == 0 ) { + if ( !i->second.is_directory() ) { + visitor.file( i->first.c_str() ); + } + else if ( visitor.directory( i->first.c_str(), i->first.depth() - start_depth ) ) { + skip_depth = i->first.depth(); + } } } } -} }; #endif diff --git a/libs/fs_path.h b/libs/fs_path.h index 2baf297e..23e1aaef 100644 --- a/libs/fs_path.h +++ b/libs/fs_path.h @@ -30,53 +30,53 @@ /// - Provides a limited STL-style interface to push and pop file or directory names at the end of the path. class UnixPath { -StringBuffer m_string; + StringBuffer m_string; -void check_separator(){ - if ( !empty() && m_string.back() != '/' ) { - m_string.push_back( '/' ); + void check_separator(){ + if ( !empty() && m_string.back() != '/' ) { + m_string.push_back( '/' ); + } } -} public: /// \brief Constructs with the directory \p root. -UnixPath( const char* root ) - : m_string( root ){ - check_separator(); -} + UnixPath( const char* root ) + : m_string( root ){ + check_separator(); + } -bool empty() const { - return m_string.empty(); -} + bool empty() const { + return m_string.empty(); + } -const char* c_str() const { - return m_string.c_str(); -} + const char* c_str() const { + return m_string.c_str(); + } /// \brief Appends the directory \p name. -void push( const char* name ){ - m_string.push_string( name ); - check_separator(); -} + void push( const char* name ){ + m_string.push_string( name ); + check_separator(); + } /// \brief Appends the directory [\p first, \p last). -void push( const char* first, const char* last ){ - m_string.push_range( first, last ); - check_separator(); -} + void push( const char* first, const char* last ){ + m_string.push_range( first, last ); + check_separator(); + } /// \brief Appends the filename \p name. -void push_filename( const char* name ){ - m_string.push_string( name ); -} + void push_filename( const char* name ){ + m_string.push_string( name ); + } /// \brief Removes the last directory or filename appended. -void pop(){ - if ( m_string.back() == '/' ) { - m_string.pop_back(); + void pop(){ + if ( m_string.back() == '/' ) { + m_string.pop_back(); + } + while ( !empty() && m_string.back() != '/' ) + { + m_string.pop_back(); + } } - while ( !empty() && m_string.back() != '/' ) - { - m_string.pop_back(); - } -} }; #endif diff --git a/libs/generic/bitfield.h b/libs/generic/bitfield.h index f9427aac..e713d44b 100644 --- a/libs/generic/bitfield.h +++ b/libs/generic/bitfield.h @@ -35,26 +35,26 @@ template class BitFieldValue : public Enumeration { -unsigned m_value; + unsigned m_value; protected: -explicit BitFieldValue( unsigned value ) : m_value( value ){ -} + explicit BitFieldValue( unsigned value ) : m_value( value ){ + } public: -BitFieldValue() : m_value( 0 ){ -} -explicit BitFieldValue( typename Enumeration::Value value ) : m_value( 1 << value ){ -} -unsigned get() const { - return m_value; -} + BitFieldValue() : m_value( 0 ){ + } + explicit BitFieldValue( typename Enumeration::Value value ) : m_value( 1 << value ){ + } + unsigned get() const { + return m_value; + } }; template class BitFieldValueUnsafe : public BitFieldValue { public: -explicit BitFieldValueUnsafe( unsigned value ) : BitFieldValue( value ){ -} + explicit BitFieldValueUnsafe( unsigned value ) : BitFieldValue( value ){ + } }; template diff --git a/libs/generic/callback.cpp b/libs/generic/callback.cpp index db04d53e..b612050c 100644 --- a/libs/generic/callback.cpp +++ b/libs/generic/callback.cpp @@ -29,17 +29,17 @@ namespace ExampleMemberCaller class Integer { public: -int value; + int value; -void printValue() const { - // print this->value here; -} + void printValue() const { + // print this->value here; + } -void setValue(){ - value = 3; -} + void setValue(){ + value = 3; + } // a typedef to make things more readable -typedef MemberCaller SetValueCaller; + typedef MemberCaller SetValueCaller; }; void example(){ @@ -120,34 +120,34 @@ class A4 class Test { public: -void test0(){ -} -typedef Member Test0; -typedef MemberCaller Test0Caller; -void test0const() const { -} -typedef ConstMember Test0Const; -typedef ConstMemberCaller Test0ConstCaller; -void test1( A1 ){ -} -typedef Member1 Test1; -typedef MemberCaller1 Test1Caller; -void test1const( A1 ) const { -} -typedef ConstMember1 Test1Const; -typedef ConstMemberCaller1 Test1ConstCaller; -void test2( A1, A2 ){ -} -typedef Member2 Test2; -void test2const( A1, A2 ) const { -} -typedef ConstMember2 Test2Const; -void test3( A1, A2, A3 ){ -} -typedef Member3 Test3; -void test3const( A1, A2, A3 ) const { -} -typedef ConstMember3 Test3Const; + void test0(){ + } + typedef Member Test0; + typedef MemberCaller Test0Caller; + void test0const() const { + } + typedef ConstMember Test0Const; + typedef ConstMemberCaller Test0ConstCaller; + void test1( A1 ){ + } + typedef Member1 Test1; + typedef MemberCaller1 Test1Caller; + void test1const( A1 ) const { + } + typedef ConstMember1 Test1Const; + typedef ConstMemberCaller1 Test1ConstCaller; + void test2( A1, A2 ){ + } + typedef Member2 Test2; + void test2const( A1, A2 ) const { + } + typedef ConstMember2 Test2Const; + void test3( A1, A2, A3 ){ + } + typedef Member3 Test3; + void test3const( A1, A2, A3 ) const { + } + typedef ConstMember3 Test3Const; }; void test0free(){ diff --git a/libs/generic/callback.h b/libs/generic/callback.h index a22a3ffd..f5a8e717 100644 --- a/libs/generic/callback.h +++ b/libs/generic/callback.h @@ -56,18 +56,18 @@ template class ConvertFromOpaque { public: -static Type& apply( void* p ){ - return *static_cast( p ); -} + static Type& apply( void* p ){ + return *static_cast( p ); + } }; template class ConvertFromOpaque { public: -static const Type& apply( void* p ){ - return *static_cast( p ); -} + static const Type& apply( void* p ){ + return *static_cast( p ); + } }; @@ -75,160 +75,160 @@ template class ConvertFromOpaque { public: -static Type* apply( void* p ){ - return static_cast( p ); -} + static Type* apply( void* p ){ + return static_cast( p ); + } }; template class ConvertFromOpaque { public: -static const Type* apply( void* p ){ - return static_cast( p ); -} + static const Type* apply( void* p ){ + return static_cast( p ); + } }; template class BindFirstOpaque { -typedef typename Caller::first_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::result_type result_type; -explicit BindFirstOpaque( FirstBound firstBound ) : firstBound( firstBound ){ -} -result_type operator()() const { - return Caller::call( firstBound ); -} -FirstBound getBound() const { - return firstBound; -} -static result_type thunk( void* environment ){ - return Caller::call( ConvertFromOpaque::apply( environment ) ); -} -void* getEnvironment() const { - return convertToOpaque( firstBound ); -} + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque( FirstBound firstBound ) : firstBound( firstBound ){ + } + result_type operator()() const { + return Caller::call( firstBound ); + } + FirstBound getBound() const { + return firstBound; + } + static result_type thunk( void* environment ){ + return Caller::call( ConvertFromOpaque::apply( environment ) ); + } + void* getEnvironment() const { + return convertToOpaque( firstBound ); + } }; template class BindFirstOpaque1 { -typedef typename Caller::first_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::second_argument_type first_argument_type; -typedef typename Caller::result_type result_type; -explicit BindFirstOpaque1( FirstBound firstBound ) : firstBound( firstBound ){ -} -result_type operator()( first_argument_type a1 ) const { - return Caller::call( firstBound, a1 ); -} -FirstBound getBound() const { - return firstBound; -} -static result_type thunk( void* environment, first_argument_type a1 ){ - return Caller::call( ConvertFromOpaque::apply( environment ), a1 ); -} -void* getEnvironment() const { - return convertToOpaque( firstBound ); -} + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque1( FirstBound firstBound ) : firstBound( firstBound ){ + } + result_type operator()( first_argument_type a1 ) const { + return Caller::call( firstBound, a1 ); + } + FirstBound getBound() const { + return firstBound; + } + static result_type thunk( void* environment, first_argument_type a1 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1 ); + } + void* getEnvironment() const { + return convertToOpaque( firstBound ); + } }; template class BindFirstOpaque2 { -typedef typename Caller::first_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::second_argument_type first_argument_type; -typedef typename Caller::third_argument_type second_argument_type; -typedef typename Caller::result_type result_type; -explicit BindFirstOpaque2( FirstBound firstBound ) : firstBound( firstBound ){ -} -result_type operator()( first_argument_type a1, second_argument_type a2 ) const { - return Caller::call( firstBound, a1, a2 ); -} -FirstBound getBound() const { - return firstBound; -} -static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2 ){ - return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2 ); -} -void* getEnvironment() const { - return convertToOpaque( firstBound ); -} + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::third_argument_type second_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque2( FirstBound firstBound ) : firstBound( firstBound ){ + } + result_type operator()( first_argument_type a1, second_argument_type a2 ) const { + return Caller::call( firstBound, a1, a2 ); + } + FirstBound getBound() const { + return firstBound; + } + static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2 ); + } + void* getEnvironment() const { + return convertToOpaque( firstBound ); + } }; template class BindFirstOpaque3 { -typedef typename Caller::first_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::second_argument_type first_argument_type; -typedef typename Caller::third_argument_type second_argument_type; -typedef typename Caller::fourth_argument_type third_argument_type; -typedef typename Caller::result_type result_type; -explicit BindFirstOpaque3( FirstBound firstBound ) : firstBound( firstBound ){ -} -result_type operator()( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) const { - return Caller::call( firstBound, a1, a2, a3 ); -} -FirstBound getBound() const { - return firstBound; -} -static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ - return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2, a3 ); -} -void* getEnvironment() const { - return convertToOpaque( firstBound ); -} + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::third_argument_type second_argument_type; + typedef typename Caller::fourth_argument_type third_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque3( FirstBound firstBound ) : firstBound( firstBound ){ + } + result_type operator()( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) const { + return Caller::call( firstBound, a1, a2, a3 ); + } + FirstBound getBound() const { + return firstBound; + } + static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2, a3 ); + } + void* getEnvironment() const { + return convertToOpaque( firstBound ); + } }; template class BindFirstOpaque4 { -typedef typename Caller::first_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::second_argument_type first_argument_type; -typedef typename Caller::third_argument_type second_argument_type; -typedef typename Caller::fourth_argument_type third_argument_type; -typedef typename Caller::fifth_argument_type fourth_argument_type; -typedef typename Caller::result_type result_type; -explicit BindFirstOpaque4( FirstBound firstBound ) : firstBound( firstBound ){ -} -result_type operator()( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ) const { - return Caller::call( firstBound, a1, a2, a3, a4 ); -} -FirstBound getBound() const { - return firstBound; -} -static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2, a3, a4 ); -} -void* getEnvironment() const { - return convertToOpaque( firstBound ); -} + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::third_argument_type second_argument_type; + typedef typename Caller::fourth_argument_type third_argument_type; + typedef typename Caller::fifth_argument_type fourth_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque4( FirstBound firstBound ) : firstBound( firstBound ){ + } + result_type operator()( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ) const { + return Caller::call( firstBound, a1, a2, a3, a4 ); + } + FirstBound getBound() const { + return firstBound; + } + static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2, a3, a4 ); + } + void* getEnvironment() const { + return convertToOpaque( firstBound ); + } }; template class CallbackBase { -void* m_environment; -Thunk_ m_thunk; + void* m_environment; + Thunk_ m_thunk; public: -typedef Thunk_ Thunk; -CallbackBase( void* environment, Thunk function ) : m_environment( environment ), m_thunk( function ){ -} -void* getEnvironment() const { - return m_environment; -} -Thunk getThunk() const { - return m_thunk; -} + typedef Thunk_ Thunk; + CallbackBase( void* environment, Thunk function ) : m_environment( environment ), m_thunk( function ){ + } + void* getEnvironment() const { + return m_environment; + } + Thunk getThunk() const { + return m_thunk; + } }; template @@ -242,7 +242,7 @@ inline bool operator!=( const CallbackBase& self, const CallbackBase inline bool operator<( const CallbackBase& self, const CallbackBase& other ){ return self.getEnvironment() < other.getEnvironment() || - ( !( other.getEnvironment() < self.getEnvironment() ) && self.getThunk() < other.getThunk() ); + ( !( other.getEnvironment() < self.getEnvironment() ) && self.getThunk() < other.getThunk() ); } @@ -252,23 +252,23 @@ inline bool operator<( const CallbackBase& self, const CallbackBase class Callback0 : public CallbackBase { -typedef CallbackBase Base; -static Result nullThunk( void* ){ -} + typedef CallbackBase Base; + static Result nullThunk( void* ){ + } public: -typedef Result result_type; + typedef Result result_type; -Callback0() : Base( 0, nullThunk ){ -} -template -Callback0( const BindFirstOpaque& caller ) : Base( caller.getEnvironment(), BindFirstOpaque::thunk ){ -} -Callback0( void* environment, typename Base::Thunk function ) : Base( environment, function ){ -} -result_type operator()() const { - return Base::getThunk() ( Base::getEnvironment() ); -} + Callback0() : Base( 0, nullThunk ){ + } + template + Callback0( const BindFirstOpaque& caller ) : Base( caller.getEnvironment(), BindFirstOpaque::thunk ){ + } + Callback0( void* environment, typename Base::Thunk function ) : Base( environment, function ){ + } + result_type operator()() const { + return Base::getThunk() ( Base::getEnvironment() ); + } }; template @@ -290,24 +290,24 @@ typedef Callback0 Callback; template class Callback1 : public CallbackBase { -typedef CallbackBase Base; -static Result nullThunk( void*, FirstArgument ){ -} + typedef CallbackBase Base; + static Result nullThunk( void*, FirstArgument ){ + } public: -typedef FirstArgument first_argument_type; -typedef Result result_type; + typedef FirstArgument first_argument_type; + typedef Result result_type; -Callback1() : Base( 0, nullThunk ){ -} -template -Callback1( const BindFirstOpaque1& caller ) : Base( caller.getEnvironment(), BindFirstOpaque1::thunk ){ -} -Callback1( void* environment, typename Base::Thunk function ) : Base( environment, function ){ -} -result_type operator()( FirstArgument firstArgument ) const { - return Base::getThunk() ( Base::getEnvironment(), firstArgument ); -} + Callback1() : Base( 0, nullThunk ){ + } + template + Callback1( const BindFirstOpaque1& caller ) : Base( caller.getEnvironment(), BindFirstOpaque1::thunk ){ + } + Callback1( void* environment, typename Base::Thunk function ) : Base( environment, function ){ + } + result_type operator()( FirstArgument firstArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument ); + } }; template @@ -325,45 +325,45 @@ inline Callback1 class Callback2 : public CallbackBase { -typedef CallbackBase Base; -static Result nullThunk( void*, FirstArgument, SecondArgument ){ -} + typedef CallbackBase Base; + static Result nullThunk( void*, FirstArgument, SecondArgument ){ + } public: -typedef FirstArgument first_argument_type; -typedef SecondArgument second_argument_type; -typedef Result result_type; + typedef FirstArgument first_argument_type; + typedef SecondArgument second_argument_type; + typedef Result result_type; -Callback2() : Base( 0, nullThunk ){ -} -template -Callback2( const BindFirstOpaque2& caller ) : Base( caller.getEnvironment(), BindFirstOpaque2::thunk ){ -} -Callback2( void* environment, typename Base::Thunk function ) : Base( environment, function ){ -} -result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument ) const { - return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument ); -} + Callback2() : Base( 0, nullThunk ){ + } + template + Callback2( const BindFirstOpaque2& caller ) : Base( caller.getEnvironment(), BindFirstOpaque2::thunk ){ + } + Callback2( void* environment, typename Base::Thunk function ) : Base( environment, function ){ + } + result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument ); + } }; template inline Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type - > makeCallback2( const Caller& caller, typename Caller::first_argument_type callee ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type +> makeCallback2( const Caller& caller, typename Caller::first_argument_type callee ){ return Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type - >( BindFirstOpaque2( callee ) ); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type + >( BindFirstOpaque2( callee ) ); } template inline Callback2< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::result_type - > makeStatelessCallback2( const Caller& caller ){ + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::result_type +> makeStatelessCallback2( const Caller& caller ){ return makeCallback2( Caller2To3(), 0 ); } @@ -373,49 +373,49 @@ inline Callback2< template class Callback3 : public CallbackBase { -typedef CallbackBase Base; -static Result nullThunk( void*, FirstArgument, SecondArgument, ThirdArgument ){ -} + typedef CallbackBase Base; + static Result nullThunk( void*, FirstArgument, SecondArgument, ThirdArgument ){ + } public: -typedef FirstArgument first_argument_type; -typedef SecondArgument second_argument_type; -typedef ThirdArgument third_argument_type; -typedef Result result_type; + typedef FirstArgument first_argument_type; + typedef SecondArgument second_argument_type; + typedef ThirdArgument third_argument_type; + typedef Result result_type; -Callback3() : Base( 0, nullThunk ){ -} -template -Callback3( const BindFirstOpaque3& caller ) : Base( caller.getEnvironment(), BindFirstOpaque3::thunk ){ -} -Callback3( void* environment, typename Base::Thunk function ) : Base( environment, function ){ -} -result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument ) const { - return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument, thirdArgument ); -} + Callback3() : Base( 0, nullThunk ){ + } + template + Callback3( const BindFirstOpaque3& caller ) : Base( caller.getEnvironment(), BindFirstOpaque3::thunk ){ + } + Callback3( void* environment, typename Base::Thunk function ) : Base( environment, function ){ + } + result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument, thirdArgument ); + } }; template inline Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type - > makeCallback3( const Caller& caller, typename Caller::first_argument_type callee ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type +> makeCallback3( const Caller& caller, typename Caller::first_argument_type callee ){ return Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type - >( BindFirstOpaque3( callee ) ); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type + >( BindFirstOpaque3( callee ) ); } template inline Callback3< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type - > makeStatelessCallback3( const Caller& caller ){ + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type +> makeStatelessCallback3( const Caller& caller ){ return makeCallback3( Caller3To4(), 0 ); } @@ -425,53 +425,53 @@ inline Callback3< template class Callback4 : public CallbackBase { -typedef CallbackBase Base; -static Result nullThunk( void*, FirstArgument, SecondArgument, ThirdArgument, FourthArgument ){ -} + typedef CallbackBase Base; + static Result nullThunk( void*, FirstArgument, SecondArgument, ThirdArgument, FourthArgument ){ + } public: -typedef FirstArgument first_argument_type; -typedef SecondArgument second_argument_type; -typedef ThirdArgument third_argument_type; -typedef FourthArgument fourth_argument_type; -typedef Result result_type; + typedef FirstArgument first_argument_type; + typedef SecondArgument second_argument_type; + typedef ThirdArgument third_argument_type; + typedef FourthArgument fourth_argument_type; + typedef Result result_type; -Callback4() : Base( 0, nullThunk ){ -} -template -Callback4( const BindFirstOpaque4& caller ) : Base( caller.getEnvironment(), BindFirstOpaque4::thunk ){ -} -Callback4( void* environment, typename Base::Thunk function ) : Base( environment, function ){ -} -result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument, FourthArgument fourthArgument ) const { - return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument, thirdArgument, fourthArgument ); -} + Callback4() : Base( 0, nullThunk ){ + } + template + Callback4( const BindFirstOpaque4& caller ) : Base( caller.getEnvironment(), BindFirstOpaque4::thunk ){ + } + Callback4( void* environment, typename Base::Thunk function ) : Base( environment, function ){ + } + result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument, FourthArgument fourthArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument, thirdArgument, fourthArgument ); + } }; template inline Callback4< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::fifth_argument_type, - typename Caller::result_type - > makeCallback4( const Caller& caller, typename Caller::first_argument_type callee ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::fifth_argument_type, + typename Caller::result_type +> makeCallback4( const Caller& caller, typename Caller::first_argument_type callee ){ return Callback4< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::fifth_argument_type, - typename Caller::result_type - >( BindFirstOpaque4( callee ) ); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::fifth_argument_type, + typename Caller::result_type + >( BindFirstOpaque4( callee ) ); } template inline Callback4< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type - > makeStatelessCallback4( const Caller& caller ){ + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type +> makeStatelessCallback4( const Caller& caller ){ return makeCallback4( Caller4To5(), 0 ); } @@ -485,8 +485,8 @@ template class MemberCaller : public BindFirstOpaque< Member > { public: -MemberCaller( Environment& environment ) : BindFirstOpaque< Member >( environment ){ -} + MemberCaller( Environment& environment ) : BindFirstOpaque< Member >( environment ){ + } }; /// \brief Forms a Callback from a const Environment reference and a const Environment member-function. @@ -498,8 +498,8 @@ template class ConstMemberCaller : public BindFirstOpaque< ConstMember > { public: -ConstMemberCaller( const Environment& environment ) : BindFirstOpaque< ConstMember >( environment ){ -} + ConstMemberCaller( const Environment& environment ) : BindFirstOpaque< ConstMember >( environment ){ + } }; /// \brief Forms a Callback from a non-const Environment reference and a const Environment member-function which takes one argument. @@ -507,8 +507,8 @@ template > { public: -MemberCaller1( Environment& environment ) : BindFirstOpaque1< Member1 >( environment ){ -} + MemberCaller1( Environment& environment ) : BindFirstOpaque1< Member1 >( environment ){ + } }; /// \brief Forms a Callback from a const Environment reference and a const Environment member-function which takes one argument. @@ -516,8 +516,8 @@ template > { public: -ConstMemberCaller1( const Environment& environment ) : BindFirstOpaque1< ConstMember1 >( environment ){ -} + ConstMemberCaller1( const Environment& environment ) : BindFirstOpaque1< ConstMember1 >( environment ){ + } }; /// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference. @@ -529,8 +529,8 @@ template class ReferenceCaller : public BindFirstOpaque< Function1 > { public: -ReferenceCaller( Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ -} + ReferenceCaller( Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ + } }; /// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference. @@ -542,8 +542,8 @@ template class ConstReferenceCaller : public BindFirstOpaque< Function1 > { public: -ConstReferenceCaller( const Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ -} + ConstReferenceCaller( const Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ + } }; /// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference and one other argument. @@ -551,8 +551,8 @@ template > { public: -ReferenceCaller1( Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ -} + ReferenceCaller1( Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ + } }; /// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference and one other argument. @@ -560,8 +560,8 @@ template > { public: -ConstReferenceCaller1( const Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ -} + ConstReferenceCaller1( const Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ + } }; /// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer. @@ -569,8 +569,8 @@ template class PointerCaller : public BindFirstOpaque< Function1 > { public: -PointerCaller( Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ -} + PointerCaller( Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ + } }; /// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer. @@ -578,8 +578,8 @@ template class ConstPointerCaller : public BindFirstOpaque< Function1 > { public: -ConstPointerCaller( const Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ -} + ConstPointerCaller( const Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ + } }; /// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer and one other argument. @@ -587,8 +587,8 @@ template > { public: -PointerCaller1( Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ -} + PointerCaller1( Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ + } }; /// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer and one other argument. @@ -596,8 +596,8 @@ template > { public: -ConstPointerCaller1( const Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ -} + ConstPointerCaller1( const Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ + } }; /// \brief Forms a Callback from a free function which takes no arguments. @@ -605,8 +605,8 @@ template class FreeCaller : public BindFirstOpaque< Caller0To1< Function0 > > { public: -FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >( 0 ){ -} + FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >( 0 ){ + } }; /// \brief Forms a Callback from a free function which takes a single argument. @@ -614,8 +614,8 @@ template class FreeCaller1 : public BindFirstOpaque1< Caller1To2< Function1 > > { public: -FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >( 0 ){ -} + FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >( 0 ){ + } }; diff --git a/libs/generic/constant.cpp b/libs/generic/constant.cpp index 7c3c2fa6..9ddeb5bc 100644 --- a/libs/generic/constant.cpp +++ b/libs/generic/constant.cpp @@ -29,8 +29,8 @@ class Bleh { public: -STRING_CONSTANT( Name, "Bleh" ); -INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "Bleh" ); + INTEGER_CONSTANT( Version, 1 ); }; int version = Bleh::Version(); diff --git a/libs/generic/enumeration.h b/libs/generic/enumeration.h index 8d6c75eb..d78e7d21 100644 --- a/libs/generic/enumeration.h +++ b/libs/generic/enumeration.h @@ -35,13 +35,13 @@ template class EnumeratedValue : public Enumeration { -typename Enumeration::Value m_value; + typename Enumeration::Value m_value; public: -explicit EnumeratedValue( typename Enumeration::Value value ) : m_value( value ){ -} -typename Enumeration::Value get() const { - return m_value; -} + explicit EnumeratedValue( typename Enumeration::Value value ) : m_value( value ){ + } + typename Enumeration::Value get() const { + return m_value; + } }; template diff --git a/libs/generic/functional.h b/libs/generic/functional.h index 5459ba0d..993d7ed4 100644 --- a/libs/generic/functional.h +++ b/libs/generic/functional.h @@ -6,313 +6,313 @@ template class Member { public: -typedef Object& first_argument_type; -typedef R result_type; -static result_type call( first_argument_type object ){ - return ( object.*member )(); -} + typedef Object& first_argument_type; + typedef R result_type; + static result_type call( first_argument_type object ){ + return ( object.*member )(); + } }; template class ConstMember { public: -typedef const Object& first_argument_type; -typedef R result_type; -static result_type call( first_argument_type object ){ - return ( object.*member )(); -} + typedef const Object& first_argument_type; + typedef R result_type; + static result_type call( first_argument_type object ){ + return ( object.*member )(); + } }; template class Member1 { public: -typedef Object& first_argument_type; -typedef A1 second_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a1 ){ - return ( object.*member )( a1 ); -} + typedef Object& first_argument_type; + typedef A1 second_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a1 ){ + return ( object.*member )( a1 ); + } }; template class ConstMember1 { public: -typedef const Object& first_argument_type; -typedef A1 second_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a1 ){ - return ( object.*member )( a1 ); -} + typedef const Object& first_argument_type; + typedef A1 second_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a1 ){ + return ( object.*member )( a1 ); + } }; template class Member2 { public: -typedef Object& first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ - return ( object.*member )( a2, a3 ); -} + typedef Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ + return ( object.*member )( a2, a3 ); + } }; template class ConstMember2 { public: -typedef const Object& first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ - return ( object.*member )( a2, a3 ); -} + typedef const Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ + return ( object.*member )( a2, a3 ); + } }; template class Member3 { public: -typedef Object& first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef A4 fourth_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - return ( object.*member )( a2, a3, a4 ); -} + typedef Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return ( object.*member )( a2, a3, a4 ); + } }; template class ConstMember3 { public: -typedef const Object& first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef A4 fourth_argument_type; -typedef R result_type; -static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - return ( object.*member )( a2, a3, a4 ); -} + typedef const Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return ( object.*member )( a2, a3, a4 ); + } }; template class Function0 { public: -typedef R result_type; -static result_type call(){ - return (func)( ); -} + typedef R result_type; + static result_type call(){ + return (func)( ); + } }; template class Function1 { public: -typedef A1 first_argument_type; -typedef R result_type; -static result_type call( first_argument_type a1 ){ - return (func)( a1 ); -} + typedef A1 first_argument_type; + typedef R result_type; + static result_type call( first_argument_type a1 ){ + return (func)( a1 ); + } }; template class Function2 { public: -typedef A1 first_argument_type; -typedef A2 second_argument_type; -typedef R result_type; -static result_type call( first_argument_type a1, second_argument_type a2 ){ - return (func)( a1, a2 ); -} + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef R result_type; + static result_type call( first_argument_type a1, second_argument_type a2 ){ + return (func)( a1, a2 ); + } }; template class Function3 { public: -typedef A1 first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef R result_type; -static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ - return (func)( a1, a2, a3 ); -} + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ + return (func)( a1, a2, a3 ); + } }; template class Function4 { public: -typedef A1 first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef A4 fourth_argument_type; -typedef R result_type; -static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - return (func)( a1, a2, a3, a4 ); -} + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return (func)( a1, a2, a3, a4 ); + } }; template class Function5 { public: -typedef A1 first_argument_type; -typedef A2 second_argument_type; -typedef A3 third_argument_type; -typedef A4 fourth_argument_type; -typedef A5 fifth_argument_type; -typedef R result_type; -static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4, fifth_argument_type a5 ){ - return (func)( a1, a2, a3, a4, a5 ); -} + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef A5 fifth_argument_type; + typedef R result_type; + static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4, fifth_argument_type a5 ){ + return (func)( a1, a2, a3, a4, a5 ); + } }; template class Caller0To1 { public: -typedef FirstArgument first_argument_type; -typedef typename Caller::result_type result_type; -static result_type call( first_argument_type ){ - return Caller::call(); -} + typedef FirstArgument first_argument_type; + typedef typename Caller::result_type result_type; + static result_type call( first_argument_type ){ + return Caller::call(); + } }; template class Caller1To2 { public: -typedef FirstArgument first_argument_type; -typedef typename Caller::first_argument_type second_argument_type; -typedef typename Caller::result_type result_type; -static result_type call( first_argument_type, second_argument_type a2 ){ - return Caller::call( a2 ); -} + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::result_type result_type; + static result_type call( first_argument_type, second_argument_type a2 ){ + return Caller::call( a2 ); + } }; template class Caller2To3 { public: -typedef FirstArgument first_argument_type; -typedef typename Caller::first_argument_type second_argument_type; -typedef typename Caller::second_argument_type third_argument_type; -typedef typename Caller::result_type result_type; -static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3 ){ - return Caller::call( a2, a3 ); -} + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::second_argument_type third_argument_type; + typedef typename Caller::result_type result_type; + static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3 ){ + return Caller::call( a2, a3 ); + } }; template class Caller3To4 { public: -typedef FirstArgument first_argument_type; -typedef typename Caller::first_argument_type second_argument_type; -typedef typename Caller::second_argument_type third_argument_type; -typedef typename Caller::third_argument_type fourth_argument_type; -typedef typename Caller::result_type result_type; -static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - return Caller::call( a2, a3, a4 ); -} + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::second_argument_type third_argument_type; + typedef typename Caller::third_argument_type fourth_argument_type; + typedef typename Caller::result_type result_type; + static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return Caller::call( a2, a3, a4 ); + } }; template class Caller4To5 { public: -typedef FirstArgument first_argument_type; -typedef typename Caller::first_argument_type second_argument_type; -typedef typename Caller::second_argument_type third_argument_type; -typedef typename Caller::third_argument_type fourth_argument_type; -typedef typename Caller::fourth_argument_type fifth_argument_type; -typedef typename Caller::result_type result_type; -static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4, fifth_argument_type a5 ){ - return Caller::call( a2, a3, a4, a5 ); -} + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::second_argument_type third_argument_type; + typedef typename Caller::third_argument_type fourth_argument_type; + typedef typename Caller::fourth_argument_type fifth_argument_type; + typedef typename Caller::result_type result_type; + static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4, fifth_argument_type a5 ){ + return Caller::call( a2, a3, a4, a5 ); + } }; template class FunctorInvoke { public: -typedef typename Functor::result_type result_type; -inline result_type operator()( Functor functor ){ - return functor(); -} + typedef typename Functor::result_type result_type; + inline result_type operator()( Functor functor ){ + return functor(); + } }; template class Functor1Invoke { -typename Functor::first_argument_type a1; + typename Functor::first_argument_type a1; public: -typedef typename Functor::first_argument_type first_argument_type; -typedef typename Functor::result_type result_type; -Functor1Invoke( first_argument_type a1 ) : a1( a1 ){ -} -inline result_type operator()( Functor functor ){ - return functor( a1 ); -} + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::result_type result_type; + Functor1Invoke( first_argument_type a1 ) : a1( a1 ){ + } + inline result_type operator()( Functor functor ){ + return functor( a1 ); + } }; template class Functor2Invoke { -typename Functor::first_argument_type a1; -typename Functor::second_argument_type a2; + typename Functor::first_argument_type a1; + typename Functor::second_argument_type a2; public: -typedef typename Functor::first_argument_type first_argument_type; -typedef typename Functor::second_argument_type second_argument_type; -typedef typename Functor::result_type result_type; -Functor2Invoke( first_argument_type a1, second_argument_type a2 ) - : a1( a1 ), a2( a2 ){ -} -inline result_type operator()( Functor functor ){ - return functor( a1, a2 ); -} + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::second_argument_type second_argument_type; + typedef typename Functor::result_type result_type; + Functor2Invoke( first_argument_type a1, second_argument_type a2 ) + : a1( a1 ), a2( a2 ){ + } + inline result_type operator()( Functor functor ){ + return functor( a1, a2 ); + } }; template class Functor3Invoke { -typename Functor::first_argument_type a1; -typename Functor::second_argument_type a2; -typename Functor::third_argument_type a3; + typename Functor::first_argument_type a1; + typename Functor::second_argument_type a2; + typename Functor::third_argument_type a3; public: -typedef typename Functor::first_argument_type first_argument_type; -typedef typename Functor::second_argument_type second_argument_type; -typedef typename Functor::third_argument_type third_argument_type; -typedef typename Functor::result_type result_type; -Functor3Invoke( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) - : a1( a1 ), a2( a2 ), a3( a3 ){ -} -inline result_type operator()( Functor functor ){ - return functor( a1, a2, a3 ); -} + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::second_argument_type second_argument_type; + typedef typename Functor::third_argument_type third_argument_type; + typedef typename Functor::result_type result_type; + Functor3Invoke( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) + : a1( a1 ), a2( a2 ), a3( a3 ){ + } + inline result_type operator()( Functor functor ){ + return functor( a1, a2, a3 ); + } }; template class TypeEqual { public: -typedef False type; + typedef False type; }; template class TypeEqual { public: -typedef True type; + typedef True type; }; diff --git a/libs/generic/object.cpp b/libs/generic/object.cpp index bbb56108..123a74d7 100644 --- a/libs/generic/object.cpp +++ b/libs/generic/object.cpp @@ -25,11 +25,11 @@ namespace { class Blah { -int i; + int i; public: -Blah(){ - i = 3; -} + Blah(){ + i = 3; + } }; void Test(){ diff --git a/libs/generic/reference.h b/libs/generic/reference.h index df5a05a8..a6b2a95d 100644 --- a/libs/generic/reference.h +++ b/libs/generic/reference.h @@ -31,20 +31,20 @@ template class Reference { -Type* m_contained; + Type* m_contained; public: -explicit Reference( Type& contained ) : m_contained( &contained ){ -} -operator Type&() const -{ - return *m_contained; -} -Type& get() const { - return *m_contained; -} -Type* get_pointer() const { - return m_contained; -} + explicit Reference( Type& contained ) : m_contained( &contained ){ + } + operator Type&() const + { + return *m_contained; + } + Type& get() const { + return *m_contained; + } + Type* get_pointer() const { + return m_contained; + } }; template @@ -68,20 +68,20 @@ inline Reference makeReference( Type& value ){ template class ConstReference { -const Type* m_contained; + const Type* m_contained; public: -explicit ConstReference( const Type& contained ) : m_contained( &contained ){ -} -operator const Type&() const -{ - return *m_contained; -} -const Type& get() const { - return *m_contained; -} -const Type* get_pointer() const { - return m_contained; -} + explicit ConstReference( const Type& contained ) : m_contained( &contained ){ + } + operator const Type&() const + { + return *m_contained; + } + const Type& get() const { + return *m_contained; + } + const Type* get_pointer() const { + return m_contained; + } }; template diff --git a/libs/generic/referencecounted.h b/libs/generic/referencecounted.h index 37abd91f..6033ab53 100644 --- a/libs/generic/referencecounted.h +++ b/libs/generic/referencecounted.h @@ -31,59 +31,59 @@ template class IncRefDecRefCounter { public: -void increment( Type& value ){ - value.IncRef(); -} -void decrement( Type& value ){ - value.DecRef(); -} + void increment( Type& value ){ + value.IncRef(); + } + void decrement( Type& value ){ + value.DecRef(); + } }; /// \brief A smart-pointer that uses a counter stored in the object pointed-to. template > class SmartPointer : public Counter { -Type* m_value; + Type* m_value; public: -SmartPointer( const SmartPointer& other ) - : m_value( other.m_value ){ - Counter::increment( *m_value ); -} -explicit SmartPointer( Type* value ) - : m_value( value ){ - Counter::increment( *m_value ); -} -~SmartPointer(){ - Counter::decrement( *m_value ); -} -SmartPointer& operator=( const SmartPointer& other ){ - SmartPointer temp( other ); - temp.swap( *this ); - return *this; -} -SmartPointer& operator=( Type* value ){ - SmartPointer temp( value ); - temp.swap( *this ); - return *this; -} -void swap( SmartPointer& other ){ - std::swap( m_value, other.m_value ); -} + SmartPointer( const SmartPointer& other ) + : m_value( other.m_value ){ + Counter::increment( *m_value ); + } + explicit SmartPointer( Type* value ) + : m_value( value ){ + Counter::increment( *m_value ); + } + ~SmartPointer(){ + Counter::decrement( *m_value ); + } + SmartPointer& operator=( const SmartPointer& other ){ + SmartPointer temp( other ); + temp.swap( *this ); + return *this; + } + SmartPointer& operator=( Type* value ){ + SmartPointer temp( value ); + temp.swap( *this ); + return *this; + } + void swap( SmartPointer& other ){ + std::swap( m_value, other.m_value ); + } -operator Type*() const -{ - return m_value; -} -Type& operator*() const { - return *m_value; -} -Type* operator->() const { - return m_value; -} -Type* get() const { - return m_value; -} + operator Type*() const + { + return m_value; + } + Type& operator*() const { + return *m_value; + } + Type* operator->() const { + return m_value; + } + Type* get() const { + return m_value; + } }; template @@ -114,44 +114,44 @@ inline void swap( SmartPointer& self, SmartPointer& other ){ template > class SmartReference : public Counter { -Type* m_value; + Type* m_value; public: -SmartReference( const SmartReference& other ) - : m_value( other.m_value ){ - Counter::increment( *m_value ); -} -explicit SmartReference( Type& value ) - : m_value( &value ){ - Counter::increment( *m_value ); -} -~SmartReference(){ - Counter::decrement( *m_value ); -} -SmartReference& operator=( const SmartReference& other ){ - SmartReference temp( other ); - temp.swap( *this ); - return *this; -} -SmartReference& operator=( Type& value ){ - SmartReference temp( value ); - temp.swap( *this ); - return *this; -} -void swap( SmartReference& other ){ - std::swap( m_value, other.m_value ); -} + SmartReference( const SmartReference& other ) + : m_value( other.m_value ){ + Counter::increment( *m_value ); + } + explicit SmartReference( Type& value ) + : m_value( &value ){ + Counter::increment( *m_value ); + } + ~SmartReference(){ + Counter::decrement( *m_value ); + } + SmartReference& operator=( const SmartReference& other ){ + SmartReference temp( other ); + temp.swap( *this ); + return *this; + } + SmartReference& operator=( Type& value ){ + SmartReference temp( value ); + temp.swap( *this ); + return *this; + } + void swap( SmartReference& other ){ + std::swap( m_value, other.m_value ); + } -operator Type&() const -{ - return *m_value; -} -Type& get() const { - return *m_value; -} -Type* get_pointer() const { - return m_value; -} + operator Type&() const + { + return *m_value; + } + Type& get() const { + return *m_value; + } + Type* get_pointer() const { + return m_value; + } }; template diff --git a/libs/generic/static.cpp b/libs/generic/static.cpp index b32972de..71755ab2 100644 --- a/libs/generic/static.cpp +++ b/libs/generic/static.cpp @@ -30,9 +30,9 @@ namespace ExampleStatic class MyClass { public: -int value; -MyClass() : value( 3 ){ -} + int value; + MyClass() : value( 3 ){ + } }; typedef Static StaticMyClass; @@ -41,9 +41,9 @@ typedef Static StaticMyClass; class DynamicInitialisation { public: -DynamicInitialisation(){ - // StaticMyClass::instance() may be invalid here because construction order is undefined -} + DynamicInitialisation(){ + // StaticMyClass::instance() may be invalid here because construction order is undefined + } }; DynamicInitialisation g_dynamicInitialisation; @@ -61,9 +61,9 @@ namespace ExampleLazyStatic class MyClass { public: -int value; -MyClass() : value( 3 ){ -} + int value; + MyClass() : value( 3 ){ + } // destructor will never be called }; @@ -73,9 +73,9 @@ typedef LazyStatic StaticMyClass; class DynamicInitialisation { public: -DynamicInitialisation(){ - int bar = StaticMyClass::instance().value; -} + DynamicInitialisation(){ + int bar = StaticMyClass::instance().value; + } }; DynamicInitialisation g_dynamicInitialisation; @@ -93,9 +93,9 @@ namespace ExampleSmartStatic class MyClass { public: -int value; -MyClass() : value( 3 ){ -} + int value; + MyClass() : value( 3 ){ + } }; typedef CountedStatic StaticMyClass; @@ -104,13 +104,13 @@ typedef CountedStatic StaticMyClass; class DynamicInitialisation { public: -DynamicInitialisation(){ - // StaticMyClass::instance() is invalid before the ref is constructed - SmartStatic ref; - int bar = ref.instance().value; + DynamicInitialisation(){ + // StaticMyClass::instance() is invalid before the ref is constructed + SmartStatic ref; + int bar = ref.instance().value; - SmartStatic ref2; // any number of instances are allowed. -} + SmartStatic ref2; // any number of instances are allowed. + } }; DynamicInitialisation g_dynamicInitialisation; diff --git a/libs/generic/static.h b/libs/generic/static.h index ad501fc3..2106064c 100644 --- a/libs/generic/static.h +++ b/libs/generic/static.h @@ -42,11 +42,11 @@ class Null template class Static { -static Type m_instance; + static Type m_instance; public: -static Type& instance(){ - return m_instance; -} + static Type& instance(){ + return m_instance; + } }; template @@ -65,14 +65,14 @@ Type Static::m_instance; template class LazyStatic { -static Type* m_instance; // this will be initialised to 0 by the CRT, according to the c++ standard + static Type* m_instance; // this will be initialised to 0 by the CRT, according to the c++ standard public: -static Type& instance(){ - if ( m_instance == 0 ) { - m_instance = new Type; // allocate using 'new' to get the correct alignment + static Type& instance(){ + if ( m_instance == 0 ) { + m_instance = new Type; // allocate using 'new' to get the correct alignment + } + return *m_instance; } - return *m_instance; -} }; template @@ -89,22 +89,22 @@ Type * LazyStatic::m_instance; template class CountedStatic { -static std::size_t m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard -static Type* m_instance; + static std::size_t m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard + static Type* m_instance; public: -static Type& instance(){ - return *m_instance; -} -static void capture(){ - if ( ++m_refcount == 1 ) { - m_instance = new Type; // allocate using 'new' to get the correct alignment + static Type& instance(){ + return *m_instance; } -} -static void release(){ - if ( --m_refcount == 0 ) { - delete m_instance; + static void capture(){ + if ( ++m_refcount == 1 ) { + m_instance = new Type; // allocate using 'new' to get the correct alignment + } + } + static void release(){ + if ( --m_refcount == 0 ) { + delete m_instance; + } } -} }; template @@ -125,15 +125,15 @@ template class SmartStatic { public: -SmartStatic(){ - CountedStatic::capture(); -} -~SmartStatic(){ - CountedStatic::release(); -} -Type& instance(){ - return CountedStatic::instance(); -} + SmartStatic(){ + CountedStatic::capture(); + } + ~SmartStatic(){ + CountedStatic::release(); + } + Type& instance(){ + return CountedStatic::instance(); + } }; diff --git a/libs/generic/vector.h b/libs/generic/vector.h index 8d511bdb..6b66a876 100644 --- a/libs/generic/vector.h +++ b/libs/generic/vector.h @@ -7,189 +7,189 @@ template class BasicVector2 { -Element m_elements[2]; + Element m_elements[2]; public: -BasicVector2(){ -} -template -BasicVector2( const BasicVector2& other ){ - x() = static_cast( other.x() ); - y() = static_cast( other.y() ); -} -BasicVector2( const Element& x_, const Element& y_ ){ - x() = x_; - y() = y_; -} + BasicVector2(){ + } + template + BasicVector2( const BasicVector2& other ){ + x() = static_cast( other.x() ); + y() = static_cast( other.y() ); + } + BasicVector2( const Element& x_, const Element& y_ ){ + x() = x_; + y() = y_; + } -Element& x(){ - return m_elements[0]; -} -const Element& x() const { - return m_elements[0]; -} -Element& y(){ - return m_elements[1]; -} -const Element& y() const { - return m_elements[1]; -} + Element& x(){ + return m_elements[0]; + } + const Element& x() const { + return m_elements[0]; + } + Element& y(){ + return m_elements[1]; + } + const Element& y() const { + return m_elements[1]; + } -const Element& operator[]( std::size_t i ) const { - return m_elements[i]; -} -Element& operator[]( std::size_t i ){ - return m_elements[i]; -} + const Element& operator[]( std::size_t i ) const { + return m_elements[i]; + } + Element& operator[]( std::size_t i ){ + return m_elements[i]; + } -Element* data(){ - return m_elements; -} -const Element* data() const { - return m_elements; -} + Element* data(){ + return m_elements; + } + const Element* data() const { + return m_elements; + } }; /// \brief A 3-element vector. template class BasicVector3 { -Element m_elements[3]; + Element m_elements[3]; public: -BasicVector3(){ -} -template -BasicVector3( const BasicVector3& other ){ - x() = static_cast( other.x() ); - y() = static_cast( other.y() ); - z() = static_cast( other.z() ); -} -template -explicit BasicVector3( const BasicVector2& vec2 ){ - x() = static_cast( vec2.x() ); - y() = static_cast( vec2.y() ); - z() = 0; -} -BasicVector3( const Element& x_, const Element& y_, const Element& z_ ) : m_elements{ x_, y_, z_ }{ -} -explicit BasicVector3( const Element& value ) : m_elements{ value, value, value }{ -} + BasicVector3(){ + } + template + BasicVector3( const BasicVector3& other ){ + x() = static_cast( other.x() ); + y() = static_cast( other.y() ); + z() = static_cast( other.z() ); + } + template + explicit BasicVector3( const BasicVector2& vec2 ){ + x() = static_cast( vec2.x() ); + y() = static_cast( vec2.y() ); + z() = 0; + } + BasicVector3( const Element& x_, const Element& y_, const Element& z_ ) : m_elements{ x_, y_, z_ }{ + } + explicit BasicVector3( const Element& value ) : m_elements{ value, value, value }{ + } -Element& x(){ - return m_elements[0]; -} -const Element& x() const { - return m_elements[0]; -} -Element& y(){ - return m_elements[1]; -} -const Element& y() const { - return m_elements[1]; -} -Element& z(){ - return m_elements[2]; -} -const Element& z() const { - return m_elements[2]; -} + Element& x(){ + return m_elements[0]; + } + const Element& x() const { + return m_elements[0]; + } + Element& y(){ + return m_elements[1]; + } + const Element& y() const { + return m_elements[1]; + } + Element& z(){ + return m_elements[2]; + } + const Element& z() const { + return m_elements[2]; + } -const Element& operator[]( std::size_t i ) const { - return m_elements[i]; -} -Element& operator[]( std::size_t i ){ - return m_elements[i]; -} + const Element& operator[]( std::size_t i ) const { + return m_elements[i]; + } + Element& operator[]( std::size_t i ){ + return m_elements[i]; + } -Element* data(){ - return m_elements; -} -const Element* data() const { - return m_elements; -} + Element* data(){ + return m_elements; + } + const Element* data() const { + return m_elements; + } -void set( const Element value ){ - x() = y() = z() = value; -} + void set( const Element value ){ + x() = y() = z() = value; + } }; /// \brief A 4-element vector. template class BasicVector4 { -Element m_elements[4]; + Element m_elements[4]; public: -BasicVector4(){ -} -BasicVector4( Element x_, Element y_, Element z_, Element w_ ){ - x() = x_; - y() = y_; - z() = z_; - w() = w_; -} -BasicVector4( const BasicVector3& self, Element w_ ){ - x() = self.x(); - y() = self.y(); - z() = self.z(); - w() = w_; -} + BasicVector4(){ + } + BasicVector4( Element x_, Element y_, Element z_, Element w_ ){ + x() = x_; + y() = y_; + z() = z_; + w() = w_; + } + BasicVector4( const BasicVector3& self, Element w_ ){ + x() = self.x(); + y() = self.y(); + z() = self.z(); + w() = w_; + } -Element& x(){ - return m_elements[0]; -} -const Element& x() const { - return m_elements[0]; -} -Element& y(){ - return m_elements[1]; -} -const Element& y() const { - return m_elements[1]; -} -Element& z(){ - return m_elements[2]; -} -const Element& z() const { - return m_elements[2]; -} -Element& w(){ - return m_elements[3]; -} -const Element& w() const { - return m_elements[3]; -} + Element& x(){ + return m_elements[0]; + } + const Element& x() const { + return m_elements[0]; + } + Element& y(){ + return m_elements[1]; + } + const Element& y() const { + return m_elements[1]; + } + Element& z(){ + return m_elements[2]; + } + const Element& z() const { + return m_elements[2]; + } + Element& w(){ + return m_elements[3]; + } + const Element& w() const { + return m_elements[3]; + } -Element index( std::size_t i ) const { - return m_elements[i]; -} -Element& index( std::size_t i ){ - return m_elements[i]; -} -Element operator[]( std::size_t i ) const { - return m_elements[i]; -} -Element& operator[]( std::size_t i ){ - return m_elements[i]; -} + Element index( std::size_t i ) const { + return m_elements[i]; + } + Element& index( std::size_t i ){ + return m_elements[i]; + } + Element operator[]( std::size_t i ) const { + return m_elements[i]; + } + Element& operator[]( std::size_t i ){ + return m_elements[i]; + } -Element* data(){ - return m_elements; -} -const Element* data() const { - return m_elements; -} + Element* data(){ + return m_elements; + } + const Element* data() const { + return m_elements; + } -BasicVector3& vec3(){ - return reinterpret_cast&>( x() ); -} -const BasicVector3& vec3() const { - return reinterpret_cast&>( x() ); -} + BasicVector3& vec3(){ + return reinterpret_cast&>( x() ); + } + const BasicVector3& vec3() const { + return reinterpret_cast&>( x() ); + } -void set( const Element value ){ - x() = y() = z() = w() = value; -} + void set( const Element value ){ + x() = y() = z() = w() = value; + } }; template diff --git a/libs/gtkutil/accelerator.h b/libs/gtkutil/accelerator.h index dbbad344..cf6fe8b2 100644 --- a/libs/gtkutil/accelerator.h +++ b/libs/gtkutil/accelerator.h @@ -110,29 +110,29 @@ void global_accel_group_disconnect( const Accelerator& accelerator, const Callba class Command { public: -Callback m_callback; -const Accelerator& m_accelerator; -Command( const Callback& callback, const Accelerator& accelerator ) : m_callback( callback ), m_accelerator( accelerator ){ -} + Callback m_callback; + const Accelerator& m_accelerator; + Command( const Callback& callback, const Accelerator& accelerator ) : m_callback( callback ), m_accelerator( accelerator ){ + } }; class Toggle { public: -Command m_command; -BoolExportCallback m_exportCallback; -Toggle( const Callback& callback, const Accelerator& accelerator, const BoolExportCallback& exportCallback ) : m_command( callback, accelerator ), m_exportCallback( exportCallback ){ -} + Command m_command; + BoolExportCallback m_exportCallback; + Toggle( const Callback& callback, const Accelerator& accelerator, const BoolExportCallback& exportCallback ) : m_command( callback, accelerator ), m_exportCallback( exportCallback ){ + } }; class KeyEvent { public: -const Accelerator& m_accelerator; -Callback m_keyDown; -Callback m_keyUp; -KeyEvent( const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp ) : m_accelerator( accelerator ), m_keyDown( keyDown ), m_keyUp( keyUp ){ -} + const Accelerator& m_accelerator; + Callback m_keyDown; + Callback m_keyUp; + KeyEvent( const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp ) : m_accelerator( accelerator ), m_keyDown( keyDown ), m_keyUp( keyUp ){ + } }; diff --git a/libs/gtkutil/cursor.h b/libs/gtkutil/cursor.h index 47c60bd8..70b92af6 100644 --- a/libs/gtkutil/cursor.h +++ b/libs/gtkutil/cursor.h @@ -40,191 +40,191 @@ void Sys_SetCursorPos( GtkWindow* window, int x, int y ); class DeferredMotion { -guint m_handler; -typedef void ( *MotionFunction )( gdouble x, gdouble y, guint state, void* data ); -MotionFunction m_function; -void* m_data; -gdouble m_x; -gdouble m_y; -guint m_state; + guint m_handler; + typedef void ( *MotionFunction )( gdouble x, gdouble y, guint state, void* data ); + MotionFunction m_function; + void* m_data; + gdouble m_x; + gdouble m_y; + guint m_state; -static gboolean deferred( DeferredMotion* self ){ - self->m_handler = 0; - self->m_function( self->m_x, self->m_y, self->m_state, self->m_data ); - return FALSE; -} -public: -DeferredMotion( MotionFunction function, void* data ) : m_handler( 0 ), m_function( function ), m_data( data ){ -} -void motion( gdouble x, gdouble y, guint state ){ - m_x = x; - m_y = y; - m_state = state; - if ( m_handler == 0 ) { - m_handler = g_idle_add( (GSourceFunc)deferred, this ); + static gboolean deferred( DeferredMotion* self ){ + self->m_handler = 0; + self->m_function( self->m_x, self->m_y, self->m_state, self->m_data ); + return FALSE; + } +public: + DeferredMotion( MotionFunction function, void* data ) : m_handler( 0 ), m_function( function ), m_data( data ){ + } + void motion( gdouble x, gdouble y, guint state ){ + m_x = x; + m_y = y; + m_state = state; + if ( m_handler == 0 ) { + m_handler = g_idle_add( (GSourceFunc)deferred, this ); + } + } + static gboolean gtk_motion( GtkWidget *widget, GdkEventMotion *event, DeferredMotion* self ){ + self->motion( event->x, event->y, event->state ); + return FALSE; } -} -static gboolean gtk_motion( GtkWidget *widget, GdkEventMotion *event, DeferredMotion* self ){ - self->motion( event->x, event->y, event->state ); - return FALSE; -} }; class DeferredMotionDelta { -int m_delta_x; -int m_delta_y; -unsigned int m_state; -guint m_motion_handler; -typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); -MotionDeltaFunction m_function; -void* m_data; + int m_delta_x; + int m_delta_y; + unsigned int m_state; + guint m_motion_handler; + typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); + MotionDeltaFunction m_function; + void* m_data; -static gboolean deferred_motion( gpointer data ){ - DeferredMotionDelta* self = reinterpret_cast( data ); - self->m_function( - self->m_delta_x, - self->m_delta_y, - self->m_state, - self->m_data + static gboolean deferred_motion( gpointer data ){ + DeferredMotionDelta* self = reinterpret_cast( data ); + self->m_function( + self->m_delta_x, + self->m_delta_y, + self->m_state, + self->m_data ); - self->m_motion_handler = 0; - self->m_delta_x = 0; - self->m_delta_y = 0; - return FALSE; -} + self->m_motion_handler = 0; + self->m_delta_x = 0; + self->m_delta_y = 0; + return FALSE; + } public: -DeferredMotionDelta( MotionDeltaFunction function, void* data ) : m_delta_x( 0 ), m_delta_y( 0 ), m_motion_handler( 0 ), m_function( function ), m_data( data ){ -} -void flush(){ - if ( m_motion_handler != 0 ) { - g_source_remove( m_motion_handler ); - deferred_motion( this ); + DeferredMotionDelta( MotionDeltaFunction function, void* data ) : m_delta_x( 0 ), m_delta_y( 0 ), m_motion_handler( 0 ), m_function( function ), m_data( data ){ } -} -void motion_delta( int x, int y, unsigned int state ){ - m_delta_x += x; - m_delta_y += y; - m_state = state; - if ( m_motion_handler == 0 ) { - m_motion_handler = g_idle_add( deferred_motion, this ); + void flush(){ + if ( m_motion_handler != 0 ) { + g_source_remove( m_motion_handler ); + deferred_motion( this ); + } + } + void motion_delta( int x, int y, unsigned int state ){ + m_delta_x += x; + m_delta_y += y; + m_state = state; + if ( m_motion_handler == 0 ) { + m_motion_handler = g_idle_add( deferred_motion, this ); + } } -} }; class FreezePointer { -unsigned int handle_motion; -int recorded_x, recorded_y, last_x, last_y, center_x, center_y; -GtkWindow* m_window; -GtkWidget* m_widget; -typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); -MotionDeltaFunction m_function; -void* m_data; + unsigned int handle_motion; + int recorded_x, recorded_y, last_x, last_y, center_x, center_y; + GtkWindow* m_window; + GtkWidget* m_widget; + typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); + MotionDeltaFunction m_function; + void* m_data; public: -FreezePointer() : handle_motion( 0 ), m_function( 0 ), m_data( 0 ){ -} -static gboolean motion_delta( GtkWidget *widget, GdkEventMotion *event, FreezePointer* self ){ - int current_x, current_y; - Sys_GetCursorPos( GTK_WINDOW( widget ), ¤t_x, ¤t_y ); + FreezePointer() : handle_motion( 0 ), m_function( 0 ), m_data( 0 ){ + } + static gboolean motion_delta( GtkWidget *widget, GdkEventMotion *event, FreezePointer* self ){ + int current_x, current_y; + Sys_GetCursorPos( GTK_WINDOW( widget ), ¤t_x, ¤t_y ); #define FIX_LINUX_TOUCHPAD 0 /* issues with this: mouse juddering in win10 (system is already at normal scaling) Leaving the DPI scaling to the application instead of the system half fixes it in GNU/Linux Mouselook is broken with custom Input Coordinate Tranformation */ #if FIX_LINUX_TOUCHPAD - const int dx = current_x - self->last_x; - const int dy = current_y - self->last_y; - const int ddx = current_x - self->center_x; - const int ddy = current_y - self->center_y; - self->last_x = current_x; - self->last_y = current_y; - if ( dx != 0 || dy != 0 ) { - //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; - if ( ddx < -32 || ddx > 32 || ddy < -32 || ddy > 32 ) { - Sys_SetCursorPos( GTK_WINDOW( widget ), self->center_x, self->center_y ); - self->last_x = self->center_x; - self->last_y = self->center_y; - } + const int dx = current_x - self->last_x; + const int dy = current_y - self->last_y; + const int ddx = current_x - self->center_x; + const int ddy = current_y - self->center_y; + self->last_x = current_x; + self->last_y = current_y; + if ( dx != 0 || dy != 0 ) { + //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; + if ( ddx < -32 || ddx > 32 || ddy < -32 || ddy > 32 ) { + Sys_SetCursorPos( GTK_WINDOW( widget ), self->center_x, self->center_y ); + self->last_x = self->center_x; + self->last_y = self->center_y; + } #else - const int dx = current_x - self->center_x; - const int dy = current_y - self->center_y; - if ( dx != 0 || dy != 0 ) { - //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; - Sys_SetCursorPos( GTK_WINDOW( widget ), self->center_x, self->center_y ); + const int dx = current_x - self->center_x; + const int dy = current_y - self->center_y; + if ( dx != 0 || dy != 0 ) { + //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; + Sys_SetCursorPos( GTK_WINDOW( widget ), self->center_x, self->center_y ); #endif - self->m_function( dx, dy, event->state, self->m_data ); + self->m_function( dx, dy, event->state, self->m_data ); + } + return FALSE; } - return FALSE; -} -void freeze_pointer( GtkWindow* window, GtkWidget* widget, MotionDeltaFunction function, void* data ){ - ASSERT_MESSAGE( m_function == 0, "can't freeze pointer: already frozen" ); + void freeze_pointer( GtkWindow* window, GtkWidget* widget, MotionDeltaFunction function, void* data ){ + ASSERT_MESSAGE( m_function == 0, "can't freeze pointer: already frozen" ); - const GdkEventMask mask = static_cast( GDK_POINTER_MOTION_MASK - | GDK_POINTER_MOTION_HINT_MASK - | GDK_BUTTON_MOTION_MASK - | GDK_BUTTON1_MOTION_MASK - | GDK_BUTTON2_MOTION_MASK - | GDK_BUTTON3_MOTION_MASK - | GDK_BUTTON_PRESS_MASK - | GDK_BUTTON_RELEASE_MASK - | GDK_VISIBILITY_NOTIFY_MASK ); + const GdkEventMask mask = static_cast( GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK + | GDK_BUTTON_MOTION_MASK + | GDK_BUTTON1_MOTION_MASK + | GDK_BUTTON2_MOTION_MASK + | GDK_BUTTON3_MOTION_MASK + | GDK_BUTTON_PRESS_MASK + | GDK_BUTTON_RELEASE_MASK + | GDK_VISIBILITY_NOTIFY_MASK ); - GdkCursor* cursor = gdk_cursor_new( GDK_BLANK_CURSOR ); - //GdkCursor* cursor = create_blank_cursor(); - //GdkGrabStatus status = - /* fixes cursor runaways during srsly quick drags in camera - drags with pressed buttons have no problem at all w/o this */ - gdk_pointer_grab( gtk_widget_get_window( GTK_WIDGET( window ) ), TRUE, mask, 0, cursor, GDK_CURRENT_TIME ); - //gdk_window_set_cursor ( gtk_widget_get_window( GTK_WIDGET( window ) ), cursor ); - /* is needed to fix activating neighbor widgets, that happens, if using upper one */ - gtk_grab_add( widget ); + GdkCursor* cursor = gdk_cursor_new( GDK_BLANK_CURSOR ); + //GdkCursor* cursor = create_blank_cursor(); + //GdkGrabStatus status = + /* fixes cursor runaways during srsly quick drags in camera + drags with pressed buttons have no problem at all w/o this */ + gdk_pointer_grab( gtk_widget_get_window( GTK_WIDGET( window ) ), TRUE, mask, 0, cursor, GDK_CURRENT_TIME ); + //gdk_window_set_cursor ( gtk_widget_get_window( GTK_WIDGET( window ) ), cursor ); + /* is needed to fix activating neighbor widgets, that happens, if using upper one */ + gtk_grab_add( widget ); - gdk_cursor_unref( cursor ); + gdk_cursor_unref( cursor ); - Sys_GetCursorPos( window, &recorded_x, &recorded_y ); + Sys_GetCursorPos( window, &recorded_x, &recorded_y ); - /* using center for tracking for max safety */ - gdk_window_get_origin( gtk_widget_get_window( widget ), ¢er_x, ¢er_y ); - GtkAllocation allocation; - gtk_widget_get_allocation( widget, &allocation ); - center_y += allocation.height / 2; - center_x += allocation.width / 2; + /* using center for tracking for max safety */ + gdk_window_get_origin( gtk_widget_get_window( widget ), ¢er_x, ¢er_y ); + GtkAllocation allocation; + gtk_widget_get_allocation( widget, &allocation ); + center_y += allocation.height / 2; + center_x += allocation.width / 2; - Sys_SetCursorPos( window, center_x, center_y ); + Sys_SetCursorPos( window, center_x, center_y ); - last_x = center_x; - last_y = center_y; + last_x = center_x; + last_y = center_y; - m_widget = widget; - m_window = window; + m_widget = widget; + m_window = window; - m_function = function; - m_data = data; + m_function = function; + m_data = data; - handle_motion = g_signal_connect( G_OBJECT( window ), "motion_notify_event", G_CALLBACK( motion_delta ), this ); -} - -void unfreeze_pointer( bool centerize ){ - ASSERT_MESSAGE( m_function != 0, "can't unfreeze pointer: is not frozen" ); - - g_signal_handler_disconnect( G_OBJECT( m_window ), handle_motion ); - - m_function = 0; - m_data = 0; - - if( centerize ){ - Sys_SetCursorPos( m_window, center_x, center_y ); - } - else{ - Sys_SetCursorPos( m_window, recorded_x, recorded_y ); + handle_motion = g_signal_connect( G_OBJECT( window ), "motion_notify_event", G_CALLBACK( motion_delta ), this ); } + + void unfreeze_pointer( bool centerize ){ + ASSERT_MESSAGE( m_function != 0, "can't unfreeze pointer: is not frozen" ); + + g_signal_handler_disconnect( G_OBJECT( m_window ), handle_motion ); + + m_function = 0; + m_data = 0; + + if( centerize ){ + Sys_SetCursorPos( m_window, center_x, center_y ); + } + else{ + Sys_SetCursorPos( m_window, recorded_x, recorded_y ); + } // gdk_window_set_cursor( gtk_widget_get_window( GTK_WIDGET( m_window ) ), 0 ); - gdk_pointer_ungrab( GDK_CURRENT_TIME ); + gdk_pointer_ungrab( GDK_CURRENT_TIME ); - gtk_grab_remove( m_widget ); -} + gtk_grab_remove( m_widget ); + } }; @@ -233,40 +233,40 @@ void unfreeze_pointer( bool centerize ){ class DeferredAdjustment { -gdouble m_value; -guint m_handler; -typedef void ( *ValueChangedFunction )( void* data, gdouble value ); -ValueChangedFunction m_function; -void* m_data; + gdouble m_value; + guint m_handler; + typedef void ( *ValueChangedFunction )( void* data, gdouble value ); + ValueChangedFunction m_function; + void* m_data; -static gboolean deferred_value_changed( gpointer data ){ - DeferredAdjustment* self = reinterpret_cast( data ); - self->m_function( - self->m_data, - self->m_value + static gboolean deferred_value_changed( gpointer data ){ + DeferredAdjustment* self = reinterpret_cast( data ); + self->m_function( + self->m_data, + self->m_value ); - self->m_handler = 0; - self->m_value = 0; - return FALSE; -} + self->m_handler = 0; + self->m_value = 0; + return FALSE; + } public: -DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){ -} -void flush(){ - if ( m_handler != 0 ) { - g_source_remove( m_handler ); - deferred_value_changed( this ); + DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){ } -} -void value_changed( gdouble value ){ - m_value = value; - if ( m_handler == 0 ) { - m_handler = g_idle_add( deferred_value_changed, this ); + void flush(){ + if ( m_handler != 0 ) { + g_source_remove( m_handler ); + deferred_value_changed( this ); + } + } + void value_changed( gdouble value ){ + m_value = value; + if ( m_handler == 0 ) { + m_handler = g_idle_add( deferred_value_changed, this ); + } + } + static void adjustment_value_changed( GtkAdjustment *adjustment, DeferredAdjustment* self ){ + self->value_changed( gtk_adjustment_get_value( adjustment ) ); } -} -static void adjustment_value_changed( GtkAdjustment *adjustment, DeferredAdjustment* self ){ - self->value_changed( gtk_adjustment_get_value( adjustment ) ); -} }; diff --git a/libs/gtkutil/dialog.cpp b/libs/gtkutil/dialog.cpp index 5e8d17aa..74f4ea7b 100644 --- a/libs/gtkutil/dialog.cpp +++ b/libs/gtkutil/dialog.cpp @@ -255,12 +255,12 @@ GtkTable* DialogRow_new( const char* name, GtkWidget* widget ){ gtk_table_set_row_spacings( table, 0 ); gtk_table_attach( table, GTK_WIDGET( DialogLabel_new( name ) ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, widget, 1, 3, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); return table; } diff --git a/libs/gtkutil/dialog.h b/libs/gtkutil/dialog.h index 59e6eb84..e7e72e4e 100644 --- a/libs/gtkutil/dialog.h +++ b/libs/gtkutil/dialog.h @@ -72,12 +72,12 @@ GtkWindow* create_simple_modal_dialog_window( const char* title, ModalDialog& di class RadioHBox { public: -GtkHBox* m_hbox; -GtkRadioButton* m_radio; -RadioHBox( GtkHBox* hbox, GtkRadioButton* radio ) : - m_hbox( hbox ), - m_radio( radio ){ -} + GtkHBox* m_hbox; + GtkRadioButton* m_radio; + RadioHBox( GtkHBox* hbox, GtkRadioButton* radio ) : + m_hbox( hbox ), + m_radio( radio ){ + } }; RadioHBox RadioHBox_new( StringArrayRange names ); @@ -86,14 +86,14 @@ RadioHBox RadioHBox_new( StringArrayRange names ); class PathEntry { public: -GtkFrame* m_frame; -GtkEntry* m_entry; -GtkButton* m_button; -PathEntry( GtkFrame* frame, GtkEntry* entry, GtkButton* button ) : - m_frame( frame ), - m_entry( entry ), - m_button( button ){ -} + GtkFrame* m_frame; + GtkEntry* m_entry; + GtkButton* m_button; + PathEntry( GtkFrame* frame, GtkEntry* entry, GtkButton* button ) : + m_frame( frame ), + m_entry( entry ), + m_button( button ){ + } }; PathEntry PathEntry_new(); @@ -101,13 +101,13 @@ PathEntry PathEntry_new(); class BrowsedPathEntry { public: -typedef Callback1 SetPathCallback; -typedef Callback1 BrowseCallback; + typedef Callback1 SetPathCallback; + typedef Callback1 BrowseCallback; -PathEntry m_entry; -BrowseCallback m_browse; + PathEntry m_entry; + BrowseCallback m_browse; -BrowsedPathEntry( const BrowseCallback& browse ); + BrowsedPathEntry( const BrowseCallback& browse ); }; GtkLabel* DialogLabel_new( const char* name ); diff --git a/libs/gtkutil/filechooser.cpp b/libs/gtkutil/filechooser.cpp index 0abe3581..27621ecd 100644 --- a/libs/gtkutil/filechooser.cpp +++ b/libs/gtkutil/filechooser.cpp @@ -50,74 +50,74 @@ struct filetype_pair_t class FileTypeList : public IFileTypeList { -struct filetype_copy_t -{ - filetype_copy_t( const filetype_pair_t& other ) - : m_moduleName( other.m_moduleName ), m_name( other.m_type.name ), m_pattern( other.m_type.pattern ){ - } - CopiedString m_moduleName; - CopiedString m_name; - CopiedString m_pattern; -}; + struct filetype_copy_t + { + filetype_copy_t( const filetype_pair_t& other ) + : m_moduleName( other.m_moduleName ), m_name( other.m_type.name ), m_pattern( other.m_type.pattern ){ + } + CopiedString m_moduleName; + CopiedString m_name; + CopiedString m_pattern; + }; -typedef std::list Types; -Types m_types; + typedef std::list Types; + Types m_types; public: -typedef Types::const_iterator const_iterator; -const_iterator begin() const { - return m_types.begin(); -} -const_iterator end() const { - return m_types.end(); -} + typedef Types::const_iterator const_iterator; + const_iterator begin() const { + return m_types.begin(); + } + const_iterator end() const { + return m_types.end(); + } -std::size_t size() const { - return m_types.size(); -} + std::size_t size() const { + return m_types.size(); + } -void addType( const char* moduleName, filetype_t type ){ - m_types.push_back( filetype_pair_t( moduleName, type ) ); -} + void addType( const char* moduleName, filetype_t type ){ + m_types.push_back( filetype_pair_t( moduleName, type ) ); + } }; class GTKMasks { -const FileTypeList& m_types; + const FileTypeList& m_types; public: -std::vector m_filters; -std::vector m_masks; + std::vector m_filters; + std::vector m_masks; -GTKMasks( const FileTypeList& types ) : m_types( types ){ - m_masks.reserve( m_types.size() ); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - std::size_t len = strlen( ( *i ).m_name.c_str() ) + strlen( ( *i ).m_pattern.c_str() ) + 3; - StringOutputStream buffer( len + 1 ); // length + null char + GTKMasks( const FileTypeList& types ) : m_types( types ){ + m_masks.reserve( m_types.size() ); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) + { + std::size_t len = strlen( ( *i ).m_name.c_str() ) + strlen( ( *i ).m_pattern.c_str() ) + 3; + StringOutputStream buffer( len + 1 ); // length + null char - buffer << ( *i ).m_name.c_str() << " <" << ( *i ).m_pattern.c_str() << ">"; + buffer << ( *i ).m_name.c_str() << " <" << ( *i ).m_pattern.c_str() << ">"; - m_masks.push_back( buffer.c_str() ); - } + m_masks.push_back( buffer.c_str() ); + } - m_filters.reserve( m_types.size() ); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - m_filters.push_back( ( *i ).m_pattern ); - } -} - -filetype_pair_t GetTypeForGTKMask( const char *mask ) const { - std::vector::const_iterator j = m_masks.begin(); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j ) - { - if ( string_equal( ( *j ).c_str(), mask ) ) { - return filetype_pair_t( ( *i ).m_moduleName.c_str(), filetype_t( ( *i ).m_name.c_str(), ( *i ).m_pattern.c_str() ) ); + m_filters.reserve( m_types.size() ); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) + { + m_filters.push_back( ( *i ).m_pattern ); } } - return filetype_pair_t(); -} + + filetype_pair_t GetTypeForGTKMask( const char *mask ) const { + std::vector::const_iterator j = m_masks.begin(); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j ) + { + if ( string_equal( ( *j ).c_str(), mask ) ) { + return filetype_pair_t( ( *i ).m_moduleName.c_str(), filetype_t( ( *i ).m_name.c_str(), ( *i ).m_pattern.c_str() ) ); + } + } + return filetype_pair_t(); + } }; @@ -140,20 +140,20 @@ const char* file_dialog_show( GtkWidget* parent, bool open, const char* title, c GtkWidget* dialog; if ( open ) { dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL ); + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_OPEN, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, + NULL ); } else { dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL ); + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_SAVE, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, + NULL ); gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER( dialog ), "unnamed" ); } @@ -213,7 +213,7 @@ const char* file_dialog_show( GtkWidget* parent, bool open, const char* title, c filetype_t type; GtkFileFilter* filter = gtk_file_chooser_get_filter( GTK_FILE_CHOOSER( dialog ) ); if ( filter != 0 // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files' - && !string_equal( gtk_file_filter_get_name( filter ), "All supported formats" ) ) + && !string_equal( gtk_file_filter_get_name( filter ), "All supported formats" ) ) type = masks.GetTypeForGTKMask( gtk_file_filter_get_name( filter ) ).m_type; else type = masks.GetTypeForGTKMask( ( *masks.m_masks.begin() ).c_str() ).m_type; @@ -257,11 +257,11 @@ const char* file_dialog_show( GtkWidget* parent, bool open, const char* title, c char* dir_dialog( GtkWidget* parent, const char* title, const char* path ){ GtkWidget* dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL ); + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, + NULL ); gtk_window_set_modal( GTK_WINDOW( dialog ), TRUE ); gtk_window_set_position( GTK_WINDOW( dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); @@ -286,9 +286,9 @@ const char* file_dialog( GtkWidget* parent, bool open, const char* title, const const char* file = file_dialog_show( parent, open, title, path, pattern, want_load, want_import, want_save ); if ( open - || file == 0 - || !file_exists( file ) - || gtk_MessageBox( parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION ) == eIDYES ) { + || file == 0 + || !file_exists( file ) + || gtk_MessageBox( parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION ) == eIDYES ) { return file; } } diff --git a/libs/gtkutil/glfont.cpp b/libs/gtkutil/glfont.cpp index 6a5e0a80..0bc357ff 100644 --- a/libs/gtkutil/glfont.cpp +++ b/libs/gtkutil/glfont.cpp @@ -92,331 +92,331 @@ void gray_to_texture( const unsigned int x_max, const unsigned int y_max, const // generic string printing with call lists class GLFontCallList final : public GLFont { -GLuint m_displayList; -GLuint m_atlas; -int m_pixelHeight; -int m_pixelAscent; -int m_pixelDescent; -PangoFontMap *m_fontmap; -PangoContext *m_ft2_context; + GLuint m_displayList; + GLuint m_atlas; + int m_pixelHeight; + int m_pixelAscent; + int m_pixelDescent; + PangoFontMap *m_fontmap; + PangoContext *m_ft2_context; public: -GLFontCallList( GLuint displayList, GLuint atlas, int asc, int desc, int pixelHeight, PangoFontMap *fontmap, PangoContext *ft2_context ) : - m_displayList( displayList ), m_atlas( atlas ), m_pixelHeight( pixelHeight ), m_pixelAscent( asc ), m_pixelDescent( desc ), m_fontmap( fontmap ), m_ft2_context( ft2_context ){ -} -~GLFontCallList(){ - glDeleteLists( m_displayList, 128 ); - glDeleteTextures( 1, &m_atlas ); - if( m_ft2_context ) - g_object_unref( G_OBJECT( m_ft2_context ) ); - if( m_fontmap ) - g_object_unref( G_OBJECT( m_fontmap ) ); -} -void printString( const char *s ){ - GLboolean rasterPosValid; - glGetBooleanv( GL_CURRENT_RASTER_POSITION_VALID, &rasterPosValid ); - if( !rasterPosValid ) - return; - GLfloat rasterPos[4]; - glGetFloatv( GL_CURRENT_RASTER_POSITION, rasterPos ); + GLFontCallList( GLuint displayList, GLuint atlas, int asc, int desc, int pixelHeight, PangoFontMap *fontmap, PangoContext *ft2_context ) : + m_displayList( displayList ), m_atlas( atlas ), m_pixelHeight( pixelHeight ), m_pixelAscent( asc ), m_pixelDescent( desc ), m_fontmap( fontmap ), m_ft2_context( ft2_context ){ + } + ~GLFontCallList(){ + glDeleteLists( m_displayList, 128 ); + glDeleteTextures( 1, &m_atlas ); + if( m_ft2_context ) + g_object_unref( G_OBJECT( m_ft2_context ) ); + if( m_fontmap ) + g_object_unref( G_OBJECT( m_fontmap ) ); + } + void printString( const char *s ){ + GLboolean rasterPosValid; + glGetBooleanv( GL_CURRENT_RASTER_POSITION_VALID, &rasterPosValid ); + if( !rasterPosValid ) + return; + GLfloat rasterPos[4]; + glGetFloatv( GL_CURRENT_RASTER_POSITION, rasterPos ); - GLint viewport[4]; - glGetIntegerv( GL_VIEWPORT, viewport ); - glMatrixMode( GL_PROJECTION ); - glPushMatrix(); - glLoadIdentity(); - glOrtho( viewport[0], viewport[2], viewport[1], viewport[3], -1, 1 ); + GLint viewport[4]; + glGetIntegerv( GL_VIEWPORT, viewport ); + glMatrixMode( GL_PROJECTION ); + glPushMatrix(); + glLoadIdentity(); + glOrtho( viewport[0], viewport[2], viewport[1], viewport[3], -1, 1 ); - glMatrixMode( GL_MODELVIEW ); - glPushMatrix(); - glLoadIdentity(); - glTranslatef( rasterPos[0], rasterPos[1], 0 ); + glMatrixMode( GL_MODELVIEW ); + glPushMatrix(); + glLoadIdentity(); + glTranslatef( rasterPos[0], rasterPos[1], 0 ); - glPushAttrib( GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT ); - glDisable( GL_LIGHTING ); - glEnable( GL_TEXTURE_2D ); - glDisable( GL_DEPTH_TEST ); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + glPushAttrib( GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_POLYGON_BIT ); + glDisable( GL_LIGHTING ); + glEnable( GL_TEXTURE_2D ); + glDisable( GL_DEPTH_TEST ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); - glBindTexture( GL_TEXTURE_2D, m_atlas ); - GlobalOpenGL().m_glListBase( m_displayList ); - GlobalOpenGL().m_glCallLists( GLsizei( strlen( s ) ), GL_UNSIGNED_BYTE, reinterpret_cast( s ) ); + glBindTexture( GL_TEXTURE_2D, m_atlas ); + GlobalOpenGL().m_glListBase( m_displayList ); + GlobalOpenGL().m_glCallLists( GLsizei( strlen( s ) ), GL_UNSIGNED_BYTE, reinterpret_cast( s ) ); - glPopAttrib(); + glPopAttrib(); - glMatrixMode( GL_PROJECTION ); - glPopMatrix(); - glMatrixMode( GL_MODELVIEW ); //! must leave GL_MODELVIEW mode, as renderer relies on this during Renderer.render() - glPopMatrix(); -} - -void renderString( const char *s, const GLuint& tex, const unsigned char colour[3], unsigned int& wid, unsigned int& hei ){ - if( !m_ft2_context || m_pixelHeight == 0 ){ - wid = hei = 0; - return; + glMatrixMode( GL_PROJECTION ); + glPopMatrix(); + glMatrixMode( GL_MODELVIEW ); //! must leave GL_MODELVIEW mode, as renderer relies on this during Renderer.render() + glPopMatrix(); } - PangoLayout *layout; - PangoRectangle log_rect; - FT_Bitmap bitmap; + void renderString( const char *s, const GLuint& tex, const unsigned char colour[3], unsigned int& wid, unsigned int& hei ){ + if( !m_ft2_context || m_pixelHeight == 0 ){ + wid = hei = 0; + return; + } - layout = pango_layout_new( m_ft2_context ); - pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. - pango_layout_set_text( layout, s, -1 ); // -1 null-terminated string. - pango_layout_get_extents( layout, NULL, &log_rect ); + PangoLayout *layout; + PangoRectangle log_rect; + FT_Bitmap bitmap; - if ( log_rect.width > 0 && log_rect.height > 0 ) { - hei = bitmap.rows = PANGO_PIXELS_CEIL( log_rect.height );//m_pixelAscent + m_pixelDescent; - wid = bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); -// globalOutputStream() << wid << " " << hei << " rendering\n"; - bitmap.pitch = bitmap.width; - unsigned char *boo = (unsigned char *) malloc( bitmap.rows * bitmap.width ); - memset( boo, 0, bitmap.rows * bitmap.width ); - bitmap.buffer = boo; - bitmap.num_grays = 0xff; - bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; - pango_ft2_render_layout_subpixel( &bitmap, layout, -log_rect.x, 0 ); + layout = pango_layout_new( m_ft2_context ); + pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. + pango_layout_set_text( layout, s, -1 ); // -1 null-terminated string. + pango_layout_get_extents( layout, NULL, &log_rect ); - hei += 2; - wid += 2; - unsigned char *buf = (unsigned char *) malloc( 4 * hei * wid ); - memset( buf, 0x00, 4 * hei * wid ); + if ( log_rect.width > 0 && log_rect.height > 0 ) { + hei = bitmap.rows = PANGO_PIXELS_CEIL( log_rect.height );//m_pixelAscent + m_pixelDescent; + wid = bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); +// globalOutputStream() << wid << " " << hei << " rendering\n"; + bitmap.pitch = bitmap.width; + unsigned char *boo = (unsigned char *) malloc( bitmap.rows * bitmap.width ); + memset( boo, 0, bitmap.rows * bitmap.width ); + bitmap.buffer = boo; + bitmap.num_grays = 0xff; + bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; + pango_ft2_render_layout_subpixel( &bitmap, layout, -log_rect.x, 0 ); + + hei += 2; + wid += 2; + unsigned char *buf = (unsigned char *) malloc( 4 * hei * wid ); + memset( buf, 0x00, 4 * hei * wid ); #if 0 - GLfloat color[4] = { 1, 0, 0, 1 }; - guint32 rgb = ( ( ( guint32 )( color[0] * 255.0 ) ) << 24 ) | - ( ( ( guint32 )( color[1] * 255.0 ) ) << 16 ) | - ( ( ( guint32 )( color[2] * 255.0 ) ) << 8 ); + GLfloat color[4] = { 1, 0, 0, 1 }; + guint32 rgb = ( ( ( guint32 )( color[0] * 255.0 ) ) << 24 ) | + ( ( ( guint32 )( color[1] * 255.0 ) ) << 16 ) | + ( ( ( guint32 )( color[2] * 255.0 ) ) << 8 ); - GLfloat a = color[3]; + GLfloat a = color[3]; - guint32 *t; - guint8 *row, *row_end; - row = bitmap.buffer + bitmap.rows * bitmap.width; /* past-the-end */ - row_end = bitmap.buffer; /* beginning */ + guint32 *t; + guint8 *row, *row_end; + row = bitmap.buffer + bitmap.rows * bitmap.width; /* past-the-end */ + row_end = bitmap.buffer; /* beginning */ - t = ( guint32* ) buf; + t = ( guint32* ) buf; - if( a == 1.0 ) { - do { - row -= bitmap.width; - for( unsigned int i = 0; i < bitmap.width; i++ ) - *t++ = rgb | ( ( guint32 ) row[i] ); + if( a == 1.0 ) { + do { + row -= bitmap.width; + for( unsigned int i = 0; i < bitmap.width; i++ ) + *t++ = rgb | ( ( guint32 ) row[i] ); - } while( row != row_end ); - } else - { - do + } while( row != row_end ); + } else { - row -= bitmap.width; - for( unsigned int i = 0; i < bitmap.width; i++ ) - * t++ = rgb | ( ( guint32 )( a* row[i] ) ); - } while( row != row_end ); - } + do + { + row -= bitmap.width; + for( unsigned int i = 0; i < bitmap.width; i++ ) + * t++ = rgb | ( ( guint32 )( a* row[i] ) ); + } while( row != row_end ); + } #endif // 0 #if 0 - if( withfond ){ /* with background rectangle */ - const unsigned int x_max = wid; - const unsigned int y_max = hei; - unsigned int x, y, bitmapIter = 0; + if( withfond ){ /* with background rectangle */ + const unsigned int x_max = wid; + const unsigned int y_max = hei; + unsigned int x, y, bitmapIter = 0; - const unsigned char fontColorR = 255; - const unsigned char fontColorG = 255; - const unsigned char fontColorB = 0; + const unsigned char fontColorR = 255; + const unsigned char fontColorG = 255; + const unsigned char fontColorB = 0; - const unsigned char backgroundColorR = 64; - const unsigned char backgroundColorG = 64; - const unsigned char backgroundColorB = 64; + const unsigned char backgroundColorR = 64; + const unsigned char backgroundColorG = 64; + const unsigned char backgroundColorB = 64; - for( y = 0; y < y_max; y++ ) { - for( x = 0; x < x_max; x++ ) { - const unsigned int iter = ( y * x_max + x ) * 4; - if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { - buf[iter] = backgroundColorB; - buf[iter + 1] = backgroundColorG; - buf[iter + 2] = backgroundColorR; - buf[iter + 3] = 150; /* half trans border */ - continue; + for( y = 0; y < y_max; y++ ) { + for( x = 0; x < x_max; x++ ) { + const unsigned int iter = ( y * x_max + x ) * 4; + if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { + buf[iter] = backgroundColorB; + buf[iter + 1] = backgroundColorG; + buf[iter + 2] = backgroundColorR; + buf[iter + 3] = 150; /* half trans border */ + continue; + } + if( bitmap.buffer[bitmapIter] == 0 ) { + /* Render background color. */ + buf[iter] = backgroundColorB; + buf[iter + 1] = backgroundColorG; + buf[iter + 2] = backgroundColorR; + buf[iter + 3] = 255; + } + else { + /* Calculate alpha (opacity). */ + const float opacity = bitmap.buffer[bitmapIter] / 255.f; + buf[iter] = fontColorB * opacity + ( 1 - opacity ) * backgroundColorB; + buf[iter + 1] = fontColorG * opacity + ( 1 - opacity ) * backgroundColorG; + buf[iter + 2] = fontColorR * opacity + ( 1 - opacity ) * backgroundColorR; + buf[iter + 3] = 255; + } + ++bitmapIter; } - if( bitmap.buffer[bitmapIter] == 0 ) { - /* Render background color. */ - buf[iter] = backgroundColorB; - buf[iter + 1] = backgroundColorG; - buf[iter + 2] = backgroundColorR; - buf[iter + 3] = 255; - } - else { - /* Calculate alpha (opacity). */ - const float opacity = bitmap.buffer[bitmapIter] / 255.f; - buf[iter] = fontColorB * opacity + ( 1 - opacity ) * backgroundColorB; - buf[iter + 1] = fontColorG * opacity + ( 1 - opacity ) * backgroundColorG; - buf[iter + 2] = fontColorR * opacity + ( 1 - opacity ) * backgroundColorR; - buf[iter + 3] = 255; - } - ++bitmapIter; } } - } #elif 0 - if( 1 ){ /* normal with shadow */ - const unsigned int x_max = wid; - const unsigned int y_max = hei; - unsigned int x, y, bitmapIter = 0; + if( 1 ){ /* normal with shadow */ + const unsigned int x_max = wid; + const unsigned int y_max = hei; + unsigned int x, y, bitmapIter = 0; // unsigned char fontColorR = 255; // unsigned char fontColorG = 255; // unsigned char fontColorB = 0; - unsigned char fontColorR = colour[0]; - unsigned char fontColorG = colour[1]; - unsigned char fontColorB = colour[2]; + unsigned char fontColorR = colour[0]; + unsigned char fontColorG = colour[1]; + unsigned char fontColorB = colour[2]; - unsigned char backgroundColorR = 0; - unsigned char backgroundColorG = 0; - unsigned char backgroundColorB = 0; + unsigned char backgroundColorR = 0; + unsigned char backgroundColorG = 0; + unsigned char backgroundColorB = 0; - for( y = 0; y < y_max; y++ ) { - for( x = 0; x < x_max; x++ ) { - const unsigned int iter = ( y * x_max + x ) * 4; - if( x == 0 || y == 0 || x == 1 || y == 1 ) { - buf[iter] = fontColorB; - buf[iter + 1] = fontColorG; - buf[iter + 2] = fontColorR; - buf[iter + 3] = 0; - continue; - } - if( bitmap.buffer[bitmapIter] == 0 ){ - buf[iter] = fontColorB; - buf[iter + 1] = fontColorG; - buf[iter + 2] = fontColorR; - buf[iter + 3] = 0; - } - else{ - buf[iter] = backgroundColorB; - buf[iter + 1] = backgroundColorG; - buf[iter + 2] = backgroundColorR; - buf[iter + 3] = bitmap.buffer[bitmapIter]; - } - ++bitmapIter; - } - } - - bitmapIter = 0; - for( y = 0; y < y_max; y++ ) { - for( x = 0; x < x_max; x++ ) { - const unsigned int iter = ( y * x_max + x ) * 4; - if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { - continue; - } - if( bitmap.buffer[bitmapIter] != 0 ) { - if( buf[iter + 3] == 0 ){ + for( y = 0; y < y_max; y++ ) { + for( x = 0; x < x_max; x++ ) { + const unsigned int iter = ( y * x_max + x ) * 4; + if( x == 0 || y == 0 || x == 1 || y == 1 ) { buf[iter] = fontColorB; buf[iter + 1] = fontColorG; buf[iter + 2] = fontColorR; - buf[iter + 3] = bitmap.buffer[bitmapIter]; + buf[iter + 3] = 0; + continue; + } + if( bitmap.buffer[bitmapIter] == 0 ){ + buf[iter] = fontColorB; + buf[iter + 1] = fontColorG; + buf[iter + 2] = fontColorR; + buf[iter + 3] = 0; } else{ - /* Calculate alpha (opacity). */ - const float opacityFont = bitmap.buffer[bitmapIter] / 255.f; - const float opacityBack = buf[iter + 3] / 255.f; - buf[iter] = fontColorB * opacityFont + ( 1 - opacityFont ) * backgroundColorB; - buf[iter + 1] = fontColorG * opacityFont + ( 1 - opacityFont ) * backgroundColorG; - buf[iter + 2] = fontColorR * opacityFont + ( 1 - opacityFont ) * backgroundColorR; - buf[iter + 3] = ( opacityFont + ( 1 - opacityFont ) * opacityBack ) * 255.f; + buf[iter] = backgroundColorB; + buf[iter + 1] = backgroundColorG; + buf[iter + 2] = backgroundColorR; + buf[iter + 3] = bitmap.buffer[bitmapIter]; } + ++bitmapIter; + } + } + + bitmapIter = 0; + for( y = 0; y < y_max; y++ ) { + for( x = 0; x < x_max; x++ ) { + const unsigned int iter = ( y * x_max + x ) * 4; + if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { + continue; + } + if( bitmap.buffer[bitmapIter] != 0 ) { + if( buf[iter + 3] == 0 ){ + buf[iter] = fontColorB; + buf[iter + 1] = fontColorG; + buf[iter + 2] = fontColorR; + buf[iter + 3] = bitmap.buffer[bitmapIter]; + } + else{ + /* Calculate alpha (opacity). */ + const float opacityFont = bitmap.buffer[bitmapIter] / 255.f; + const float opacityBack = buf[iter + 3] / 255.f; + buf[iter] = fontColorB * opacityFont + ( 1 - opacityFont ) * backgroundColorB; + buf[iter + 1] = fontColorG * opacityFont + ( 1 - opacityFont ) * backgroundColorG; + buf[iter + 2] = fontColorR * opacityFont + ( 1 - opacityFont ) * backgroundColorR; + buf[iter + 3] = ( opacityFont + ( 1 - opacityFont ) * opacityBack ) * 255.f; + } + } + ++bitmapIter; } - ++bitmapIter; } } - } - else{ /* normal */ - const unsigned int x_max = wid; - const unsigned int y_max = hei; - unsigned int x, y, bitmapIter = 0; + else{ /* normal */ + const unsigned int x_max = wid; + const unsigned int y_max = hei; + unsigned int x, y, bitmapIter = 0; -// unsigned char fontColorR = 0; -// unsigned char fontColorG = 255; -// unsigned char fontColorB = 0; - unsigned char fontColorR = colour[0]; - unsigned char fontColorG = colour[1]; - unsigned char fontColorB = colour[2]; +// unsigned char fontColorR = 0; +// unsigned char fontColorG = 255; +// unsigned char fontColorB = 0; + unsigned char fontColorR = colour[0]; + unsigned char fontColorG = colour[1]; + unsigned char fontColorB = colour[2]; - for( y = 0; y < y_max; y++ ) { - for( x = 0; x < x_max; x++ ) { - const unsigned int iter = ( y * x_max + x ) * 4; - if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { + for( y = 0; y < y_max; y++ ) { + for( x = 0; x < x_max; x++ ) { + const unsigned int iter = ( y * x_max + x ) * 4; + if( x == 0 || y == 0 || x == ( x_max - 1 ) || y == ( y_max - 1 ) ) { + buf[iter] = fontColorB; + buf[iter + 1] = fontColorG; + buf[iter + 2] = fontColorR; + buf[iter + 3] = 0; + continue; + } buf[iter] = fontColorB; buf[iter + 1] = fontColorG; buf[iter + 2] = fontColorR; - buf[iter + 3] = 0; - continue; + buf[iter + 3] = bitmap.buffer[bitmapIter]; + ++bitmapIter; } - buf[iter] = fontColorB; - buf[iter + 1] = fontColorG; - buf[iter + 2] = fontColorR; - buf[iter + 3] = bitmap.buffer[bitmapIter]; - ++bitmapIter; } } - } #endif // 0 - //Now we just setup some texture paramaters. - glBindTexture( GL_TEXTURE_2D, tex ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + //Now we just setup some texture paramaters. + glBindTexture( GL_TEXTURE_2D, tex ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); -// glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); - //Here we actually create the texture itself - glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, wid * 3, hei, - 0, GL_BGRA, GL_UNSIGNED_BYTE, 0 ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); +// glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); + //Here we actually create the texture itself + glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, wid * 3, hei, + 0, GL_BGRA, GL_UNSIGNED_BYTE, 0 ); - /* normal with shadow */ - gray_to_texture( wid, hei, bitmap.buffer, buf, colour[0], colour[1], colour[2] ); - glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); + /* normal with shadow */ + gray_to_texture( wid, hei, bitmap.buffer, buf, colour[0], colour[1], colour[2] ); + glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); - memset( buf, 0x00, 4 * hei * wid ); - /* yellow selected with shadow */ - gray_to_texture( wid, hei, bitmap.buffer, buf, 255, 255, 0 ); - glTexSubImage2D( GL_TEXTURE_2D, 0, wid, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); + memset( buf, 0x00, 4 * hei * wid ); + /* yellow selected with shadow */ + gray_to_texture( wid, hei, bitmap.buffer, buf, 255, 255, 0 ); + glTexSubImage2D( GL_TEXTURE_2D, 0, wid, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); - memset( buf, 0x00, 4 * hei * wid ); - /* orange childSelected with shadow */ - gray_to_texture( wid, hei, bitmap.buffer, buf, 255, 128, 0 ); - glTexSubImage2D( GL_TEXTURE_2D, 0, wid * 2, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); + memset( buf, 0x00, 4 * hei * wid ); + /* orange childSelected with shadow */ + gray_to_texture( wid, hei, bitmap.buffer, buf, 255, 128, 0 ); + glTexSubImage2D( GL_TEXTURE_2D, 0, wid * 2, 0, wid, hei, GL_BGRA, GL_UNSIGNED_BYTE, buf ); - glBindTexture( GL_TEXTURE_2D, 0 ); + glBindTexture( GL_TEXTURE_2D, 0 ); - free( buf ); - free( boo ); + free( buf ); + free( boo ); + } + g_object_unref( G_OBJECT( layout ) ); + } + int getPixelAscent() const { + return m_pixelAscent; + } + int getPixelDescent() const { + return m_pixelDescent; + } + int getPixelHeight() const { + return m_pixelHeight; } - g_object_unref( G_OBJECT( layout ) ); -} -int getPixelAscent() const { - return m_pixelAscent; -} -int getPixelDescent() const { - return m_pixelDescent; -} -int getPixelHeight() const { - return m_pixelHeight; -} }; #ifdef _WIN32 - #include +#include #endif #include "debugging/debugging.h" @@ -482,8 +482,8 @@ GLFont *glfont_create( const char* font_string ){ firstbitmap += 256; } -/* *height = fontInfo->ascent + fontInfo->descent; - *width = fontInfo->max_bounds.width; */ + /* *height = fontInfo->ascent + fontInfo->descent; + *width = fontInfo->max_bounds.width; */ return new GLFontCallList( font_list_base, fontInfo->ascent, fontInfo->descent, fontInfo->ascent + fontInfo->descent ); } @@ -544,65 +544,65 @@ GLFont *glfont_create( const char* font_string ){ class GLFontInternal : public GLFont { -const char *font_string; -int font_height; -int font_ascent; -int font_descent; -int y_offset_bitmap_render_pango_units; -PangoContext *ft2_context; -PangoFontMap *fontmap; + const char *font_string; + int font_height; + int font_ascent; + int font_descent; + int y_offset_bitmap_render_pango_units; + PangoContext *ft2_context; + PangoFontMap *fontmap; public: -GLFontInternal( const char *_font_string ) : font_string( _font_string ){ - PangoFontDescription *font_desc; - PangoLayout *layout; - PangoRectangle log_rect; - int font_ascent_pango_units; - int font_descent_pango_units; + GLFontInternal( const char *_font_string ) : font_string( _font_string ){ + PangoFontDescription *font_desc; + PangoLayout *layout; + PangoRectangle log_rect; + int font_ascent_pango_units; + int font_descent_pango_units; #if !PANGO_VERSION_CHECK( 1,22,0 ) - ft2_context = pango_ft2_get_context( 72, 72 ); + ft2_context = pango_ft2_get_context( 72, 72 ); #else - fontmap = pango_ft2_font_map_new(); - pango_ft2_font_map_set_resolution( PANGO_FT2_FONT_MAP( fontmap ), 72, 72 ); - ft2_context = pango_font_map_create_context( fontmap ); + fontmap = pango_ft2_font_map_new(); + pango_ft2_font_map_set_resolution( PANGO_FT2_FONT_MAP( fontmap ), 72, 72 ); + ft2_context = pango_font_map_create_context( fontmap ); #endif - font_desc = pango_font_description_from_string( font_string ); - //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); - pango_context_set_font_description( ft2_context, font_desc ); - pango_font_description_free( font_desc ); - // TODO fallback to fixed 8, courier new 8 + font_desc = pango_font_description_from_string( font_string ); + //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); + pango_context_set_font_description( ft2_context, font_desc ); + pango_font_description_free( font_desc ); + // TODO fallback to fixed 8, courier new 8 - layout = pango_layout_new( ft2_context ); + layout = pango_layout_new( ft2_context ); #ifdef FONT_SIZE_WORKAROUND - pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. - pango_layout_set_text( layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1 ); // -1 null-terminated string. + pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. + pango_layout_set_text( layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1 ); // -1 null-terminated string. #endif #if !PANGO_VERSION_CHECK( 1,22,0 ) - PangoLayoutIter *iter; - iter = pango_layout_get_iter( layout ); - font_ascent_pango_units = pango_layout_iter_get_baseline( iter ); - pango_layout_iter_free( iter ); + PangoLayoutIter *iter; + iter = pango_layout_get_iter( layout ); + font_ascent_pango_units = pango_layout_iter_get_baseline( iter ); + pango_layout_iter_free( iter ); #else - font_ascent_pango_units = pango_layout_get_baseline( layout ); + font_ascent_pango_units = pango_layout_get_baseline( layout ); #endif - pango_layout_get_extents( layout, NULL, &log_rect ); - g_object_unref( G_OBJECT( layout ) ); - font_descent_pango_units = log_rect.height - font_ascent_pango_units; + pango_layout_get_extents( layout, NULL, &log_rect ); + g_object_unref( G_OBJECT( layout ) ); + font_descent_pango_units = log_rect.height - font_ascent_pango_units; - font_ascent = PANGO_PIXELS_CEIL( font_ascent_pango_units ); - font_descent = PANGO_PIXELS_CEIL( font_descent_pango_units ); - font_height = font_ascent + font_descent; - y_offset_bitmap_render_pango_units = ( font_ascent * PANGO_SCALE ) - font_ascent_pango_units; -} + font_ascent = PANGO_PIXELS_CEIL( font_ascent_pango_units ); + font_descent = PANGO_PIXELS_CEIL( font_descent_pango_units ); + font_height = font_ascent + font_descent; + y_offset_bitmap_render_pango_units = ( font_ascent * PANGO_SCALE ) - font_ascent_pango_units; + } -virtual ~GLFontInternal(){ - g_object_unref( G_OBJECT( ft2_context ) ); - g_object_unref( G_OBJECT( fontmap ) ); -} + virtual ~GLFontInternal(){ + g_object_unref( G_OBJECT( ft2_context ) ); + g_object_unref( G_OBJECT( fontmap ) ); + } // Renders the input text at the current location with the current color. // The X position of the current location is used to place the left edge of the text image, @@ -614,88 +614,88 @@ virtual ~GLFontInternal(){ // just a hair outside of the viewport (meaning the current raster position is invalid), // then no text will be rendered. The solution to this is a very hacky one. You can search // Google for "glDrawPixels clipping". -virtual void printString( const char *s ){ - // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. + virtual void printString( const char *s ){ + // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. - PangoLayout *layout; - PangoRectangle log_rect; - FT_Bitmap bitmap; - unsigned char *begin_bitmap_buffer; - GLfloat color[4]; - GLint previous_unpack_alignment; - GLboolean previous_blend_enabled; - GLint previous_blend_func_src; - GLint previous_blend_func_dst; - GLfloat previous_red_bias; - GLfloat previous_green_bias; - GLfloat previous_blue_bias; - GLfloat previous_alpha_scale; + PangoLayout *layout; + PangoRectangle log_rect; + FT_Bitmap bitmap; + unsigned char *begin_bitmap_buffer; + GLfloat color[4]; + GLint previous_unpack_alignment; + GLboolean previous_blend_enabled; + GLint previous_blend_func_src; + GLint previous_blend_func_dst; + GLfloat previous_red_bias; + GLfloat previous_green_bias; + GLfloat previous_blue_bias; + GLfloat previous_alpha_scale; - layout = pango_layout_new( ft2_context ); - pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. - pango_layout_set_text( layout, s, -1 ); // -1 null-terminated string. - pango_layout_get_extents( layout, NULL, &log_rect ); + layout = pango_layout_new( ft2_context ); + pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. + pango_layout_set_text( layout, s, -1 ); // -1 null-terminated string. + pango_layout_get_extents( layout, NULL, &log_rect ); - if ( log_rect.width > 0 && log_rect.height > 0 ) { - bitmap.rows = font_ascent + font_descent; - bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); - bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. - begin_bitmap_buffer = (unsigned char *) g_malloc( bitmap.rows * bitmap.width ); - memset( begin_bitmap_buffer, 0, bitmap.rows * bitmap.width ); - bitmap.buffer = begin_bitmap_buffer + ( bitmap.rows - 1 ) * bitmap.width; // See pitch above. - bitmap.num_grays = 0xff; - bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; - pango_ft2_render_layout_subpixel( &bitmap, layout, -log_rect.x, - y_offset_bitmap_render_pango_units ); - GlobalOpenGL().m_glGetFloatv( GL_CURRENT_COLOR, color ); + if ( log_rect.width > 0 && log_rect.height > 0 ) { + bitmap.rows = font_ascent + font_descent; + bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); + bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. + begin_bitmap_buffer = (unsigned char *) g_malloc( bitmap.rows * bitmap.width ); + memset( begin_bitmap_buffer, 0, bitmap.rows * bitmap.width ); + bitmap.buffer = begin_bitmap_buffer + ( bitmap.rows - 1 ) * bitmap.width; // See pitch above. + bitmap.num_grays = 0xff; + bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; + pango_ft2_render_layout_subpixel( &bitmap, layout, -log_rect.x, + y_offset_bitmap_render_pango_units ); + GlobalOpenGL().m_glGetFloatv( GL_CURRENT_COLOR, color ); - // Save state. I didn't see any OpenGL push/pop operations for these. - // Question: Is saving/restoring this state necessary? Being safe. - GlobalOpenGL().m_glGetIntegerv( GL_UNPACK_ALIGNMENT, &previous_unpack_alignment ); - previous_blend_enabled = GlobalOpenGL().m_glIsEnabled( GL_BLEND ); - GlobalOpenGL().m_glGetIntegerv( GL_BLEND_SRC, &previous_blend_func_src ); - GlobalOpenGL().m_glGetIntegerv( GL_BLEND_DST, &previous_blend_func_dst ); - GlobalOpenGL().m_glGetFloatv( GL_RED_BIAS, &previous_red_bias ); - GlobalOpenGL().m_glGetFloatv( GL_GREEN_BIAS, &previous_green_bias ); - GlobalOpenGL().m_glGetFloatv( GL_BLUE_BIAS, &previous_blue_bias ); - GlobalOpenGL().m_glGetFloatv( GL_ALPHA_SCALE, &previous_alpha_scale ); + // Save state. I didn't see any OpenGL push/pop operations for these. + // Question: Is saving/restoring this state necessary? Being safe. + GlobalOpenGL().m_glGetIntegerv( GL_UNPACK_ALIGNMENT, &previous_unpack_alignment ); + previous_blend_enabled = GlobalOpenGL().m_glIsEnabled( GL_BLEND ); + GlobalOpenGL().m_glGetIntegerv( GL_BLEND_SRC, &previous_blend_func_src ); + GlobalOpenGL().m_glGetIntegerv( GL_BLEND_DST, &previous_blend_func_dst ); + GlobalOpenGL().m_glGetFloatv( GL_RED_BIAS, &previous_red_bias ); + GlobalOpenGL().m_glGetFloatv( GL_GREEN_BIAS, &previous_green_bias ); + GlobalOpenGL().m_glGetFloatv( GL_BLUE_BIAS, &previous_blue_bias ); + GlobalOpenGL().m_glGetFloatv( GL_ALPHA_SCALE, &previous_alpha_scale ); - GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); - GlobalOpenGL().m_glEnable( GL_BLEND ); - GlobalOpenGL().m_glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, color[0] ); - GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, color[1] ); - GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, color[2] ); - GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, color[3] ); + GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); + GlobalOpenGL().m_glEnable( GL_BLEND ); + GlobalOpenGL().m_glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, color[0] ); + GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, color[1] ); + GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, color[2] ); + GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, color[3] ); - GlobalOpenGL().m_glDrawPixels( bitmap.width, bitmap.rows, - GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer ); - g_free( begin_bitmap_buffer ); + GlobalOpenGL().m_glDrawPixels( bitmap.width, bitmap.rows, + GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer ); + g_free( begin_bitmap_buffer ); - // Restore state in reverse order of how we set it. - GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, previous_alpha_scale ); - GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, previous_blue_bias ); - GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, previous_green_bias ); - GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, previous_red_bias ); - GlobalOpenGL().m_glBlendFunc( previous_blend_func_src, previous_blend_func_dst ); - if ( !previous_blend_enabled ) { - GlobalOpenGL().m_glDisable( GL_BLEND ); + // Restore state in reverse order of how we set it. + GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, previous_alpha_scale ); + GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, previous_blue_bias ); + GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, previous_green_bias ); + GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, previous_red_bias ); + GlobalOpenGL().m_glBlendFunc( previous_blend_func_src, previous_blend_func_dst ); + if ( !previous_blend_enabled ) { + GlobalOpenGL().m_glDisable( GL_BLEND ); + } + GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, previous_unpack_alignment ); } - GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, previous_unpack_alignment ); + + g_object_unref( G_OBJECT( layout ) ); } - g_object_unref( G_OBJECT( layout ) ); -} - -virtual int getPixelAscent() const { - return font_ascent; -} -virtual int getPixelDescent() const { - return font_descent; -} -virtual int getPixelHeight() const { - return font_height; -} + virtual int getPixelAscent() const { + return font_ascent; + } + virtual int getPixelDescent() const { + return font_descent; + } + virtual int getPixelHeight() const { + return font_height; + } }; GLFont *glfont_create( const char* font_string ){ @@ -803,7 +803,7 @@ GLFont *glfont_create( const char* font_string ){ //Here we actually create the texture itself void* empty = calloc( font_height * 12 * font_height * 12 * 2, sizeof( GLubyte ) ); glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, font_height * 12, font_height * 12, // riskily assuming, that height >= max width - 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, empty ); + 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, empty ); free( empty ); @@ -812,7 +812,7 @@ GLFont *glfont_create( const char* font_string ){ pango_layout_get_extents( layout, NULL, &log_rect ); if ( log_rect.width > 0 && log_rect.height > 0 - && PANGO_PIXELS_CEIL( log_rect.width ) <= font_height ) { // ensure, that height >= width + && PANGO_PIXELS_CEIL( log_rect.width ) <= font_height ) { // ensure, that height >= width bitmap.rows = PANGO_PIXELS_CEIL( log_rect.height ); bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); bitmap.pitch = bitmap.width; @@ -830,14 +830,14 @@ GLFont *glfont_create( const char* font_string ){ } glTexSubImage2D( GL_TEXTURE_2D, - 0, - c % 12 * font_height, - c / 12 * font_height, - bitmap.width, - bitmap.rows, - GL_LUMINANCE_ALPHA, - GL_UNSIGNED_BYTE, - buf ); + 0, + c % 12 * font_height, + c / 12 * font_height, + bitmap.width, + bitmap.rows, + GL_LUMINANCE_ALPHA, + GL_UNSIGNED_BYTE, + buf ); glNewList( font_list_base + c, GL_COMPILE ); glBegin( GL_QUADS ); diff --git a/libs/gtkutil/glfont.h b/libs/gtkutil/glfont.h index 34998524..6b99076d 100644 --- a/libs/gtkutil/glfont.h +++ b/libs/gtkutil/glfont.h @@ -27,13 +27,13 @@ typedef unsigned int GLuint; class GLFont { public: -virtual int getPixelHeight() const = 0; -virtual int getPixelAscent() const = 0; -virtual int getPixelDescent() const = 0; -virtual void printString( const char *s ) = 0; -virtual void renderString( const char *s, const GLuint& tex, const unsigned char colour[3], unsigned int& wid, unsigned int& hei ) = 0; -virtual ~GLFont(){ -} + virtual int getPixelHeight() const = 0; + virtual int getPixelAscent() const = 0; + virtual int getPixelDescent() const = 0; + virtual void printString( const char *s ) = 0; + virtual void renderString( const char *s, const GLuint& tex, const unsigned char colour[3], unsigned int& wid, unsigned int& hei ) = 0; + virtual ~GLFont(){ + } }; GLFont *glfont_create( const char* font_string ); diff --git a/libs/gtkutil/idledraw.h b/libs/gtkutil/idledraw.h index 6267951d..f6e75870 100644 --- a/libs/gtkutil/idledraw.h +++ b/libs/gtkutil/idledraw.h @@ -28,33 +28,33 @@ class IdleDraw { -Callback m_draw; -unsigned int m_handler; -static gboolean draw( gpointer data ){ - reinterpret_cast( data )->m_draw(); - reinterpret_cast( data )->m_handler = 0; - return FALSE; -} + Callback m_draw; + unsigned int m_handler; + static gboolean draw( gpointer data ){ + reinterpret_cast( data )->m_draw(); + reinterpret_cast( data )->m_handler = 0; + return FALSE; + } public: -IdleDraw( const Callback& draw ) : m_draw( draw ), m_handler( 0 ){ -} -~IdleDraw(){ - if ( m_handler != 0 ) { - g_source_remove( m_handler ); + IdleDraw( const Callback& draw ) : m_draw( draw ), m_handler( 0 ){ } -} -void queueDraw(){ - if ( m_handler == 0 ) { - m_handler = g_idle_add( &draw, this ); + ~IdleDraw(){ + if ( m_handler != 0 ) { + g_source_remove( m_handler ); + } } -} -typedef MemberCaller QueueDrawCaller; + void queueDraw(){ + if ( m_handler == 0 ) { + m_handler = g_idle_add( &draw, this ); + } + } + typedef MemberCaller QueueDrawCaller; -void flush(){ - if ( m_handler != 0 ) { - draw( this ); + void flush(){ + if ( m_handler != 0 ) { + draw( this ); + } } -} }; diff --git a/libs/gtkutil/nonmodal.h b/libs/gtkutil/nonmodal.h index eb79fb60..41985ca8 100644 --- a/libs/gtkutil/nonmodal.h +++ b/libs/gtkutil/nonmodal.h @@ -46,114 +46,114 @@ inline void widget_connect_escape_clear_focus_widget( GtkWidget* widget ){ class NonModalEntry { -bool m_editing; -Callback m_apply; -Callback m_cancel; + bool m_editing; + Callback m_apply; + Callback m_cancel; -static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ - self->m_editing = false; - return FALSE; -} - -static gboolean focus_out( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ - if ( self->m_editing && gtk_widget_get_visible( GTK_WIDGET( entry ) ) ) { - self->m_apply(); - } - self->m_editing = false; - return FALSE; -} - -static gboolean changed( GtkEntry* entry, NonModalEntry* self ){ - self->m_editing = true; - return FALSE; -} - -static gboolean enter( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ - if ( event->keyval == GDK_KEY_Return ) { - self->m_apply(); + static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ self->m_editing = false; - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); - return TRUE; + return FALSE; } - return FALSE; -} -static gboolean escape( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ - if ( event->keyval == GDK_KEY_Escape ) { - self->m_cancel(); + static gboolean focus_out( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ + if ( self->m_editing && gtk_widget_get_visible( GTK_WIDGET( entry ) ) ) { + self->m_apply(); + } self->m_editing = false; - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); - return TRUE; + return FALSE; + } + + static gboolean changed( GtkEntry* entry, NonModalEntry* self ){ + self->m_editing = true; + return FALSE; + } + + static gboolean enter( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ + if ( event->keyval == GDK_KEY_Return ) { + self->m_apply(); + self->m_editing = false; + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); + return TRUE; + } + return FALSE; + } + + static gboolean escape( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ + if ( event->keyval == GDK_KEY_Escape ) { + self->m_cancel(); + self->m_editing = false; + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); + return TRUE; + } + return FALSE; } - return FALSE; -} public: -NonModalEntry( const Callback& apply, const Callback& cancel ) : m_editing( false ), m_apply( apply ), m_cancel( cancel ){ -} -void connect( GtkEntry* entry ){ - g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); - g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( focus_out ), this ); - g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( enter ), this ); - g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( escape ), this ); - g_signal_connect( G_OBJECT( entry ), "changed", G_CALLBACK( changed ), this ); -} + NonModalEntry( const Callback& apply, const Callback& cancel ) : m_editing( false ), m_apply( apply ), m_cancel( cancel ){ + } + void connect( GtkEntry* entry ){ + g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( focus_out ), this ); + g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( enter ), this ); + g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( escape ), this ); + g_signal_connect( G_OBJECT( entry ), "changed", G_CALLBACK( changed ), this ); + } }; class NonModalSpinner { -Callback m_apply; -Callback m_cancel; + Callback m_apply; + Callback m_cancel; -static gboolean changed( GtkSpinButton* spin, NonModalSpinner* self ){ - self->m_apply(); - return FALSE; -} - -static gboolean enter( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ - if ( event->keyval == GDK_KEY_Return ) { - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); - return TRUE; + static gboolean changed( GtkSpinButton* spin, NonModalSpinner* self ){ + self->m_apply(); + return FALSE; } - return FALSE; -} -static gboolean escape( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ - if ( event->keyval == GDK_KEY_Escape ) { - self->m_cancel(); - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); - return TRUE; + static gboolean enter( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ + if ( event->keyval == GDK_KEY_Return ) { + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); + return TRUE; + } + return FALSE; + } + + static gboolean escape( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ + if ( event->keyval == GDK_KEY_Escape ) { + self->m_cancel(); + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); + return TRUE; + } + return FALSE; } - return FALSE; -} public: -NonModalSpinner( const Callback& apply, const Callback& cancel ) : m_apply( apply ), m_cancel( cancel ){ -} -void connect( GtkSpinButton* spin ){ - guint handler = g_signal_connect( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), "value_changed", G_CALLBACK( changed ), this ); - g_object_set_data( G_OBJECT( spin ), "handler", gint_to_pointer( handler ) ); - g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( enter ), this ); - g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( escape ), this ); -} + NonModalSpinner( const Callback& apply, const Callback& cancel ) : m_apply( apply ), m_cancel( cancel ){ + } + void connect( GtkSpinButton* spin ){ + guint handler = g_signal_connect( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), "value_changed", G_CALLBACK( changed ), this ); + g_object_set_data( G_OBJECT( spin ), "handler", gint_to_pointer( handler ) ); + g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( enter ), this ); + g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( escape ), this ); + } }; class NonModalRadio { -Callback m_changed; + Callback m_changed; public: -NonModalRadio( const Callback& changed ) : m_changed( changed ){ -} -void connect( GtkRadioButton* radio ){ - GSList* group = gtk_radio_button_get_group( radio ); - for (; group != 0; group = g_slist_next( group ) ) - { - toggle_button_connect_callback( GTK_TOGGLE_BUTTON( group->data ), m_changed ); + NonModalRadio( const Callback& changed ) : m_changed( changed ){ + } + void connect( GtkRadioButton* radio ){ + GSList* group = gtk_radio_button_get_group( radio ); + for (; group != 0; group = g_slist_next( group ) ) + { + toggle_button_connect_callback( GTK_TOGGLE_BUTTON( group->data ), m_changed ); + } } -} }; diff --git a/libs/gtkutil/paned.cpp b/libs/gtkutil/paned.cpp index 8a922101..dacd7209 100644 --- a/libs/gtkutil/paned.cpp +++ b/libs/gtkutil/paned.cpp @@ -29,8 +29,8 @@ class PanedState { public: -float position; -int size; + float position; + int size; }; gboolean hpaned_allocate( GtkWidget* widget, GtkAllocation* allocation, PanedState* paned ){ diff --git a/libs/gtkutil/widget.h b/libs/gtkutil/widget.h index 20a183d1..f2f392a8 100644 --- a/libs/gtkutil/widget.h +++ b/libs/gtkutil/widget.h @@ -56,98 +56,98 @@ inline void widget_toggle_visible( GtkWidget* widget ){ class ToggleItem { -BoolExportCallback m_exportCallback; -typedef std::list ImportCallbacks; -ImportCallbacks m_importCallbacks; + BoolExportCallback m_exportCallback; + typedef std::list ImportCallbacks; + ImportCallbacks m_importCallbacks; public: -ToggleItem( const BoolExportCallback& exportCallback ) : m_exportCallback( exportCallback ){ -} - -void update(){ - for ( ImportCallbacks::iterator i = m_importCallbacks.begin(); i != m_importCallbacks.end(); ++i ) - { - m_exportCallback( *i ); + ToggleItem( const BoolExportCallback& exportCallback ) : m_exportCallback( exportCallback ){ } -} -void addCallback( const BoolImportCallback& callback ){ - m_importCallbacks.push_back( callback ); - m_exportCallback( callback ); -} -typedef MemberCaller1 AddCallbackCaller; + void update(){ + for ( ImportCallbacks::iterator i = m_importCallbacks.begin(); i != m_importCallbacks.end(); ++i ) + { + m_exportCallback( *i ); + } + } + + void addCallback( const BoolImportCallback& callback ){ + m_importCallbacks.push_back( callback ); + m_exportCallback( callback ); + } + typedef MemberCaller1 AddCallbackCaller; }; class ToggleShown { -bool m_shownDeferred; + bool m_shownDeferred; -ToggleShown( const ToggleShown& other ); // NOT COPYABLE -ToggleShown& operator=( const ToggleShown& other ); // NOT ASSIGNABLE + ToggleShown( const ToggleShown& other ); // NOT COPYABLE + ToggleShown& operator=( const ToggleShown& other ); // NOT ASSIGNABLE -static gboolean notify_visible( GtkWidget* widget, gpointer dummy, ToggleShown* self ){ - /* destroy = notify::visible with visible = 0, thus let's filter it out */ - if( gtk_main_level() > 0 ){ //== 0 at destroy time - self->m_shownDeferred = widget_is_visible( self->m_widget ); + static gboolean notify_visible( GtkWidget* widget, gpointer dummy, ToggleShown* self ){ + /* destroy = notify::visible with visible = 0, thus let's filter it out */ + if( gtk_main_level() > 0 ){ //== 0 at destroy time + self->m_shownDeferred = widget_is_visible( self->m_widget ); + } + //globalOutputStream() << "ToggleShown::notify_visible time " << gtk_get_current_event_time() << " visible " << self->m_shownDeferred << "\n"; + self->update(); + return FALSE; + } + static gboolean destroy( GtkWidget* widget, ToggleShown* self ){ + //globalOutputStream() << "ToggleShown::destroy time " << gtk_get_current_event_time() << " visible " << self->m_shownDeferred << "\n"; + //self->m_shownDeferred = widget_is_visible( self->m_widget ); //always 0 at destroy time + self->m_widget = 0; + return FALSE; } -//globalOutputStream() << "ToggleShown::notify_visible time " << gtk_get_current_event_time() << " visible " << self->m_shownDeferred << "\n"; - self->update(); - return FALSE; -} -static gboolean destroy( GtkWidget* widget, ToggleShown* self ){ -//globalOutputStream() << "ToggleShown::destroy time " << gtk_get_current_event_time() << " visible " << self->m_shownDeferred << "\n"; - //self->m_shownDeferred = widget_is_visible( self->m_widget ); //always 0 at destroy time - self->m_widget = 0; - return FALSE; -} public: -GtkWidget* m_widget; -ToggleItem m_item; + GtkWidget* m_widget; + ToggleItem m_item; -ToggleShown( bool shown ) - : m_shownDeferred( shown ), m_widget( 0 ), m_item( ActiveCaller( *this ) ){ -} -void update(){ -//globalOutputStream() << "ToggleShown::update\n"; - m_item.update(); -} -bool active() const { -//globalOutputStream() << "ToggleShown::active\n"; - if ( m_widget == 0 ) { - return m_shownDeferred; + ToggleShown( bool shown ) + : m_shownDeferred( shown ), m_widget( 0 ), m_item( ActiveCaller( *this ) ){ } - else - { - return widget_is_visible( m_widget ); + void update(){ + //globalOutputStream() << "ToggleShown::update\n"; + m_item.update(); } -} -void exportActive( const BoolImportCallback& importCallback ){ -//globalOutputStream() << "ToggleShown::exportActive\n"; - importCallback( active() ); -} -typedef MemberCaller1 ActiveCaller; -void set( bool shown ){ -//globalOutputStream() << "ToggleShown::set\n"; - if ( m_widget == 0 ) { - m_shownDeferred = shown; + bool active() const { + //globalOutputStream() << "ToggleShown::active\n"; + if ( m_widget == 0 ) { + return m_shownDeferred; + } + else + { + return widget_is_visible( m_widget ); + } } - else - { - widget_set_visible( m_widget, shown ); + void exportActive( const BoolImportCallback& importCallback ){ + //globalOutputStream() << "ToggleShown::exportActive\n"; + importCallback( active() ); + } + typedef MemberCaller1 ActiveCaller; + void set( bool shown ){ + //globalOutputStream() << "ToggleShown::set\n"; + if ( m_widget == 0 ) { + m_shownDeferred = shown; + } + else + { + widget_set_visible( m_widget, shown ); + } + } + void toggle(){ + //globalOutputStream() << "ToggleShown::toggle\n"; + widget_toggle_visible( m_widget ); + } + typedef MemberCaller ToggleCaller; + void connect( GtkWidget* widget ){ + //globalOutputStream() << "ToggleShown::connect\n"; + m_widget = widget; + widget_set_visible( m_widget, m_shownDeferred ); + g_signal_connect( G_OBJECT( m_widget ), "notify::visible", G_CALLBACK( notify_visible ), this ); + g_signal_connect( G_OBJECT( m_widget ), "destroy", G_CALLBACK( destroy ), this ); + update(); } -} -void toggle(){ -//globalOutputStream() << "ToggleShown::toggle\n"; - widget_toggle_visible( m_widget ); -} -typedef MemberCaller ToggleCaller; -void connect( GtkWidget* widget ){ -//globalOutputStream() << "ToggleShown::connect\n"; - m_widget = widget; - widget_set_visible( m_widget, m_shownDeferred ); - g_signal_connect( G_OBJECT( m_widget ), "notify::visible", G_CALLBACK( notify_visible ), this ); - g_signal_connect( G_OBJECT( m_widget ), "destroy", G_CALLBACK( destroy ), this ); - update(); -} }; namespace{ @@ -176,23 +176,23 @@ inline void widget_make_default( GtkWidget* widget ){ class WidgetFocusPrinter { -const char* m_name; + const char* m_name; -static gboolean focus_in( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ - globalOutputStream() << self->m_name << " takes focus\n"; - return FALSE; -} -static gboolean focus_out( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ - globalOutputStream() << self->m_name << " loses focus\n"; - return FALSE; -} + static gboolean focus_in( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ + globalOutputStream() << self->m_name << " takes focus\n"; + return FALSE; + } + static gboolean focus_out( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ + globalOutputStream() << self->m_name << " loses focus\n"; + return FALSE; + } public: -WidgetFocusPrinter( const char* name ) : m_name( name ){ -} -void connect( GtkWidget* widget ){ - g_signal_connect( G_OBJECT( widget ), "focus_in_event", G_CALLBACK( focus_in ), this ); - g_signal_connect( G_OBJECT( widget ), "focus_out_event", G_CALLBACK( focus_out ), this ); -} + WidgetFocusPrinter( const char* name ) : m_name( name ){ + } + void connect( GtkWidget* widget ){ + g_signal_connect( G_OBJECT( widget ), "focus_in_event", G_CALLBACK( focus_in ), this ); + g_signal_connect( G_OBJECT( widget ), "focus_out_event", G_CALLBACK( focus_out ), this ); + } }; #endif diff --git a/libs/gtkutil/window.h b/libs/gtkutil/window.h index ed6c5822..4425b826 100644 --- a/libs/gtkutil/window.h +++ b/libs/gtkutil/window.h @@ -75,9 +75,9 @@ inline void window_set_position( GtkWindow* window, const WindowPosition& positi GdkScreen* screen = gdk_screen_get_default(); if ( position.x < 0 - || position.y < 0 - || position.x > gdk_screen_get_width( screen ) - || position.y > gdk_screen_get_height( screen ) ) { + || position.y < 0 + || position.x > gdk_screen_get_width( screen ) + || position.y > gdk_screen_get_height( screen ) ) { gtk_window_set_position( window, GTK_WIN_POS_CENTER_ON_PARENT ); } else @@ -106,62 +106,62 @@ typedef ConstReferenceCaller1m_position = WindowPosition( event->x, event->y, event->width, event->height ); - return FALSE; -} + static gboolean configure( GtkWidget* widget, GdkEventConfigure *event, WindowPositionTracker* self ){ + //globalOutputStream() << "WindowPositionTracker::configure\n"; + self->m_position = WindowPosition( event->x, event->y, event->width, event->height ); + return FALSE; + } public: -WindowPositionTracker() - : m_position( c_default_window_pos ), m_window( 0 ){ -} + WindowPositionTracker() + : m_position( c_default_window_pos ), m_window( 0 ){ + } -void sync( GtkWindow* window ){ -//globalOutputStream() << "WindowPositionTracker::sync\n"; - window_set_position( window, m_position ); -} + void sync( GtkWindow* window ){ + //globalOutputStream() << "WindowPositionTracker::sync\n"; + window_set_position( window, m_position ); + } -void sync(){ - if( m_window ) - sync( m_window ); -} + void sync(){ + if( m_window ) + sync( m_window ); + } -/** need to reapply pos on every hiding to keep wnd pos after hide+show (flickering between two positions, if doing on showing) -this stuff is weird: some wnds, like entity list, keep pos on hide/show... untill you resize them -) -some, like floating xy/cam/groupdialog do not; if you remove glwidget from floating xy - it does xD -if you gtk_window_set_position( window, GTK_WIN_POS_CENTER_ALWAYS ), they do keep it, except of random centering after resizing (ms windows) -but this option doesn't sound healthy; -gtk_window_set_transient_for seems to do some gtk_window_set_position also -old questionable comment on this issue: -workaround for strange gtk behaviour - modifying the contents of a window while it is not visible causes the window position to change without sending a configure_event */ -static gboolean notify_visible( GtkWidget* widget, gpointer dummy, WindowPositionTracker* self ){ - if( !widget_is_visible( GTK_WIDGET( self->m_window ) ) ) - self->sync(); - return FALSE; -} + /** need to reapply pos on every hiding to keep wnd pos after hide+show (flickering between two positions, if doing on showing) + this stuff is weird: some wnds, like entity list, keep pos on hide/show... untill you resize them -) + some, like floating xy/cam/groupdialog do not; if you remove glwidget from floating xy - it does xD + if you gtk_window_set_position( window, GTK_WIN_POS_CENTER_ALWAYS ), they do keep it, except of random centering after resizing (ms windows) + but this option doesn't sound healthy; + gtk_window_set_transient_for seems to do some gtk_window_set_position also + old questionable comment on this issue: + workaround for strange gtk behaviour - modifying the contents of a window while it is not visible causes the window position to change without sending a configure_event */ + static gboolean notify_visible( GtkWidget* widget, gpointer dummy, WindowPositionTracker* self ){ + if( !widget_is_visible( GTK_WIDGET( self->m_window ) ) ) + self->sync(); + return FALSE; + } -void connect( GtkWindow* window ){ -//globalOutputStream() << "WindowPositionTracker::connect\n"; - m_window = window; - sync( window ); - g_signal_connect( G_OBJECT( window ), "configure_event", G_CALLBACK( configure ), this ); - g_signal_connect( G_OBJECT( window ), "notify::visible", G_CALLBACK( notify_visible ), this ); -} + void connect( GtkWindow* window ){ + //globalOutputStream() << "WindowPositionTracker::connect\n"; + m_window = window; + sync( window ); + g_signal_connect( G_OBJECT( window ), "configure_event", G_CALLBACK( configure ), this ); + g_signal_connect( G_OBJECT( window ), "notify::visible", G_CALLBACK( notify_visible ), this ); + } -const WindowPosition& getPosition() const { -//globalOutputStream() << "WindowPositionTracker::getPosition\n"; - return m_position; -} + const WindowPosition& getPosition() const { + //globalOutputStream() << "WindowPositionTracker::getPosition\n"; + return m_position; + } -//hack -void setPosition( const WindowPosition& position ){ -//globalOutputStream() << "WindowPositionTracker::setPosition\n"; - m_position = position; -} + //hack + void setPosition( const WindowPosition& position ){ + //globalOutputStream() << "WindowPositionTracker::setPosition\n"; + m_position = position; + } }; diff --git a/libs/gtkutil/xorrectangle.h b/libs/gtkutil/xorrectangle.h index 9c7791a5..e95cebd6 100644 --- a/libs/gtkutil/xorrectangle.h +++ b/libs/gtkutil/xorrectangle.h @@ -66,18 +66,18 @@ public: const float r = 10.f; switch ( rect.modifier ) { - case rect_t::eSelect: glColor3f( 1.f / r, .5f / r, 0.f ); break; - case rect_t::eDeselect: glColor3f( 0.f, 0.f, 1.f / r ); break; - case rect_t::eToggle: glColor3f( 1.f / r, 1.f / r, 1.f / r ); break; + case rect_t::eSelect: glColor3f( 1.f / r, .5f / r, 0.f ); break; + case rect_t::eDeselect: glColor3f( 0.f, 0.f, 1.f / r ); break; + case rect_t::eToggle: glColor3f( 1.f / r, 1.f / r, 1.f / r ); break; } draw( rect, GL_QUADS ); /* filter to handle bright background */ glBlendFunc( GL_ZERO, GL_SRC_COLOR ); switch ( rect.modifier ) { - case rect_t::eSelect: glColor3f( 1.f, .9f, 0.7f ); break; - case rect_t::eDeselect: glColor3f( 0.8f, 0.8f, 1.f ); break; - case rect_t::eToggle: glColor3f( .8f, .8f, .8f ); break; + case rect_t::eSelect: glColor3f( 1.f, .9f, 0.7f ); break; + case rect_t::eDeselect: glColor3f( 0.8f, 0.8f, 1.f ); break; + case rect_t::eToggle: glColor3f( .8f, .8f, .8f ); break; } draw( rect, GL_QUADS ); /* alpha blend on top */ @@ -85,9 +85,9 @@ public: const float a = .3f; switch ( rect.modifier ) { - case rect_t::eSelect: glColor4f( 1.f, .5f, 0.f, a ); break; - case rect_t::eDeselect: glColor4f( 0.f, 0.f, 1.f, a ); break; - case rect_t::eToggle: glColor4f( 1.f, 1.f, 1.f, a ); break; + case rect_t::eSelect: glColor4f( 1.f, .5f, 0.f, a ); break; + case rect_t::eDeselect: glColor4f( 0.f, 0.f, 1.f, a ); break; + case rect_t::eToggle: glColor4f( 1.f, 1.f, 1.f, a ); break; } draw( rect, GL_QUADS ); diff --git a/libs/imagelib.h b/libs/imagelib.h index c8f6b2ef..bfe278d9 100644 --- a/libs/imagelib.h +++ b/libs/imagelib.h @@ -34,52 +34,52 @@ struct RGBAPixel class RGBAImage : public Image { -RGBAImage( const RGBAImage& other ); -RGBAImage& operator=( const RGBAImage& other ); + RGBAImage( const RGBAImage& other ); + RGBAImage& operator=( const RGBAImage& other ); public: -RGBAPixel* pixels; -unsigned int width, height; + RGBAPixel* pixels; + unsigned int width, height; -RGBAImage( unsigned int _width, unsigned int _height ) - : pixels( new RGBAPixel[_width * _height] ), width( _width ), height( _height ){ -} -virtual ~RGBAImage(){ - delete[] pixels; -} + RGBAImage( unsigned int _width, unsigned int _height ) + : pixels( new RGBAPixel[_width * _height] ), width( _width ), height( _height ){ + } + virtual ~RGBAImage(){ + delete[] pixels; + } -void release(){ - delete this; -} -byte* getRGBAPixels() const { - return reinterpret_cast( pixels ); -} -unsigned int getWidth() const { - return width; -} -unsigned int getHeight() const { - return height; -} + void release(){ + delete this; + } + byte* getRGBAPixels() const { + return reinterpret_cast( pixels ); + } + unsigned int getWidth() const { + return width; + } + unsigned int getHeight() const { + return height; + } }; class RGBAImageFlags : public RGBAImage { public: -int m_surfaceFlags; -int m_contentFlags; -int m_value; -RGBAImageFlags( unsigned short _width, unsigned short _height, int surfaceFlags, int contentFlags, int value ) : - RGBAImage( _width, _height ), m_surfaceFlags( surfaceFlags ), m_contentFlags( contentFlags ), m_value( value ){ -} + int m_surfaceFlags; + int m_contentFlags; + int m_value; + RGBAImageFlags( unsigned short _width, unsigned short _height, int surfaceFlags, int contentFlags, int value ) : + RGBAImage( _width, _height ), m_surfaceFlags( surfaceFlags ), m_contentFlags( contentFlags ), m_value( value ){ + } -int getSurfaceFlags() const { - return m_surfaceFlags; -} -int getContentFlags() const { - return m_contentFlags; -} -int getValue() const { - return m_value; -} + int getSurfaceFlags() const { + return m_surfaceFlags; + } + int getContentFlags() const { + return m_contentFlags; + } + int getValue() const { + return m_value; + } }; @@ -97,38 +97,38 @@ inline void ArchiveFile_freeBuffer( InputStream::byte_type* buffer ){ class ScopedArchiveBuffer { public: -std::size_t length; -InputStream::byte_type* buffer; + std::size_t length; + InputStream::byte_type* buffer; -ScopedArchiveBuffer( ArchiveFile& file ){ - buffer = ArchiveFile_loadBuffer( file, length ); -} -~ScopedArchiveBuffer(){ - ArchiveFile_freeBuffer( buffer ); -} + ScopedArchiveBuffer( ArchiveFile& file ){ + buffer = ArchiveFile_loadBuffer( file, length ); + } + ~ScopedArchiveBuffer(){ + ArchiveFile_freeBuffer( buffer ); + } }; class PointerInputStream : public InputStream { -const byte* m_read; + const byte* m_read; public: -PointerInputStream( const byte* pointer ) - : m_read( pointer ){ -} -std::size_t read( byte* buffer, std::size_t length ){ - const byte* end = m_read + length; - while ( m_read != end ) - { - *buffer++ = *m_read++; + PointerInputStream( const byte* pointer ) + : m_read( pointer ){ + } + std::size_t read( byte* buffer, std::size_t length ){ + const byte* end = m_read + length; + while ( m_read != end ) + { + *buffer++ = *m_read++; + } + return length; + } + void seek( std::size_t offset ){ + m_read += offset; + } + const byte* get(){ + return m_read; } - return length; -} -void seek( std::size_t offset ){ - m_read += offset; -} -const byte* get(){ - return m_read; -} }; #endif diff --git a/libs/instancelib.h b/libs/instancelib.h index a36a74d9..e4b3bbfe 100644 --- a/libs/instancelib.h +++ b/libs/instancelib.h @@ -33,116 +33,116 @@ class InstanceSubgraphWalker : public scene::Traversable::Walker { -scene::Instantiable::Observer* m_observer; -mutable scene::Path m_path; -mutable Stack m_parent; + scene::Instantiable::Observer* m_observer; + mutable scene::Path m_path; + mutable Stack m_parent; public: -InstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* parent ) - : m_observer( observer ), m_path( path ), m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - m_path.push( makeReference( node ) ); - scene::Instance* instance = Node_getInstantiable( node )->create( m_path, m_parent.top() ); - m_observer->insert( instance ); - Node_getInstantiable( node )->insert( m_observer, m_path, instance ); - m_parent.push( instance ); - return true; -} -void post( scene::Node& node ) const { - m_path.pop(); - m_parent.pop(); -} + InstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* parent ) + : m_observer( observer ), m_path( path ), m_parent( parent ){ + } + bool pre( scene::Node& node ) const { + m_path.push( makeReference( node ) ); + scene::Instance* instance = Node_getInstantiable( node )->create( m_path, m_parent.top() ); + m_observer->insert( instance ); + Node_getInstantiable( node )->insert( m_observer, m_path, instance ); + m_parent.push( instance ); + return true; + } + void post( scene::Node& node ) const { + m_path.pop(); + m_parent.pop(); + } }; class UninstanceSubgraphWalker : public scene::Traversable::Walker { -scene::Instantiable::Observer* m_observer; -mutable scene::Path m_path; + scene::Instantiable::Observer* m_observer; + mutable scene::Path m_path; public: -UninstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& parent ) - : m_observer( observer ), m_path( parent ){ -} -bool pre( scene::Node& node ) const { - m_path.push( makeReference( node ) ); - return true; -} -void post( scene::Node& node ) const { - scene::Instance* instance = Node_getInstantiable( node )->erase( m_observer, m_path ); - m_observer->erase( instance ); - delete instance; - m_path.pop(); -} + UninstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& parent ) + : m_observer( observer ), m_path( parent ){ + } + bool pre( scene::Node& node ) const { + m_path.push( makeReference( node ) ); + return true; + } + void post( scene::Node& node ) const { + scene::Instance* instance = Node_getInstantiable( node )->erase( m_observer, m_path ); + m_observer->erase( instance ); + delete instance; + m_path.pop(); + } }; class InstanceSet : public scene::Traversable::Observer { -typedef std::pair CachePath; + typedef std::pair CachePath; -typedef CachePath key_type; + typedef CachePath key_type; -typedef std::map InstanceMap; -InstanceMap m_instances; + typedef std::map InstanceMap; + InstanceMap m_instances; public: -typedef InstanceMap::iterator iterator; + typedef InstanceMap::iterator iterator; -iterator begin(){ - return m_instances.begin(); -} -iterator end(){ - return m_instances.end(); -} + iterator begin(){ + return m_instances.begin(); + } + iterator end(){ + return m_instances.end(); + } // traverse observer -void insert( scene::Node& child ){ - for ( iterator i = begin(); i != end(); ++i ) - { - Node_traverseSubgraph( child, InstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second, ( *i ).second ) ); - ( *i ).second->boundsChanged(); + void insert( scene::Node& child ){ + for ( iterator i = begin(); i != end(); ++i ) + { + Node_traverseSubgraph( child, InstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second, ( *i ).second ) ); + ( *i ).second->boundsChanged(); + } } -} -void erase( scene::Node& child ){ - for ( iterator i = begin(); i != end(); ++i ) - { - Node_traverseSubgraph( child, UninstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second ) ); - ( *i ).second->boundsChanged(); + void erase( scene::Node& child ){ + for ( iterator i = begin(); i != end(); ++i ) + { + Node_traverseSubgraph( child, UninstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second ) ); + ( *i ).second->boundsChanged(); + } } -} // instance -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - for ( iterator i = begin(); i != end(); ++i ) - { - visitor.visit( *( *i ).second ); + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + for ( iterator i = begin(); i != end(); ++i ) + { + visitor.visit( *( *i ).second ); + } } -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - const bool inserted = m_instances.insert( InstanceMap::value_type( key_type( observer, PathConstReference( instance->path() ) ), instance ) ).second; - ASSERT_MESSAGE( inserted, "InstanceSet::insert - element already exists" ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - InstanceMap::iterator i = m_instances.find( key_type( observer, PathConstReference( path ) ) ); - ASSERT_MESSAGE( i != m_instances.end(), "InstanceSet::erase - failed to find element" ); - scene::Instance* instance = i->second; - m_instances.erase( i ); - return instance; -} + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + const bool inserted = m_instances.insert( InstanceMap::value_type( key_type( observer, PathConstReference( instance->path() ) ), instance ) ).second; + ASSERT_MESSAGE( inserted, "InstanceSet::insert - element already exists" ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + InstanceMap::iterator i = m_instances.find( key_type( observer, PathConstReference( path ) ) ); + ASSERT_MESSAGE( i != m_instances.end(), "InstanceSet::erase - failed to find element" ); + scene::Instance* instance = i->second; + m_instances.erase( i ); + return instance; + } -void transformChanged(){ - for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) - { - ( *i ).second->transformChanged(); + void transformChanged(){ + for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) + { + ( *i ).second->transformChanged(); + } } -} -typedef MemberCaller TransformChangedCaller; -void boundsChanged(){ - for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) - { - ( *i ).second->boundsChanged(); + typedef MemberCaller TransformChangedCaller; + void boundsChanged(){ + for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) + { + ( *i ).second->boundsChanged(); + } } -} -typedef MemberCaller BoundsChangedCaller; + typedef MemberCaller BoundsChangedCaller; }; template @@ -157,19 +157,19 @@ template class InstanceEvaluateTransform { public: -inline void operator()( scene::Instance& instance ) const { - InstanceTypeCast::cast( instance )->evaluateTransform(); -} + inline void operator()( scene::Instance& instance ) const { + InstanceTypeCast::cast( instance )->evaluateTransform(); + } }; template class InstanceSetEvaluateTransform { public: -static void apply( InstanceSet& instances ){ - InstanceSet_forEach( instances, InstanceEvaluateTransform() ); -} -typedef ReferenceCaller::apply> Caller; + static void apply( InstanceSet& instances ){ + InstanceSet_forEach( instances, InstanceEvaluateTransform() ); + } + typedef ReferenceCaller::apply> Caller; }; #endif diff --git a/libs/maplib.h b/libs/maplib.h index 07da39dc..4c411128 100644 --- a/libs/maplib.h +++ b/libs/maplib.h @@ -36,192 +36,192 @@ class NameableString : public Nameable { -CopiedString m_name; + CopiedString m_name; public: -NameableString( const char* name ) - : m_name( name ){ -} + NameableString( const char* name ) + : m_name( name ){ + } -const char* name() const { - return m_name.c_str(); -} -void attach( const NameCallback& callback ){ -} -void detach( const NameCallback& callback ){ -} + const char* name() const { + return m_name.c_str(); + } + void attach( const NameCallback& callback ){ + } + void detach( const NameCallback& callback ){ + } }; class UndoFileChangeTracker : public UndoTracker, public MapFile { -std::size_t m_size; -std::size_t m_saved; -typedef void ( UndoFileChangeTracker::*Pending )(); -Pending m_pending; -Callback m_changed; + std::size_t m_size; + std::size_t m_saved; + typedef void ( UndoFileChangeTracker::*Pending )(); + Pending m_pending; + Callback m_changed; public: -UndoFileChangeTracker() : m_size( 0 ), m_saved( MAPFILE_MAX_CHANGES ), m_pending( 0 ){ -} -void print(){ - globalOutputStream() << "saved: " << Unsigned( m_saved ) << " size: " << Unsigned( m_size ) << "\n"; -} - -void push(){ - ++m_size; - m_changed(); - //print(); -} -void pop(){ - --m_size; - m_changed(); - //print(); -} -void pushOperation(){ - if ( m_size < m_saved ) { - // redo queue has been flushed.. it is now impossible to get back to the saved state via undo/redo - m_saved = MAPFILE_MAX_CHANGES; + UndoFileChangeTracker() : m_size( 0 ), m_saved( MAPFILE_MAX_CHANGES ), m_pending( 0 ){ } - push(); -} -void clear(){ - m_size = 0; - m_changed(); - //print(); -} -void begin(){ - m_pending = Pending( &UndoFileChangeTracker::pushOperation ); -} -void undo(){ - m_pending = Pending( &UndoFileChangeTracker::pop ); -} -void redo(){ - m_pending = Pending( &UndoFileChangeTracker::push ); -} - -void changed(){ - if ( m_pending != 0 ) { - ( ( *this ).*m_pending )(); - m_pending = 0; + void print(){ + globalOutputStream() << "saved: " << Unsigned( m_saved ) << " size: " << Unsigned( m_size ) << "\n"; } -} -void save(){ - m_saved = m_size; - m_changed(); -} -bool saved() const { - return m_saved == m_size; -} + void push(){ + ++m_size; + m_changed(); + //print(); + } + void pop(){ + --m_size; + m_changed(); + //print(); + } + void pushOperation(){ + if ( m_size < m_saved ) { + // redo queue has been flushed.. it is now impossible to get back to the saved state via undo/redo + m_saved = MAPFILE_MAX_CHANGES; + } + push(); + } + void clear(){ + m_size = 0; + m_changed(); + //print(); + } + void begin(){ + m_pending = Pending( &UndoFileChangeTracker::pushOperation ); + } + void undo(){ + m_pending = Pending( &UndoFileChangeTracker::pop ); + } + void redo(){ + m_pending = Pending( &UndoFileChangeTracker::push ); + } -void setChangedCallback( const Callback& changed ){ - m_changed = changed; - m_changed(); -} + void changed(){ + if ( m_pending != 0 ) { + ( ( *this ).*m_pending )(); + m_pending = 0; + } + } -std::size_t changes() const { - return m_size; -} + void save(){ + m_saved = m_size; + m_changed(); + } + bool saved() const { + return m_saved == m_size; + } + + void setChangedCallback( const Callback& changed ){ + m_changed = changed; + m_changed(); + } + + std::size_t changes() const { + return m_size; + } }; class MapRoot : public scene::Node::Symbiot, public scene::Instantiable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; + + scene::Node m_node; + IdentityTransform m_transform; + TraversableNodeSet m_traverse; + InstanceSet m_instances; + typedef SelectableInstance Instance; + NameableString m_name; + UndoFileChangeTracker m_changeTracker; public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + typedef LazyStatic StaticTypeCasts; -scene::Node m_node; -IdentityTransform m_transform; -TraversableNodeSet m_traverse; -InstanceSet m_instances; -typedef SelectableInstance Instance; -NameableString m_name; -UndoFileChangeTracker m_changeTracker; -public: -typedef LazyStatic StaticTypeCasts; - -scene::Traversable& get( NullType){ - return m_traverse; -} -TransformNode& get( NullType){ - return m_transform; -} -Nameable& get( NullType){ - return m_name; -} -MapFile& get( NullType){ - return m_changeTracker; -} - -MapRoot( const char* name ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_name( name ){ - m_node.m_isRoot = true; - - m_traverse.attach( this ); - - GlobalUndoSystem().trackerAttach( m_changeTracker ); -} -~MapRoot(){ -} -void release(){ - GlobalUndoSystem().trackerDetach( m_changeTracker ); - - m_traverse.detach( this ); - delete this; -} -scene::Node& node(){ - return m_node; -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + scene::Traversable& get( NullType){ + return m_traverse; } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + TransformNode& get( NullType){ + return m_transform; + } + Nameable& get( NullType){ + return m_name; + } + MapFile& get( NullType){ + return m_changeTracker; } -} -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + MapRoot( const char* name ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_name( name ){ + m_node.m_isRoot = true; -scene::Node& clone() const { - return ( new MapRoot( *this ) )->node(); -} + m_traverse.attach( this ); -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new Instance( path, parent ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); - instanceAttach( path ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - instanceDetach( path ); - return m_instances.erase( observer, path ); -} + GlobalUndoSystem().trackerAttach( m_changeTracker ); + } + ~MapRoot(){ + } + void release(){ + GlobalUndoSystem().trackerDetach( m_changeTracker ); + + m_traverse.detach( this ); + delete this; + } + scene::Node& node(){ + return m_node; + } + + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + } + } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + } + } + + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } + + scene::Node& clone() const { + return ( new MapRoot( *this ) )->node(); + } + + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new Instance( path, parent ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + instanceAttach( path ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + instanceDetach( path ); + return m_instances.erase( observer, path ); + } }; inline void MapRoot_construct(){ diff --git a/libs/math/aabb.h b/libs/math/aabb.h index 7d5135af..17056138 100644 --- a/libs/math/aabb.h +++ b/libs/math/aabb.h @@ -31,13 +31,13 @@ class AABB { public: -Vector3 origin, extents; + Vector3 origin, extents; -AABB() : origin( 0, 0, 0 ), extents( -1,-1,-1 ){ -} -AABB( const Vector3& origin_, const Vector3& extents_ ) : - origin( origin_ ), extents( extents_ ){ -} + AABB() : origin( 0, 0, 0 ), extents( -1,-1,-1 ){ + } + AABB( const Vector3& origin_, const Vector3& extents_ ) : + origin( origin_ ), extents( extents_ ){ + } }; const float c_aabb_max = FLT_MAX; @@ -52,11 +52,11 @@ inline bool origin_valid( float f ){ inline bool aabb_valid( const AABB& aabb ){ return origin_valid( aabb.origin[0] ) - && origin_valid( aabb.origin[1] ) - && origin_valid( aabb.origin[2] ) - && extents_valid( aabb.extents[0] ) - && extents_valid( aabb.extents[1] ) - && extents_valid( aabb.extents[2] ); + && origin_valid( aabb.origin[1] ) + && origin_valid( aabb.origin[2] ) + && extents_valid( aabb.extents[0] ) + && extents_valid( aabb.extents[1] ) + && extents_valid( aabb.extents[2] ); } inline AABB aabb_for_minmax( const Vector3& min, const Vector3& max ){ @@ -70,29 +70,29 @@ template class AABBExtend { public: -static void apply( AABB& aabb, const Vector3& point ){ - float displacement = point[Index::VALUE] - aabb.origin[Index::VALUE]; - float half_difference = static_cast( 0.5 * ( fabs( displacement ) - aabb.extents[Index::VALUE] ) ); - if ( half_difference > 0.0f ) { - aabb.origin[Index::VALUE] += ( displacement >= 0.0f ) ? half_difference : -half_difference; - aabb.extents[Index::VALUE] += half_difference; - } -} -static void apply( AABB& aabb, const AABB& other ){ - float displacement = other.origin[Index::VALUE] - aabb.origin[Index::VALUE]; - float difference = other.extents[Index::VALUE] - aabb.extents[Index::VALUE]; - if ( fabs( displacement ) > fabs( difference ) ) { - float half_difference = static_cast( 0.5 * ( fabs( displacement ) + difference ) ); + static void apply( AABB& aabb, const Vector3& point ){ + float displacement = point[Index::VALUE] - aabb.origin[Index::VALUE]; + float half_difference = static_cast( 0.5 * ( fabs( displacement ) - aabb.extents[Index::VALUE] ) ); if ( half_difference > 0.0f ) { aabb.origin[Index::VALUE] += ( displacement >= 0.0f ) ? half_difference : -half_difference; aabb.extents[Index::VALUE] += half_difference; } } - else if ( difference > 0.0f ) { - aabb.origin[Index::VALUE] = other.origin[Index::VALUE]; - aabb.extents[Index::VALUE] = other.extents[Index::VALUE]; + static void apply( AABB& aabb, const AABB& other ){ + float displacement = other.origin[Index::VALUE] - aabb.origin[Index::VALUE]; + float difference = other.extents[Index::VALUE] - aabb.extents[Index::VALUE]; + if ( fabs( displacement ) > fabs( difference ) ) { + float half_difference = static_cast( 0.5 * ( fabs( displacement ) + difference ) ); + if ( half_difference > 0.0f ) { + aabb.origin[Index::VALUE] += ( displacement >= 0.0f ) ? half_difference : -half_difference; + aabb.extents[Index::VALUE] += half_difference; + } + } + else if ( difference > 0.0f ) { + aabb.origin[Index::VALUE] = other.origin[Index::VALUE]; + aabb.extents[Index::VALUE] = other.extents[Index::VALUE]; + } } -} }; inline void aabb_extend_by_point( AABB& aabb, const Vector3& point ){ @@ -114,13 +114,13 @@ inline void aabb_extend_by_point_safe( AABB& aabb, const Vector3& point ){ class AABBExtendByPoint { -AABB& m_aabb; + AABB& m_aabb; public: -AABBExtendByPoint( AABB& aabb ) : m_aabb( aabb ){ -} -void operator()( const Vector3& point ) const { - aabb_extend_by_point_safe( m_aabb, point ); -} + AABBExtendByPoint( AABB& aabb ) : m_aabb( aabb ){ + } + void operator()( const Vector3& point ) const { + aabb_extend_by_point_safe( m_aabb, point ); + } }; inline void aabb_extend_by_aabb( AABB& aabb, const AABB& other ){ @@ -152,8 +152,8 @@ inline bool aabb_intersects_point_dimension( const AABB& aabb, const Vector3& po inline bool aabb_intersects_point( const AABB& aabb, const Vector3& point ){ return aabb_intersects_point_dimension< IntegralConstant<0> >( aabb, point ) - && aabb_intersects_point_dimension< IntegralConstant<1> >( aabb, point ) - && aabb_intersects_point_dimension< IntegralConstant<2> >( aabb, point ); + && aabb_intersects_point_dimension< IntegralConstant<1> >( aabb, point ) + && aabb_intersects_point_dimension< IntegralConstant<2> >( aabb, point ); } template @@ -163,16 +163,16 @@ inline bool aabb_intersects_aabb_dimension( const AABB& aabb, const AABB& other inline bool aabb_intersects_aabb( const AABB& aabb, const AABB& other ){ return aabb_intersects_aabb_dimension< IntegralConstant<0> >( aabb, other ) - && aabb_intersects_aabb_dimension< IntegralConstant<1> >( aabb, other ) - && aabb_intersects_aabb_dimension< IntegralConstant<2> >( aabb, other ); + && aabb_intersects_aabb_dimension< IntegralConstant<1> >( aabb, other ) + && aabb_intersects_aabb_dimension< IntegralConstant<2> >( aabb, other ); } inline unsigned int aabb_classify_plane( const AABB& aabb, const Plane3& plane ){ double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); - if ( fabs( distance_origin ) < ( fabs( plane.a * aabb.extents[0] ) - + fabs( plane.b * aabb.extents[1] ) - + fabs( plane.c * aabb.extents[2] ) ) ) { + if ( fabs( distance_origin ) < ( fabs( plane.a * aabb.extents[0] ) + + fabs( plane.b * aabb.extents[1] ) + + fabs( plane.c * aabb.extents[2] ) ) ) { return 1; // partially inside } else if ( distance_origin < 0 ) { @@ -184,9 +184,9 @@ inline unsigned int aabb_classify_plane( const AABB& aabb, const Plane3& plane ) inline unsigned int aabb_oriented_classify_plane( const AABB& aabb, const Matrix4& transform, const Plane3& plane ){ double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); - if ( fabs( distance_origin ) < ( fabs( aabb.extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( transform.x() ) ) ) - + fabs( aabb.extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( transform.y() ) ) ) - + fabs( aabb.extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( transform.z() ) ) ) ) ) { + if ( fabs( distance_origin ) < ( fabs( aabb.extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( transform.x() ) ) ) + + fabs( aabb.extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( transform.y() ) ) ) + + fabs( aabb.extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( transform.z() ) ) ) ) ) { return 1; // partially inside } else if ( distance_origin < 0 ) { @@ -268,19 +268,19 @@ const float aabb_texcoord_botright[2] = { 1, 1 }; inline AABB aabb_for_oriented_aabb( const AABB& aabb, const Matrix4& transform ){ return AABB( - matrix4_transformed_point( transform, aabb.origin ), - Vector3( - static_cast( fabs( transform[0] * aabb.extents[0] ) - + fabs( transform[4] * aabb.extents[1] ) - + fabs( transform[8] * aabb.extents[2] ) ), - static_cast( fabs( transform[1] * aabb.extents[0] ) - + fabs( transform[5] * aabb.extents[1] ) - + fabs( transform[9] * aabb.extents[2] ) ), - static_cast( fabs( transform[2] * aabb.extents[0] ) - + fabs( transform[6] * aabb.extents[1] ) - + fabs( transform[10] * aabb.extents[2] ) ) - ) - ); + matrix4_transformed_point( transform, aabb.origin ), + Vector3( + static_cast( fabs( transform[0] * aabb.extents[0] ) + + fabs( transform[4] * aabb.extents[1] ) + + fabs( transform[8] * aabb.extents[2] ) ), + static_cast( fabs( transform[1] * aabb.extents[0] ) + + fabs( transform[5] * aabb.extents[1] ) + + fabs( transform[9] * aabb.extents[2] ) ), + static_cast( fabs( transform[2] * aabb.extents[0] ) + + fabs( transform[6] * aabb.extents[1] ) + + fabs( transform[10] * aabb.extents[2] ) ) + ) + ); } inline AABB aabb_for_oriented_aabb_safe( const AABB& aabb, const Matrix4& transform ){ diff --git a/libs/math/curve.h b/libs/math/curve.h index 1ba7b5e7..62c4a865 100644 --- a/libs/math/curve.h +++ b/libs/math/curve.h @@ -156,9 +156,9 @@ inline Vector3 CubicBezier_evaluate( const Vector3* firstPoint, double t ){ inline Vector3 CubicBezier_evaluateMid( const Vector3* firstPoint ){ return vector3_scaled( firstPoint[0], 0.125 ) - + vector3_scaled( firstPoint[1], 0.375 ) - + vector3_scaled( firstPoint[2], 0.375 ) - + vector3_scaled( firstPoint[3], 0.125 ); + + vector3_scaled( firstPoint[1], 0.375 ) + + vector3_scaled( firstPoint[2], 0.375 ) + + vector3_scaled( firstPoint[3], 0.125 ); } inline Vector3 CatmullRom_evaluate( const ControlPoints& controlPoints, double t ){ @@ -181,11 +181,11 @@ inline Vector3 CatmullRom_evaluate( const ControlPoints& controlPoints, double t Vector3 bezierPoints[4]; bezierPoints[0] = controlPoints[segment]; bezierPoints[1] = ( segment > 0 ) - ? controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment - 1], reciprocal_alpha * 0.5 ) - : controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment], reciprocal_alpha ); + ? controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment - 1], reciprocal_alpha * 0.5 ) + : controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment], reciprocal_alpha ); bezierPoints[2] = ( segment < controlPoints.size() - 2 ) - ? controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 2], reciprocal_alpha * 0.5 ) - : controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 1], reciprocal_alpha ); + ? controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 2], reciprocal_alpha * 0.5 ) + : controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 1], reciprocal_alpha ); bezierPoints[3] = controlPoints[segment + 1]; return CubicBezier_evaluate( bezierPoints, t ); } @@ -195,8 +195,8 @@ typedef Array Knots; inline double BSpline_basis( const Knots& knots, std::size_t i, std::size_t degree, double t ){ if ( degree == 0 ) { if ( knots[i] <= t - && t < knots[i + 1] - && knots[i] < knots[i + 1] ) { + && t < knots[i + 1] + && knots[i] < knots[i + 1] ) { return 1; } return 0; diff --git a/libs/math/expression.cpp b/libs/math/expression.cpp index 13f6bfef..369111e1 100644 --- a/libs/math/expression.cpp +++ b/libs/math/expression.cpp @@ -91,14 +91,14 @@ Vector3 testMatrixMultiplied1( const Vector3& a, const Matrix4& b ){ Vector3 testMatrixMultiplied2( const Vector3& a, const Matrix4& b ){ return vector3_for_expression( - point_multiplied( - vector_added( - vector3_identity( a ), - vector3_literal( Vector3( 1, 0, 0 ) ) - ), - matrix4_identity( b ) - ) - ); + point_multiplied( + vector_added( + vector3_identity( a ), + vector3_literal( Vector3( 1, 0, 0 ) ) + ), + matrix4_identity( b ) + ) + ); } Matrix4 testMatrix4Multiplied1( const Matrix4& a, const Matrix4& b ){ @@ -107,11 +107,11 @@ Matrix4 testMatrix4Multiplied1( const Matrix4& a, const Matrix4& b ){ Matrix4 testMatrix4Multiplied2( const Matrix4& a, const Matrix4& b ){ return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( b ) - ) - ); + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( b ) + ) + ); } Matrix4 testMatrix4AffineMultiplied1( const Matrix4& a, const Matrix4& b ){ @@ -120,11 +120,11 @@ Matrix4 testMatrix4AffineMultiplied1( const Matrix4& a, const Matrix4& b ){ Matrix4 testMatrix4AffineMultiplied2( const Matrix4& a, const Matrix4& b ){ return matrix4_affine_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( b ) - ) - ); + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( b ) + ) + ); } Matrix4 testMatrix4MultipliedConstant1( const Matrix4& a ){ @@ -133,11 +133,11 @@ Matrix4 testMatrix4MultipliedConstant1( const Matrix4& a ){ Matrix4 testMatrix4MultipliedConstant2( const Matrix4& a ){ return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( g_matrix4_identity ) - ) - ); + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( g_matrix4_identity ) + ) + ); } Matrix4 testMatrix4Transposed1( const Matrix4& a ){ return matrix4_transposed( a ); @@ -153,57 +153,57 @@ Vector3 testMulti1( const Matrix4& a, const Vector3& b, const Vector3& c ){ Vector3 testMulti2( const Matrix4& a, const Vector3& b, const Vector3& c ){ return vector3_for_expression( - vector_added( - point_multiplied( - vector3_identity( b ), - matrix_transposed( matrix4_identity( a ) ) - ), - vector3_identity( c ) - ) - ); + vector_added( + point_multiplied( + vector3_identity( b ), + matrix_transposed( matrix4_identity( a ) ) + ), + vector3_identity( c ) + ) + ); } template class TestBinaryFunction { -typedef Value ( *Function )( const First&, const Second& ); -Function m_function; + typedef Value ( *Function )( const First&, const Second& ); + Function m_function; public: -TestBinaryFunction( Function function ) : m_function( function ){ -} -Value run( const First& first, const Second& second ) const { - return m_function( first, second ); -} + TestBinaryFunction( Function function ) : m_function( function ){ + } + Value run( const First& first, const Second& second ) const { + return m_function( first, second ); + } }; template class TestUnaryFunction { -typedef Value ( *Function )( const First& ); -Function m_function; + typedef Value ( *Function )( const First& ); + Function m_function; public: -TestUnaryFunction( Function function ) : m_function( function ){ -} -Value run( const First& first ) const { - return m_function( first ); -} + TestUnaryFunction( Function function ) : m_function( function ){ + } + Value run( const First& first ) const { + return m_function( first ); + } }; class TestAll { public: -TestAll(){ - Vector3 result1 = TestBinaryFunction( testAdded1 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); - Vector3 result2 = TestBinaryFunction( testAdded2 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); - Vector3 result3 = TestBinaryFunction( testMultiplied1 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); - Vector3 result4 = TestBinaryFunction( testMultiplied2 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); - Vector3 result5 = TestBinaryFunction( testScaled1 ).run( Vector3( 1, 2, 3 ), 2.0 ); - Vector3 result6 = TestBinaryFunction( testScaled2 ).run( Vector3( 1, 2, 3 ), 2.0 ); - Vector3 result7 = TestBinaryFunction( testMatrixMultiplied1 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); - Vector3 result8 = TestBinaryFunction( testMatrixMultiplied2 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); - Vector3 result9 = TestUnaryFunction( testNormalised1 ).run( Vector3( 1, 2, 3 ) ); - Vector3 result10 = TestUnaryFunction( testNormalised2 ).run( Vector3( 1, 2, 3 ) ); -} + TestAll(){ + Vector3 result1 = TestBinaryFunction( testAdded1 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); + Vector3 result2 = TestBinaryFunction( testAdded2 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); + Vector3 result3 = TestBinaryFunction( testMultiplied1 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); + Vector3 result4 = TestBinaryFunction( testMultiplied2 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); + Vector3 result5 = TestBinaryFunction( testScaled1 ).run( Vector3( 1, 2, 3 ), 2.0 ); + Vector3 result6 = TestBinaryFunction( testScaled2 ).run( Vector3( 1, 2, 3 ), 2.0 ); + Vector3 result7 = TestBinaryFunction( testMatrixMultiplied1 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); + Vector3 result8 = TestBinaryFunction( testMatrixMultiplied2 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); + Vector3 result9 = TestUnaryFunction( testNormalised1 ).run( Vector3( 1, 2, 3 ) ); + Vector3 result10 = TestUnaryFunction( testNormalised2 ).run( Vector3( 1, 2, 3 ) ); + } } g_testAll; diff --git a/libs/math/expression.h b/libs/math/expression.h index 0b995e3a..b5fe4cbe 100644 --- a/libs/math/expression.h +++ b/libs/math/expression.h @@ -27,16 +27,16 @@ template class Literal { -Value m_value; + Value m_value; public: -typedef Value value_type; + typedef Value value_type; -Literal( const Value& value ) - : m_value( value ){ -} -const value_type& eval() const { - return m_value; -} + Literal( const Value& value ) + : m_value( value ){ + } + const value_type& eval() const { + return m_value; + } }; template @@ -53,16 +53,16 @@ inline float float_for_expression( const Expression& expression ){ template class ScalarDivided { -First first; -Second second; + First first; + Second second; public: -typedef typename First::value_type value_type; + typedef typename First::value_type value_type; -ScalarDivided( const First& first_, const Second& second_ ) : first( first_ ), second( second_ ){ -} -value_type eval() const { - return static_cast( first.eval() / second.eval() ); -} + ScalarDivided( const First& first_, const Second& second_ ) : first( first_ ), second( second_ ){ + } + value_type eval() const { + return static_cast( first.eval() / second.eval() ); + } }; template @@ -79,15 +79,15 @@ inline ScalarDivided, First> float_reciproca template class SquareRoot { -First first; + First first; public: -typedef typename First::value_type value_type; + typedef typename First::value_type value_type; -SquareRoot( const First& first_ ) : first( first_ ){ -} -value_type eval() const { - return static_cast( sqrt( first.eval() ) ); -} + SquareRoot( const First& first_ ) : first( first_ ){ + } + value_type eval() const { + return static_cast( sqrt( first.eval() ) ); + } }; template @@ -99,17 +99,17 @@ inline SquareRoot float_square_root( const First& first ){ template class BasicVector3Literal { -const BasicVector3 m_value; + const BasicVector3 m_value; public: -typedef Element value_type; -typedef IntegralConstant<3> dimension; + typedef Element value_type; + typedef IntegralConstant<3> dimension; -BasicVector3Literal( const BasicVector3& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int i ) const { - return m_value[i]; -} + BasicVector3Literal( const BasicVector3& value ) + : m_value( value ){ + } + const value_type& eval( unsigned int i ) const { + return m_value[i]; + } }; template @@ -122,17 +122,17 @@ typedef BasicVector3Literal Vector3Literal; template class BasicVector3Identity { -const BasicVector3& m_value; + const BasicVector3& m_value; public: -typedef Element value_type; -typedef IntegralConstant<3> dimension; + typedef Element value_type; + typedef IntegralConstant<3> dimension; -BasicVector3Identity( const BasicVector3& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int i ) const { - return m_value[i]; -} + BasicVector3Identity( const BasicVector3& value ) + : m_value( value ){ + } + const value_type& eval( unsigned int i ) const { + return m_value[i]; + } }; template @@ -151,18 +151,18 @@ inline BasicVector3 vector3_for_expression( con template class VectorScalar { -First first; -Literal second; + First first; + Literal second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorScalar( const First& first_, const Second& second_ ) - : first( first_ ), second( second_.eval() ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ), second.eval() ); -} + VectorScalar( const First& first_, const Second& second_ ) + : first( first_ ), second( second_.eval() ){ + } + value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ), second.eval() ); + } }; @@ -170,29 +170,29 @@ value_type eval( unsigned int i ) const { template class VectorVector { -First first; -Second second; + First first; + Second second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorVector( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ), second.eval( i ) ); -} + VectorVector( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ + } + value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ), second.eval( i ) ); + } }; template class Added { public: -typedef First value_type; + typedef First value_type; -static value_type apply( const First& first, const Second& second ){ - return static_cast( first + second ); -} + static value_type apply( const First& first, const Second& second ){ + return static_cast( first + second ); + } }; template @@ -207,11 +207,11 @@ template class Multiplied { public: -typedef First value_type; + typedef First value_type; -static value_type apply( const First& first, const Second& second ){ - return static_cast( first * second ); -} + static value_type apply( const First& first, const Second& second ){ + return static_cast( first * second ); + } }; template @@ -234,26 +234,26 @@ template class Negated { public: -typedef First value_type; + typedef First value_type; -static value_type apply( const First& first ){ - return -first; -} + static value_type apply( const First& first ){ + return -first; + } }; template class VectorUnary { -First first; + First first; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorUnary( const First& first_ ) : first( first_ ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ) ); -} + VectorUnary( const First& first_ ) : first( first_ ){ + } + value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ) ); + } }; template @@ -266,18 +266,18 @@ vector_negated( const First& first ){ template class VectorCross { -First first; -Second second; + First first; + Second second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorCross( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return first.eval( ( i + 1 ) % 3 ) * second.eval( ( i + 2 ) % 3 ) - first.eval( ( i + 2 ) % 3 ) * second.eval( ( i + 1 ) % 3 ); -} + VectorCross( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ + } + value_type eval( unsigned int i ) const { + return first.eval( ( i + 1 ) % 3 ) * second.eval( ( i + 2 ) % 3 ) - first.eval( ( i + 2 ) % 3 ) * second.eval( ( i + 1 ) % 3 ); + } }; template @@ -290,40 +290,40 @@ vector_cross( const First& first, const Second& second ){ template class VectorDot { -First first; -Second second; + First first; + Second second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorDot( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} - -template -struct eval_dot -{ - static value_type apply( const First& first, const Second& second ){ - return static_cast( - first.eval( Index::VALUE ) * second.eval( Index::VALUE ) - + eval_dot< IntegralConstant >::apply( first, second ) - ); + VectorDot( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ } -}; -template<> -struct eval_dot< IntegralConstant<0> > -{ - static value_type apply( const First& first, const Second& second ){ - return first.eval( 0 ) * second.eval( 0 ); + template + struct eval_dot + { + static value_type apply( const First& first, const Second& second ){ + return static_cast( + first.eval( Index::VALUE ) * second.eval( Index::VALUE ) + + eval_dot< IntegralConstant >::apply( first, second ) + ); + } + }; + + template<> + struct eval_dot< IntegralConstant<0> > + { + static value_type apply( const First& first, const Second& second ){ + return first.eval( 0 ) * second.eval( 0 ); + } + }; + + value_type eval() const { + return eval_dot< IntegralConstant >::apply( first, second ); } }; -value_type eval() const { - return eval_dot< IntegralConstant >::apply( first, second ); -} -}; - template inline VectorDot vector_dot( const First& first, const Second& second ){ @@ -333,41 +333,41 @@ inline VectorDot vector_dot( const First& first, const Second& se template class VectorLengthSquared { -First first; + First first; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -VectorLengthSquared( const First& first_ ) - : first( first_ ){ -} - -static value_type squared( const value_type& value ){ - return value * value; -} - -template -struct eval_squared -{ - static value_type apply( const First& first ){ - return static_cast( - squared( first.eval( Index::VALUE ) ) - + eval_squared< IntegralConstant >::apply( first ) - ); + VectorLengthSquared( const First& first_ ) + : first( first_ ){ } -}; -template<> -struct eval_squared< IntegralConstant<0> > -{ - static value_type apply( const First& first ){ - return squared( first.eval( 0 ) ); + static value_type squared( const value_type& value ){ + return value * value; } -}; -value_type eval() const { - return eval_squared< IntegralConstant >::apply( first ); -} + template + struct eval_squared + { + static value_type apply( const First& first ){ + return static_cast( + squared( first.eval( Index::VALUE ) ) + + eval_squared< IntegralConstant >::apply( first ) + ); + } + }; + + template<> + struct eval_squared< IntegralConstant<0> > + { + static value_type apply( const First& first ){ + return squared( first.eval( 0 ) ); + } + }; + + value_type eval() const { + return eval_squared< IntegralConstant >::apply( first ); + } }; template @@ -383,27 +383,27 @@ inline SquareRoot< VectorLengthSquared > vector_length( const First& firs #if 1 template inline VectorScalar< - Multiplied, - First, - // multiple evaulations of subexpression - ScalarDivided< - Literal, - SquareRoot< - VectorLengthSquared - > - > - > vector_normalised( const First& first ){ + Multiplied, + First, + // multiple evaulations of subexpression + ScalarDivided< + Literal, + SquareRoot< + VectorLengthSquared + > + > +> vector_normalised( const First& first ){ typedef typename First::value_type first_value_type; return vector_scaled( first, float_reciprocal( vector_length( first ) ) ); } #else template inline VectorScalar< - Multiplied, - First, - // single evaluation of subexpression - Literal - > + Multiplied, + First, + // single evaluation of subexpression + Literal +> vector_normalised( const First& first ){ typedef typename First::value_type first_value_type; return vector_scaled( first, float_literal( static_cast( first_value_type( 1.0 ) / vector_length( first ).eval() ) ) ); @@ -413,18 +413,18 @@ vector_normalised( const First& first ){ class Matrix4Literal { -const Matrix4 m_value; + const Matrix4 m_value; public: -typedef float value_type; -typedef IntegralConstant<4> dimension0; -typedef IntegralConstant<4> dimension1; + typedef float value_type; + typedef IntegralConstant<4> dimension0; + typedef IntegralConstant<4> dimension1; -Matrix4Literal( const Matrix4& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int r, unsigned int c ) const { - return m_value[r * 4 + c]; -} + Matrix4Literal( const Matrix4& value ) + : m_value( value ){ + } + const value_type& eval( unsigned int r, unsigned int c ) const { + return m_value[r * 4 + c]; + } }; inline Matrix4Literal matrix4_literal( const Matrix4& value ){ @@ -433,18 +433,18 @@ inline Matrix4Literal matrix4_literal( const Matrix4& value ){ class Matrix4Identity { -const Matrix4& m_value; + const Matrix4& m_value; public: -typedef float value_type; -typedef IntegralConstant<4> dimension0; -typedef IntegralConstant<4> dimension1; + typedef float value_type; + typedef IntegralConstant<4> dimension0; + typedef IntegralConstant<4> dimension1; -Matrix4Identity( const Matrix4& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int r, unsigned int c ) const { - return m_value[r * 4 + c]; -} + Matrix4Identity( const Matrix4& value ) + : m_value( value ){ + } + const value_type& eval( unsigned int r, unsigned int c ) const { + return m_value[r * 4 + c]; + } }; inline Matrix4Identity matrix4_identity( const Matrix4& value ){ @@ -454,42 +454,42 @@ inline Matrix4Identity matrix4_identity( const Matrix4& value ){ template inline Matrix4 matrix4_for_expression( const Expression& expression ){ return Matrix4( - expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), expression.eval( 0, 3 ), - expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), expression.eval( 1, 3 ), - expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), expression.eval( 2, 3 ), - expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), expression.eval( 3, 3 ) - ); + expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), expression.eval( 0, 3 ), + expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), expression.eval( 1, 3 ), + expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), expression.eval( 2, 3 ), + expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), expression.eval( 3, 3 ) + ); } template inline Matrix4 matrix4_affine_for_expression( const Expression& expression ){ return Matrix4( - expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), 0, - expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), 0, - expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), 0, - expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), 1 - ); + expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), 0, + expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), 0, + expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), 0, + expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), 1 + ); } template class PointMultiplied { -const First& first; -const Second& second; + const First& first; + const Second& second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; + typedef typename First::value_type value_type; + typedef typename First::dimension dimension; -PointMultiplied( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return static_cast( second.eval( 0, i ) * first.eval( 0 ) - + second.eval( 1, i ) * first.eval( 1 ) - + second.eval( 2, i ) * first.eval( 2 ) - + second.eval( 3, i ) ); -} + PointMultiplied( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ + } + value_type eval( unsigned int i ) const { + return static_cast( second.eval( 0, i ) * first.eval( 0 ) + + second.eval( 1, i ) * first.eval( 1 ) + + second.eval( 2, i ) * first.eval( 2 ) + + second.eval( 3, i ) ); + } }; template @@ -500,25 +500,25 @@ inline PointMultiplied point_multiplied( const First& point, cons template class Matrix4Multiplied { -const First& first; -const Second& second; + const First& first; + const Second& second; public: -typedef typename First::value_type value_type; -typedef typename First::dimension0 dimension0; -typedef typename First::dimension1 dimension1; + typedef typename First::value_type value_type; + typedef typename First::dimension0 dimension0; + typedef typename First::dimension1 dimension1; -Matrix4Multiplied( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} + Matrix4Multiplied( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ + } -value_type eval( unsigned int r, unsigned int c ) const { - return static_cast( - second.eval( r, 0 ) * first.eval( 0, c ) - + second.eval( r, 1 ) * first.eval( 1, c ) - + second.eval( r, 2 ) * first.eval( 2, c ) - + second.eval( r, 3 ) * first.eval( 3, c ) - ); -} + value_type eval( unsigned int r, unsigned int c ) const { + return static_cast( + second.eval( r, 0 ) * first.eval( 0, c ) + + second.eval( r, 1 ) * first.eval( 1, c ) + + second.eval( r, 2 ) * first.eval( 2, c ) + + second.eval( r, 3 ) * first.eval( 3, c ) + ); + } }; template @@ -529,19 +529,19 @@ inline Matrix4Multiplied matrix4_multiplied( const First& first, template class MatrixTransposed { -const First& first; + const First& first; public: -typedef typename First::value_type value_type; -typedef typename First::dimension0 dimension0; -typedef typename First::dimension1 dimension1; + typedef typename First::value_type value_type; + typedef typename First::dimension0 dimension0; + typedef typename First::dimension1 dimension1; -MatrixTransposed( const First& first_ ) - : first( first_ ){ -} + MatrixTransposed( const First& first_ ) + : first( first_ ){ + } -value_type eval( unsigned int r, unsigned int c ) const { - return first.eval( c, r ); -} + value_type eval( unsigned int r, unsigned int c ) const { + return first.eval( c, r ); + } }; template diff --git a/libs/math/frustum.h b/libs/math/frustum.h index 2cc083f1..590118f8 100644 --- a/libs/math/frustum.h +++ b/libs/math/frustum.h @@ -33,23 +33,23 @@ inline Matrix4 matrix4_frustum( float left, float right, float bottom, float top, float nearval, float farval ){ return Matrix4( - static_cast( ( 2 * nearval ) / ( right - left ) ), - 0, - 0, - 0, - 0, - static_cast( ( 2 * nearval ) / ( top - bottom ) ), - 0, - 0, - static_cast( ( right + left ) / ( right - left ) ), - static_cast( ( top + bottom ) / ( top - bottom ) ), - static_cast( -( farval + nearval ) / ( farval - nearval ) ), - -1, - 0, - 0, - static_cast( -( 2 * farval * nearval ) / ( farval - nearval ) ), - 0 - ); + static_cast( ( 2 * nearval ) / ( right - left ) ), + 0, + 0, + 0, + 0, + static_cast( ( 2 * nearval ) / ( top - bottom ) ), + 0, + 0, + static_cast( ( right + left ) / ( right - left ) ), + static_cast( ( top + bottom ) / ( top - bottom ) ), + static_cast( -( farval + nearval ) / ( farval - nearval ) ), + -1, + 0, + 0, + static_cast( -( 2 * farval * nearval ) / ( farval - nearval ) ), + 0 + ); } @@ -68,67 +68,67 @@ template class Vector4ClipLT { public: -static bool compare( const Vector4& self ){ - return self[Index::VALUE] < self[3]; -} -static double scale( const Vector4& self, const Vector4& other ){ - return ( self[Index::VALUE] - self[3] ) / ( other[3] - other[Index::VALUE] ); -} + static bool compare( const Vector4& self ){ + return self[Index::VALUE] < self[3]; + } + static double scale( const Vector4& self, const Vector4& other ){ + return ( self[Index::VALUE] - self[3] ) / ( other[3] - other[Index::VALUE] ); + } }; template class Vector4ClipGT { public: -static bool compare( const Vector4& self ){ - return self[Index::VALUE] > -self[3]; -} -static double scale( const Vector4& self, const Vector4& other ){ - return ( self[Index::VALUE] + self[3] ) / ( -other[3] - other[Index::VALUE] ); -} + static bool compare( const Vector4& self ){ + return self[Index::VALUE] > -self[3]; + } + static double scale( const Vector4& self, const Vector4& other ){ + return ( self[Index::VALUE] + self[3] ) / ( -other[3] - other[Index::VALUE] ); + } }; template class Vector4ClipPolygon { public: -typedef Vector4* iterator; -typedef const Vector4* const_iterator; + typedef Vector4* iterator; + typedef const Vector4* const_iterator; -static std::size_t apply( const_iterator first, const_iterator last, iterator out ){ - if( first == last ) /* prevent buffer underflow in compare( *i ); isn't actually required, for technical correctness only */ - return 0; - const_iterator next = first, i = last - 1; - iterator tmp( out ); - bool b0 = ClipPlane::compare( *i ); - while ( next != last ) - { - bool b1 = ClipPlane::compare( *next ); - if ( b0 ^ b1 ) { - *out = vector4_subtracted( *next, *i ); + static std::size_t apply( const_iterator first, const_iterator last, iterator out ){ + if( first == last ) /* prevent buffer underflow in compare( *i ); isn't actually required, for technical correctness only */ + return 0; + const_iterator next = first, i = last - 1; + iterator tmp( out ); + bool b0 = ClipPlane::compare( *i ); + while ( next != last ) + { + bool b1 = ClipPlane::compare( *next ); + if ( b0 ^ b1 ) { + *out = vector4_subtracted( *next, *i ); - double scale = ClipPlane::scale( *i, *out ); + double scale = ClipPlane::scale( *i, *out ); - ( *out )[0] = static_cast( ( *i )[0] + scale * ( ( *out )[0] ) ); - ( *out )[1] = static_cast( ( *i )[1] + scale * ( ( *out )[1] ) ); - ( *out )[2] = static_cast( ( *i )[2] + scale * ( ( *out )[2] ) ); - ( *out )[3] = static_cast( ( *i )[3] + scale * ( ( *out )[3] ) ); + ( *out )[0] = static_cast( ( *i )[0] + scale * ( ( *out )[0] ) ); + ( *out )[1] = static_cast( ( *i )[1] + scale * ( ( *out )[1] ) ); + ( *out )[2] = static_cast( ( *i )[2] + scale * ( ( *out )[2] ) ); + ( *out )[3] = static_cast( ( *i )[3] + scale * ( ( *out )[3] ) ); - ++out; + ++out; + } + + if ( b1 ) { + *out = *next; + ++out; + } + + i = next; + ++next; + b0 = b1; } - if ( b1 ) { - *out = *next; - ++out; - } - - i = next; - ++next; - b0 = b1; + return out - tmp; } - - return out - tmp; -} }; #define CLIP_X_LT_W( p ) ( Vector4ClipLT< IntegralConstant<0> >::compare( p ) ) @@ -418,42 +418,42 @@ struct Frustum Frustum(){ } Frustum( const Plane3& _right, - const Plane3& _left, - const Plane3& _bottom, - const Plane3& _top, - const Plane3& _back, - const Plane3& _front ) + const Plane3& _left, + const Plane3& _bottom, + const Plane3& _top, + const Plane3& _back, + const Plane3& _front ) : right( _right ), left( _left ), bottom( _bottom ), top( _top ), back( _back ), front( _front ){ } }; inline Frustum frustum_transformed( const Frustum& frustum, const Matrix4& transform ){ return Frustum( - plane3_transformed( frustum.right, transform ), - plane3_transformed( frustum.left, transform ), - plane3_transformed( frustum.bottom, transform ), - plane3_transformed( frustum.top, transform ), - plane3_transformed( frustum.back, transform ), - plane3_transformed( frustum.front, transform ) - ); + plane3_transformed( frustum.right, transform ), + plane3_transformed( frustum.left, transform ), + plane3_transformed( frustum.bottom, transform ), + plane3_transformed( frustum.top, transform ), + plane3_transformed( frustum.back, transform ), + plane3_transformed( frustum.front, transform ) + ); } inline Frustum frustum_inverse_transformed( const Frustum& frustum, const Matrix4& transform ){ return Frustum( - plane3_inverse_transformed( frustum.right, transform ), - plane3_inverse_transformed( frustum.left, transform ), - plane3_inverse_transformed( frustum.bottom, transform ), - plane3_inverse_transformed( frustum.top, transform ), - plane3_inverse_transformed( frustum.back, transform ), - plane3_inverse_transformed( frustum.front, transform ) - ); + plane3_inverse_transformed( frustum.right, transform ), + plane3_inverse_transformed( frustum.left, transform ), + plane3_inverse_transformed( frustum.bottom, transform ), + plane3_inverse_transformed( frustum.top, transform ), + plane3_inverse_transformed( frustum.back, transform ), + plane3_inverse_transformed( frustum.front, transform ) + ); } inline bool viewproj_test_point( const Matrix4& viewproj, const Vector3& point ){ Vector4 hpoint( matrix4_transformed_vector4( viewproj, Vector4( point, 1.0f ) ) ); if ( fabs( hpoint[0] ) < fabs( hpoint[3] ) - && fabs( hpoint[1] ) < fabs( hpoint[3] ) - && fabs( hpoint[2] ) < fabs( hpoint[3] ) ) { + && fabs( hpoint[1] ) < fabs( hpoint[3] ) + && fabs( hpoint[2] ) < fabs( hpoint[3] ) ) { return true; } return false; @@ -465,14 +465,14 @@ inline bool viewproj_test_transformed_point( const Matrix4& viewproj, const Vect inline Frustum frustum_from_viewproj( const Matrix4& viewproj ){ return Frustum - ( - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 0], viewproj[ 7] - viewproj[ 4], viewproj[11] - viewproj[ 8], viewproj[15] - viewproj[12] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 0], viewproj[ 7] + viewproj[ 4], viewproj[11] + viewproj[ 8], viewproj[15] + viewproj[12] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 1], viewproj[ 7] + viewproj[ 5], viewproj[11] + viewproj[ 9], viewproj[15] + viewproj[13] ) ), - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 1], viewproj[ 7] - viewproj[ 5], viewproj[11] - viewproj[ 9], viewproj[15] - viewproj[13] ) ), - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 2], viewproj[ 7] - viewproj[ 6], viewproj[11] - viewproj[10], viewproj[15] - viewproj[14] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 2], viewproj[ 7] + viewproj[ 6], viewproj[11] + viewproj[10], viewproj[15] + viewproj[14] ) ) - ); + ( + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 0], viewproj[ 7] - viewproj[ 4], viewproj[11] - viewproj[ 8], viewproj[15] - viewproj[12] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 0], viewproj[ 7] + viewproj[ 4], viewproj[11] + viewproj[ 8], viewproj[15] + viewproj[12] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 1], viewproj[ 7] + viewproj[ 5], viewproj[11] + viewproj[ 9], viewproj[15] + viewproj[13] ) ), + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 1], viewproj[ 7] - viewproj[ 5], viewproj[11] - viewproj[ 9], viewproj[15] - viewproj[13] ) ), + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 2], viewproj[ 7] - viewproj[ 6], viewproj[11] - viewproj[10], viewproj[15] - viewproj[14] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 2], viewproj[ 7] + viewproj[ 6], viewproj[11] + viewproj[10], viewproj[15] + viewproj[14] ) ) + ); } struct VolumeIntersection @@ -551,8 +551,8 @@ inline double plane_distance_to_point( const Plane3& plane, const Vector3& point inline double plane_distance_to_oriented_extents( const Plane3& plane, const Vector3& extents, const Matrix4& orientation ){ return fabs( extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.x() ) ) ) - + fabs( extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.y() ) ) ) - + fabs( extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.z() ) ) ); + + fabs( extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.y() ) ) ) + + fabs( extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.z() ) ) ); } /// \brief Return false if \p aabb with \p orientation is partially or completely outside \p plane. @@ -566,11 +566,11 @@ inline VolumeIntersectionValue frustum_intersects_transformed_aabb( const Frustu matrix4_transform_point( localToWorld, aabb_world.origin ); if ( plane_contains_oriented_aabb( frustum.right, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.left, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.bottom, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.top, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.back, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.front, aabb_world, localToWorld ) ) { + || plane_contains_oriented_aabb( frustum.left, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.bottom, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.top, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.back, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.front, aabb_world, localToWorld ) ) { return c_volumeOutside; } return c_volumeInside; @@ -586,27 +586,27 @@ inline bool plane3_test_line( const Plane3& plane, const Segment& segment ){ inline bool frustum_test_point( const Frustum& frustum, const Vector3& point ){ return !plane3_test_point( frustum.right, point ) - && !plane3_test_point( frustum.left, point ) - && !plane3_test_point( frustum.bottom, point ) - && !plane3_test_point( frustum.top, point ) - && !plane3_test_point( frustum.back, point ) - && !plane3_test_point( frustum.front, point ); + && !plane3_test_point( frustum.left, point ) + && !plane3_test_point( frustum.bottom, point ) + && !plane3_test_point( frustum.top, point ) + && !plane3_test_point( frustum.back, point ) + && !plane3_test_point( frustum.front, point ); } inline bool frustum_test_line( const Frustum& frustum, const Segment& segment ){ return !plane3_test_line( frustum.right, segment ) - && !plane3_test_line( frustum.left, segment ) - && !plane3_test_line( frustum.bottom, segment ) - && !plane3_test_line( frustum.top, segment ) - && !plane3_test_line( frustum.back, segment ) - && !plane3_test_line( frustum.front, segment ); + && !plane3_test_line( frustum.left, segment ) + && !plane3_test_line( frustum.bottom, segment ) + && !plane3_test_line( frustum.top, segment ) + && !plane3_test_line( frustum.back, segment ) + && !plane3_test_line( frustum.front, segment ); } inline bool viewer_test_plane( const Vector4& viewer, const Plane3& plane ){ - return ( ( plane.a * viewer[0] ) - + ( plane.b * viewer[1] ) - + ( plane.c * viewer[2] ) - + ( plane.d * viewer[3] ) ) > 0; + return ( ( plane.a * viewer[0] ) + + ( plane.b * viewer[1] ) + + ( plane.c * viewer[2] ) + + ( plane.d * viewer[3] ) ) > 0; } inline Vector3 triangle_cross( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ @@ -615,10 +615,10 @@ inline Vector3 triangle_cross( const Vector3& p0, const Vector3& p1, const Vecto inline bool viewer_test_triangle( const Vector4& viewer, const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ Vector3 cross( triangle_cross( p0, p1, p2 ) ); - return ( ( viewer[0] * cross[0] ) - + ( viewer[1] * cross[1] ) - + ( viewer[2] * cross[2] ) - + ( viewer[3] * 0 ) ) > 0; + return ( ( viewer[0] * cross[0] ) + + ( viewer[1] * cross[1] ) + + ( viewer[2] * cross[2] ) + + ( viewer[3] * 0 ) ) > 0; } inline Vector4 viewer_from_transformed_viewer( const Vector4& viewer, const Matrix4& transform ){ diff --git a/libs/math/line.h b/libs/math/line.h index 04af0ba5..6a4ebb7f 100644 --- a/libs/math/line.h +++ b/libs/math/line.h @@ -32,12 +32,12 @@ class Line { public: -Vector3 start, end; + Vector3 start, end; -Line(){ -} -Line( const Vector3& start_, const Vector3& end_ ) : start( start_ ), end( end_ ){ -} + Line(){ + } + Line( const Vector3& start_, const Vector3& end_ ) : start( start_ ), end( end_ ){ + } }; inline Vector3 line_closest_point( const Line& line, const Vector3& point ){ @@ -61,13 +61,13 @@ inline Vector3 line_closest_point( const Line& line, const Vector3& point ){ class Segment { public: -Vector3 origin, extents; + Vector3 origin, extents; -Segment(){ -} -Segment( const Vector3& origin_, const Vector3& extents_ ) : - origin( origin_ ), extents( extents_ ){ -} + Segment(){ + } + Segment( const Vector3& origin_, const Vector3& extents_ ) : + origin( origin_ ), extents( extents_ ){ + } }; @@ -95,13 +95,13 @@ template class BasicRay { public: -BasicVector3 origin, direction; + BasicVector3 origin, direction; -BasicRay(){ -} -BasicRay( const BasicVector3& origin_, const BasicVector3& direction_ ) : - origin( origin_ ), direction( direction_ ){ -} + BasicRay(){ + } + BasicRay( const BasicVector3& origin_, const BasicVector3& direction_ ) : + origin( origin_ ), direction( direction_ ){ + } }; typedef BasicRay Ray; @@ -120,20 +120,20 @@ inline void ray_transform( Ray& ray, const Matrix4& matrix ){ // closest-point-on-line inline double ray_squared_distance_to_point( const Ray& ray, const Vector3& point ){ return vector3_length_squared( - vector3_subtracted( - point, - vector3_added( - ray.origin, - vector3_scaled( - ray.direction, - vector3_dot( - vector3_subtracted( point, ray.origin ), - ray.direction - ) - ) - ) - ) - ); + vector3_subtracted( + point, + vector3_added( + ray.origin, + vector3_scaled( + ray.direction, + vector3_dot( + vector3_subtracted( point, ray.origin ), + ray.direction + ) + ) + ) + ) + ); } inline double ray_distance_to_plane( const Ray& ray, const Plane3& plane ){ @@ -144,10 +144,10 @@ inline double ray_distance_to_plane( const Ray& ray, const Plane3& plane ){ template inline BasicVector3 ray_intersect_plane( const BasicRay& ray, const Plane3& plane ){ return ray.origin + vector3_scaled( - ray.direction, - -plane3_distance_to_point( plane, ray.origin ) - / vector3_dot( ray.direction, plane.normal() ) - ); + ray.direction, + -plane3_distance_to_point( plane, ray.origin ) + / vector3_dot( ray.direction, plane.normal() ) + ); } /// \brief Returns the infinite line that is the intersection of \p plane and \p other. diff --git a/libs/math/matrix.h b/libs/math/matrix.h index 0b98c6a6..80be7863 100644 --- a/libs/math/matrix.h +++ b/libs/math/matrix.h @@ -37,190 +37,190 @@ class Matrix4 { -float m_elements[16]; + float m_elements[16]; public: -Matrix4(){ -} -Matrix4( float xx_, float xy_, float xz_, float xw_, - float yx_, float yy_, float yz_, float yw_, - float zx_, float zy_, float zz_, float zw_, - float tx_, float ty_, float tz_, float tw_ ){ - xx() = xx_; - xy() = xy_; - xz() = xz_; - xw() = xw_; - yx() = yx_; - yy() = yy_; - yz() = yz_; - yw() = yw_; - zx() = zx_; - zy() = zy_; - zz() = zz_; - zw() = zw_; - tx() = tx_; - ty() = ty_; - tz() = tz_; - tw() = tw_; -} + Matrix4(){ + } + Matrix4( float xx_, float xy_, float xz_, float xw_, + float yx_, float yy_, float yz_, float yw_, + float zx_, float zy_, float zz_, float zw_, + float tx_, float ty_, float tz_, float tw_ ){ + xx() = xx_; + xy() = xy_; + xz() = xz_; + xw() = xw_; + yx() = yx_; + yy() = yy_; + yz() = yz_; + yw() = yw_; + zx() = zx_; + zy() = zy_; + zz() = zz_; + zw() = zw_; + tx() = tx_; + ty() = ty_; + tz() = tz_; + tw() = tw_; + } -float& xx(){ - return m_elements[0]; -} -const float& xx() const { - return m_elements[0]; -} -float& xy(){ - return m_elements[1]; -} -const float& xy() const { - return m_elements[1]; -} -float& xz(){ - return m_elements[2]; -} -const float& xz() const { - return m_elements[2]; -} -float& xw(){ - return m_elements[3]; -} -const float& xw() const { - return m_elements[3]; -} -float& yx(){ - return m_elements[4]; -} -const float& yx() const { - return m_elements[4]; -} -float& yy(){ - return m_elements[5]; -} -const float& yy() const { - return m_elements[5]; -} -float& yz(){ - return m_elements[6]; -} -const float& yz() const { - return m_elements[6]; -} -float& yw(){ - return m_elements[7]; -} -const float& yw() const { - return m_elements[7]; -} -float& zx(){ - return m_elements[8]; -} -const float& zx() const { - return m_elements[8]; -} -float& zy(){ - return m_elements[9]; -} -const float& zy() const { - return m_elements[9]; -} -float& zz(){ - return m_elements[10]; -} -const float& zz() const { - return m_elements[10]; -} -float& zw(){ - return m_elements[11]; -} -const float& zw() const { - return m_elements[11]; -} -float& tx(){ - return m_elements[12]; -} -const float& tx() const { - return m_elements[12]; -} -float& ty(){ - return m_elements[13]; -} -const float& ty() const { - return m_elements[13]; -} -float& tz(){ - return m_elements[14]; -} -const float& tz() const { - return m_elements[14]; -} -float& tw(){ - return m_elements[15]; -} -const float& tw() const { - return m_elements[15]; -} + float& xx(){ + return m_elements[0]; + } + const float& xx() const { + return m_elements[0]; + } + float& xy(){ + return m_elements[1]; + } + const float& xy() const { + return m_elements[1]; + } + float& xz(){ + return m_elements[2]; + } + const float& xz() const { + return m_elements[2]; + } + float& xw(){ + return m_elements[3]; + } + const float& xw() const { + return m_elements[3]; + } + float& yx(){ + return m_elements[4]; + } + const float& yx() const { + return m_elements[4]; + } + float& yy(){ + return m_elements[5]; + } + const float& yy() const { + return m_elements[5]; + } + float& yz(){ + return m_elements[6]; + } + const float& yz() const { + return m_elements[6]; + } + float& yw(){ + return m_elements[7]; + } + const float& yw() const { + return m_elements[7]; + } + float& zx(){ + return m_elements[8]; + } + const float& zx() const { + return m_elements[8]; + } + float& zy(){ + return m_elements[9]; + } + const float& zy() const { + return m_elements[9]; + } + float& zz(){ + return m_elements[10]; + } + const float& zz() const { + return m_elements[10]; + } + float& zw(){ + return m_elements[11]; + } + const float& zw() const { + return m_elements[11]; + } + float& tx(){ + return m_elements[12]; + } + const float& tx() const { + return m_elements[12]; + } + float& ty(){ + return m_elements[13]; + } + const float& ty() const { + return m_elements[13]; + } + float& tz(){ + return m_elements[14]; + } + const float& tz() const { + return m_elements[14]; + } + float& tw(){ + return m_elements[15]; + } + const float& tw() const { + return m_elements[15]; + } -Vector4& x(){ - return reinterpret_cast( xx() ); -} -const Vector4& x() const { - return reinterpret_cast( xx() ); -} -Vector4& y(){ - return reinterpret_cast( yx() ); -} -const Vector4& y() const { - return reinterpret_cast( yx() ); -} -Vector4& z(){ - return reinterpret_cast( zx() ); -} -const Vector4& z() const { - return reinterpret_cast( zx() ); -} -Vector4& t(){ - return reinterpret_cast( tx() ); -} -const Vector4& t() const { - return reinterpret_cast( tx() ); -} + Vector4& x(){ + return reinterpret_cast( xx() ); + } + const Vector4& x() const { + return reinterpret_cast( xx() ); + } + Vector4& y(){ + return reinterpret_cast( yx() ); + } + const Vector4& y() const { + return reinterpret_cast( yx() ); + } + Vector4& z(){ + return reinterpret_cast( zx() ); + } + const Vector4& z() const { + return reinterpret_cast( zx() ); + } + Vector4& t(){ + return reinterpret_cast( tx() ); + } + const Vector4& t() const { + return reinterpret_cast( tx() ); + } -const float& index( std::size_t i ) const { - return m_elements[i]; -} -float& index( std::size_t i ){ - return m_elements[i]; -} -const float& operator[]( std::size_t i ) const { - return m_elements[i]; -} -float& operator[]( std::size_t i ){ - return m_elements[i]; -} -const float& index( std::size_t r, std::size_t c ) const { - return m_elements[( r << 2 ) + c]; -} -float& index( std::size_t r, std::size_t c ){ - return m_elements[( r << 2 ) + c]; -} + const float& index( std::size_t i ) const { + return m_elements[i]; + } + float& index( std::size_t i ){ + return m_elements[i]; + } + const float& operator[]( std::size_t i ) const { + return m_elements[i]; + } + float& operator[]( std::size_t i ){ + return m_elements[i]; + } + const float& index( std::size_t r, std::size_t c ) const { + return m_elements[( r << 2 ) + c]; + } + float& index( std::size_t r, std::size_t c ){ + return m_elements[( r << 2 ) + c]; + } }; /// \brief The 4x4 identity matrix. const Matrix4 g_matrix4_identity( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 +); /// \brief Returns true if \p self and \p other are exactly element-wise equal. inline bool operator==( const Matrix4& self, const Matrix4& other ){ return self.xx() == other.xx() && self.xy() == other.xy() && self.xz() == other.xz() && self.xw() == other.xw() - && self.yx() == other.yx() && self.yy() == other.yy() && self.yz() == other.yz() && self.yw() == other.yw() - && self.zx() == other.zx() && self.zy() == other.zy() && self.zz() == other.zz() && self.zw() == other.zw() - && self.tx() == other.tx() && self.ty() == other.ty() && self.tz() == other.tz() && self.tw() == other.tw(); + && self.yx() == other.yx() && self.yy() == other.yy() && self.yz() == other.yz() && self.yw() == other.yw() + && self.zx() == other.zx() && self.zy() == other.zy() && self.zz() == other.zz() && self.zw() == other.zw() + && self.tx() == other.tx() && self.ty() == other.ty() && self.tz() == other.tz() && self.tw() == other.tw(); } /// \brief Returns true if \p self and \p other are exactly element-wise equal. @@ -231,38 +231,38 @@ inline bool matrix4_equal( const Matrix4& self, const Matrix4& other ){ /// \brief Returns true if \p self and \p other are element-wise equal within \p epsilon. inline bool matrix4_equal_epsilon( const Matrix4& self, const Matrix4& other, float epsilon ){ return float_equal_epsilon( self.xx(), other.xx(), epsilon ) - && float_equal_epsilon( self.xy(), other.xy(), epsilon ) - && float_equal_epsilon( self.xz(), other.xz(), epsilon ) - && float_equal_epsilon( self.xw(), other.xw(), epsilon ) - && float_equal_epsilon( self.yx(), other.yx(), epsilon ) - && float_equal_epsilon( self.yy(), other.yy(), epsilon ) - && float_equal_epsilon( self.yz(), other.yz(), epsilon ) - && float_equal_epsilon( self.yw(), other.yw(), epsilon ) - && float_equal_epsilon( self.zx(), other.zx(), epsilon ) - && float_equal_epsilon( self.zy(), other.zy(), epsilon ) - && float_equal_epsilon( self.zz(), other.zz(), epsilon ) - && float_equal_epsilon( self.zw(), other.zw(), epsilon ) - && float_equal_epsilon( self.tx(), other.tx(), epsilon ) - && float_equal_epsilon( self.ty(), other.ty(), epsilon ) - && float_equal_epsilon( self.tz(), other.tz(), epsilon ) - && float_equal_epsilon( self.tw(), other.tw(), epsilon ); + && float_equal_epsilon( self.xy(), other.xy(), epsilon ) + && float_equal_epsilon( self.xz(), other.xz(), epsilon ) + && float_equal_epsilon( self.xw(), other.xw(), epsilon ) + && float_equal_epsilon( self.yx(), other.yx(), epsilon ) + && float_equal_epsilon( self.yy(), other.yy(), epsilon ) + && float_equal_epsilon( self.yz(), other.yz(), epsilon ) + && float_equal_epsilon( self.yw(), other.yw(), epsilon ) + && float_equal_epsilon( self.zx(), other.zx(), epsilon ) + && float_equal_epsilon( self.zy(), other.zy(), epsilon ) + && float_equal_epsilon( self.zz(), other.zz(), epsilon ) + && float_equal_epsilon( self.zw(), other.zw(), epsilon ) + && float_equal_epsilon( self.tx(), other.tx(), epsilon ) + && float_equal_epsilon( self.ty(), other.ty(), epsilon ) + && float_equal_epsilon( self.tz(), other.tz(), epsilon ) + && float_equal_epsilon( self.tw(), other.tw(), epsilon ); } /// \brief Returns true if \p self and \p other are exactly element-wise equal. /// \p self and \p other must be affine. inline bool matrix4_affine_equal( const Matrix4& self, const Matrix4& other ){ return self[0] == other[0] - && self[1] == other[1] - && self[2] == other[2] - && self[4] == other[4] - && self[5] == other[5] - && self[6] == other[6] - && self[8] == other[8] - && self[9] == other[9] - && self[10] == other[10] - && self[12] == other[12] - && self[13] == other[13] - && self[14] == other[14]; + && self[1] == other[1] + && self[2] == other[2] + && self[4] == other[4] + && self[5] == other[5] + && self[6] == other[6] + && self[8] == other[8] + && self[9] == other[9] + && self[10] == other[10] + && self[12] == other[12] + && self[13] == other[13] + && self[14] == other[14]; } enum Matrix4Handedness @@ -274,12 +274,12 @@ enum Matrix4Handedness /// \brief Returns MATRIX4_RIGHTHANDED if \p self is right-handed, else returns MATRIX4_LEFTHANDED. inline Matrix4Handedness matrix4_handedness( const Matrix4& self ){ return ( - vector3_dot( - vector3_cross( vector4_to_vector3( self.x() ), vector4_to_vector3( self.y() ) ), - vector4_to_vector3( self.z() ) - ) - < 0.0 - ) ? MATRIX4_LEFTHANDED : MATRIX4_RIGHTHANDED; + vector3_dot( + vector3_cross( vector4_to_vector3( self.x() ), vector4_to_vector3( self.y() ) ), + vector4_to_vector3( self.z() ) + ) + < 0.0 + ) ? MATRIX4_LEFTHANDED : MATRIX4_RIGHTHANDED; } @@ -289,23 +289,23 @@ inline Matrix4Handedness matrix4_handedness( const Matrix4& self ){ /// \brief Returns \p self post-multiplied by \p other. inline Matrix4 matrix4_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8] + other[3] * self[12], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9] + other[3] * self[13], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10] + other[3] * self[14], - other[0] * self[3] + other[1] * self[7] + other[2] * self[11] + other[3] * self[15], - other[4] * self[0] + other[5] * self[4] + other[6] * self[8] + other[7] * self[12], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9] + other[7] * self[13], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10] + other[7] * self[14], - other[4] * self[3] + other[5] * self[7] + other[6] * self[11] + other[7] * self[15], - other[8] * self[0] + other[9] * self[4] + other[10] * self[8] + other[11] * self[12], - other[8] * self[1] + other[9] * self[5] + other[10] * self[9] + other[11] * self[13], - other[8] * self[2] + other[9] * self[6] + other[10] * self[10] + other[11] * self[14], - other[8] * self[3] + other[9] * self[7] + other[10] * self[11] + other[11] * self[15], - other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + other[15] * self[12], - other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + other[15] * self[13], - other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + other[15] * self[14], - other[12] * self[3] + other[13] * self[7] + other[14] * self[11] + other[15] * self[15] - ); + other[0] * self[0] + other[1] * self[4] + other[2] * self[8] + other[3] * self[12], + other[0] * self[1] + other[1] * self[5] + other[2] * self[9] + other[3] * self[13], + other[0] * self[2] + other[1] * self[6] + other[2] * self[10] + other[3] * self[14], + other[0] * self[3] + other[1] * self[7] + other[2] * self[11] + other[3] * self[15], + other[4] * self[0] + other[5] * self[4] + other[6] * self[8] + other[7] * self[12], + other[4] * self[1] + other[5] * self[5] + other[6] * self[9] + other[7] * self[13], + other[4] * self[2] + other[5] * self[6] + other[6] * self[10] + other[7] * self[14], + other[4] * self[3] + other[5] * self[7] + other[6] * self[11] + other[7] * self[15], + other[8] * self[0] + other[9] * self[4] + other[10] * self[8] + other[11] * self[12], + other[8] * self[1] + other[9] * self[5] + other[10] * self[9] + other[11] * self[13], + other[8] * self[2] + other[9] * self[6] + other[10] * self[10] + other[11] * self[14], + other[8] * self[3] + other[9] * self[7] + other[10] * self[11] + other[11] * self[15], + other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + other[15] * self[12], + other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + other[15] * self[13], + other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + other[15] * self[14], + other[12] * self[3] + other[13] * self[7] + other[14] * self[11] + other[15] * self[15] + ); } /// \brief Post-multiplies \p self by \p other in-place. @@ -333,23 +333,23 @@ inline bool matrix4_is_affine( const Matrix4& transform ){ /// \p self and \p other must be affine. inline Matrix4 matrix4_affine_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10], - 0, - other[4] * self[0] + other[5] * self[4] + other[6] * self[8], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10], - 0, - other[8] * self[0] + other[9] * self[4] + other[10] * self[8], - other[8] * self[1] + other[9] * self[5] + other[10] * self[9], - other[8] * self[2] + other[9] * self[6] + other[10] * self[10], - 0, - other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + self[12], - other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + self[13], - other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + self[14], - 1 - ); + other[0] * self[0] + other[1] * self[4] + other[2] * self[8], + other[0] * self[1] + other[1] * self[5] + other[2] * self[9], + other[0] * self[2] + other[1] * self[6] + other[2] * self[10], + 0, + other[4] * self[0] + other[5] * self[4] + other[6] * self[8], + other[4] * self[1] + other[5] * self[5] + other[6] * self[9], + other[4] * self[2] + other[5] * self[6] + other[6] * self[10], + 0, + other[8] * self[0] + other[9] * self[4] + other[10] * self[8], + other[8] * self[1] + other[9] * self[5] + other[10] * self[9], + other[8] * self[2] + other[9] * self[6] + other[10] * self[10], + 0, + other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + self[12], + other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + self[13], + other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + self[14], + 1 + ); } /// \brief Post-multiplies \p self by \p other in-place. @@ -374,10 +374,10 @@ inline void matrix4_affine_premultiply_by_matrix4( Matrix4& self, const Matrix4& template inline BasicVector3 matrix4_transformed_point( const Matrix4& self, const BasicVector3& point ){ return BasicVector3( - static_cast( point[0] * self[0] + point[1] * self[4] + point[2] * self[8] + self[12] ), - static_cast( point[0] * self[1] + point[1] * self[5] + point[2] * self[9] + self[13] ), - static_cast( point[0] * self[2] + point[1] * self[6] + point[2] * self[10] + self[14] ) - ); + static_cast( point[0] * self[0] + point[1] * self[4] + point[2] * self[8] + self[12] ), + static_cast( point[0] * self[1] + point[1] * self[5] + point[2] * self[9] + self[13] ), + static_cast( point[0] * self[2] + point[1] * self[6] + point[2] * self[10] + self[14] ) + ); } /// \brief Transforms \p point by \p self in-place. @@ -390,10 +390,10 @@ inline void matrix4_transform_point( const Matrix4& self, BasicVector3& template inline BasicVector3 matrix4_transformed_direction( const Matrix4& self, const BasicVector3& direction ){ return BasicVector3( - static_cast( direction[0] * self[0] + direction[1] * self[4] + direction[2] * self[8] ), - static_cast( direction[0] * self[1] + direction[1] * self[5] + direction[2] * self[9] ), - static_cast( direction[0] * self[2] + direction[1] * self[6] + direction[2] * self[10] ) - ); + static_cast( direction[0] * self[0] + direction[1] * self[4] + direction[2] * self[8] ), + static_cast( direction[0] * self[1] + direction[1] * self[5] + direction[2] * self[9] ), + static_cast( direction[0] * self[2] + direction[1] * self[6] + direction[2] * self[10] ) + ); } /// \brief Transforms \p direction by \p self in-place. @@ -406,11 +406,11 @@ inline void matrix4_transform_direction( const Matrix4& self, BasicVector3 inline BasicVector4 matrix4_transformed_vector4( const Matrix4& self, const BasicVector4& vector4 ){ return BasicVector4( - static_cast( vector4[0] * self[0] + vector4[1] * self[4] + vector4[2] * self[8] + vector4[3] * self[12] ), - static_cast( vector4[0] * self[1] + vector4[1] * self[5] + vector4[2] * self[9] + vector4[3] * self[13] ), - static_cast( vector4[0] * self[2] + vector4[1] * self[6] + vector4[2] * self[10] + vector4[3] * self[14] ), - static_cast( vector4[0] * self[3] + vector4[1] * self[7] + vector4[2] * self[11] + vector4[3] * self[15] ) - ); + static_cast( vector4[0] * self[0] + vector4[1] * self[4] + vector4[2] * self[8] + vector4[3] * self[12] ), + static_cast( vector4[0] * self[1] + vector4[1] * self[5] + vector4[2] * self[9] + vector4[3] * self[13] ), + static_cast( vector4[0] * self[2] + vector4[1] * self[6] + vector4[2] * self[10] + vector4[3] * self[14] ), + static_cast( vector4[0] * self[3] + vector4[1] * self[7] + vector4[2] * self[11] + vector4[3] * self[15] ) + ); } /// \brief Transforms \p vector4 by \p self in-place. @@ -433,23 +433,23 @@ inline void matrix4_transpose( Matrix4& self ){ /// \brief Returns \p self transposed. inline Matrix4 matrix4_transposed( const Matrix4& self ){ return Matrix4( - self.xx(), - self.yx(), - self.zx(), - self.tx(), - self.xy(), - self.yy(), - self.zy(), - self.ty(), - self.xz(), - self.yz(), - self.zz(), - self.tz(), - self.xw(), - self.yw(), - self.zw(), - self.tw() - ); + self.xx(), + self.yx(), + self.zx(), + self.tx(), + self.xy(), + self.yy(), + self.zy(), + self.ty(), + self.xz(), + self.yz(), + self.zz(), + self.tz(), + self.xw(), + self.yw(), + self.zw(), + self.tw() + ); } @@ -460,9 +460,9 @@ inline Matrix4 matrix4_affine_inverse( const Matrix4& self ){ // determinant of rotation submatrix double det - = self[0] * ( self[5] * self[10] - self[9] * self[6] ) - - self[1] * ( self[4] * self[10] - self[8] * self[6] ) - + self[2] * ( self[4] * self[9] - self[8] * self[5] ); + = self[0] * ( self[5] * self[10] - self[9] * self[6] ) + - self[1] * ( self[4] * self[10] - self[8] * self[6] ) + + self[2] * ( self[4] * self[9] - self[8] * self[5] ); // throw exception here if (det*det < 1e-25) @@ -484,14 +484,14 @@ inline Matrix4 matrix4_affine_inverse( const Matrix4& self ){ // multiply translation part by rotation result[12] = -( self[12] * result[0] + - self[13] * result[4] + - self[14] * result[8] ); + self[13] * result[4] + + self[14] * result[8] ); result[13] = -( self[12] * result[1] + - self[13] * result[5] + - self[14] * result[9] ); + self[13] * result[5] + + self[14] * result[9] ); result[14] = -( self[12] * result[2] + - self[13] * result[6] + - self[14] * result[10] ); + self[13] * result[6] + + self[14] * result[10] ); result[15] = 1; return result; @@ -513,9 +513,9 @@ template class Matrix4Index { public: -typedef IntegralConstant r; -typedef IntegralConstant c; -typedef IntegralConstant<( r::VALUE * 4 ) + c::VALUE> i; + typedef IntegralConstant r; + typedef IntegralConstant c; + typedef IntegralConstant<( r::VALUE * 4 ) + c::VALUE> i; }; /// \brief A functor which returns the cofactor of a 3x3 submatrix obtained by ignoring a given row and column of a 4x4 matrix. @@ -525,20 +525,20 @@ template class Matrix4Cofactor { public: -typedef typename Matrix4Index::i xx; -typedef typename Matrix4Index::i xy; -typedef typename Matrix4Index::i xz; -typedef typename Matrix4Index::i yx; -typedef typename Matrix4Index::i yy; -typedef typename Matrix4Index::i yz; -typedef typename Matrix4Index::i zx; -typedef typename Matrix4Index::i zy; -typedef typename Matrix4Index::i zz; -static double apply( const Matrix4& self ){ - return self[xx::VALUE] * ( self[yy::VALUE] * self[zz::VALUE] - self[zy::VALUE] * self[yz::VALUE] ) - - self[xy::VALUE] * ( self[yx::VALUE] * self[zz::VALUE] - self[zx::VALUE] * self[yz::VALUE] ) - + self[xz::VALUE] * ( self[yx::VALUE] * self[zy::VALUE] - self[zx::VALUE] * self[yy::VALUE] ); -} + typedef typename Matrix4Index::i xx; + typedef typename Matrix4Index::i xy; + typedef typename Matrix4Index::i xz; + typedef typename Matrix4Index::i yx; + typedef typename Matrix4Index::i yy; + typedef typename Matrix4Index::i yz; + typedef typename Matrix4Index::i zx; + typedef typename Matrix4Index::i zy; + typedef typename Matrix4Index::i zz; + static double apply( const Matrix4& self ){ + return self[xx::VALUE] * ( self[yy::VALUE] * self[zz::VALUE] - self[zy::VALUE] * self[yz::VALUE] ) + - self[xy::VALUE] * ( self[yx::VALUE] * self[zz::VALUE] - self[zx::VALUE] * self[yz::VALUE] ) + + self[xz::VALUE] * ( self[yx::VALUE] * self[zy::VALUE] - self[zx::VALUE] * self[yy::VALUE] ); + } }; /// \brief The cofactor element indices for a 4x4 matrix row or column. @@ -547,17 +547,17 @@ template class Cofactor4 { public: -typedef IntegralConstant<( Element <= 0 ) ? 1 : 0> x; -typedef IntegralConstant<( Element <= 1 ) ? 2 : 1> y; -typedef IntegralConstant<( Element <= 2 ) ? 3 : 2> z; + typedef IntegralConstant<( Element <= 0 ) ? 1 : 0> x; + typedef IntegralConstant<( Element <= 1 ) ? 2 : 1> y; + typedef IntegralConstant<( Element <= 2 ) ? 3 : 2> z; }; /// \brief Returns the determinant of \p self. inline double matrix4_determinant( const Matrix4& self ){ return self.xx() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) - - self.xy() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) - + self.xz() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) - - self.xw() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ); + - self.xy() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) + + self.xz() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) + - self.xw() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ); } /// \brief Returns the inverse of \p self using the Adjoint method. @@ -566,23 +566,23 @@ inline Matrix4 matrix4_full_inverse( const Matrix4& self ){ double determinant = 1.0 / matrix4_determinant( self ); return Matrix4( - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<3> >::apply( self ) * determinant ) - ); + static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<3> >::apply( self ) * determinant ) + ); } /// \brief Inverts \p self in-place using the Adjoint method. @@ -606,11 +606,11 @@ inline BasicVector3 matrix4_transformed_normal( const Matrix4& matrix, /// \brief Constructs a pure-translation matrix from \p translation. inline Matrix4 matrix4_translation_for_vec3( const Vector3& translation ){ return Matrix4( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - translation[0], translation[1], translation[2], 1 - ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + translation[0], translation[1], translation[2], 1 + ); } /// \brief Returns the translation part of \p self. @@ -642,19 +642,19 @@ inline float angle_modulate_degrees_range( float angle ){ /// \brief Returns \p euler angles converted from radians to degrees. inline Vector3 euler_radians_to_degrees( const Vector3& euler ){ return Vector3( - static_cast( radians_to_degrees( euler.x() ) ), - static_cast( radians_to_degrees( euler.y() ) ), - static_cast( radians_to_degrees( euler.z() ) ) - ); + static_cast( radians_to_degrees( euler.x() ) ), + static_cast( radians_to_degrees( euler.y() ) ), + static_cast( radians_to_degrees( euler.z() ) ) + ); } /// \brief Returns \p euler angles converted from degrees to radians. inline Vector3 euler_degrees_to_radians( const Vector3& euler ){ return Vector3( - static_cast( degrees_to_radians( euler.x() ) ), - static_cast( degrees_to_radians( euler.y() ) ), - static_cast( degrees_to_radians( euler.z() ) ) - ); + static_cast( degrees_to_radians( euler.x() ) ), + static_cast( degrees_to_radians( euler.y() ) ), + static_cast( degrees_to_radians( euler.z() ) ) + ); } @@ -662,11 +662,11 @@ inline Vector3 euler_degrees_to_radians( const Vector3& euler ){ /// \brief Constructs a pure-rotation matrix about the x axis from sin \p s and cosine \p c of an angle. inline Matrix4 matrix4_rotation_for_sincos_x( float s, float c ){ return Matrix4( - 1, 0, 0, 0, - 0, c, s, 0, - 0,-s, c, 0, - 0, 0, 0, 1 - ); + 1, 0, 0, 0, + 0, c, s, 0, + 0,-s, c, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the x axis from an angle in radians. @@ -682,11 +682,11 @@ inline Matrix4 matrix4_rotation_for_x_degrees( float x ){ /// \brief Constructs a pure-rotation matrix about the y axis from sin \p s and cosine \p c of an angle. inline Matrix4 matrix4_rotation_for_sincos_y( float s, float c ){ return Matrix4( - c, 0,-s, 0, - 0, 1, 0, 0, - s, 0, c, 0, - 0, 0, 0, 1 - ); + c, 0,-s, 0, + 0, 1, 0, 0, + s, 0, c, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the y axis from an angle in radians. @@ -702,11 +702,11 @@ inline Matrix4 matrix4_rotation_for_y_degrees( float y ){ /// \brief Constructs a pure-rotation matrix about the z axis from sin \p s and cosine \p c of an angle. inline Matrix4 matrix4_rotation_for_sincos_z( float s, float c ){ return Matrix4( - c, s, 0, 0, - -s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); + c, s, 0, 0, + -s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the z axis from an angle in radians. @@ -753,33 +753,33 @@ inline Matrix4 matrix4_rotation_for_euler_xyz( const Vector3& euler ){ double sz = sin( euler[2] ); return Matrix4( - static_cast( cy * cz ), - static_cast( cy * sz ), - static_cast( -sy ), - 0, - static_cast( sx * sy * cz + cx * -sz ), - static_cast( sx * sy * sz + cx * cz ), - static_cast( sx * cy ), - 0, - static_cast( cx * sy * cz + sx * sz ), - static_cast( cx * sy * sz + -sx * cz ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( cy * cz ), + static_cast( cy * sz ), + static_cast( -sy ), + 0, + static_cast( sx * sy * cz + cx * -sz ), + static_cast( sx * sy * sz + cx * cz ), + static_cast( sx * cy ), + 0, + static_cast( cx * sy * cz + sx * sz ), + static_cast( cx * sy * sz + -sx * cz ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_x( euler[0] ), - matrix4_rotation_for_y( euler[1] ) - ), - matrix4_rotation_for_z( euler[2] ) - ); + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_x( euler[0] ), + matrix4_rotation_for_y( euler[1] ) + ), + matrix4_rotation_for_z( euler[2] ) + ); #endif } @@ -799,12 +799,12 @@ inline void matrix4_rotate_by_euler_xyz_degrees( Matrix4& self, const Vector3& e /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (y, z, x). inline Matrix4 matrix4_rotation_for_euler_yzx( const Vector3& euler ){ return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_y( euler[1] ), - matrix4_rotation_for_z( euler[2] ) - ), - matrix4_rotation_for_x( euler[0] ) - ); + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_y( euler[1] ), + matrix4_rotation_for_z( euler[2] ) + ), + matrix4_rotation_for_x( euler[0] ) + ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (y, z, x). @@ -815,12 +815,12 @@ inline Matrix4 matrix4_rotation_for_euler_yzx_degrees( const Vector3& euler ){ /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (x, z, y). inline Matrix4 matrix4_rotation_for_euler_xzy( const Vector3& euler ){ return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_x( euler[0] ), - matrix4_rotation_for_z( euler[2] ) - ), - matrix4_rotation_for_y( euler[1] ) - ); + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_x( euler[0] ), + matrix4_rotation_for_z( euler[2] ) + ), + matrix4_rotation_for_y( euler[1] ) + ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (x, z, y). @@ -845,33 +845,33 @@ inline Matrix4 matrix4_rotation_for_euler_yxz( const Vector3& euler ){ double sz = sin( euler[2] ); return Matrix4( - static_cast( cy * cz + sx * sy * -sz ), - static_cast( cy * sz + sx * sy * cz ), - static_cast( -cx * sy ), - 0, - static_cast( cx * -sz ), - static_cast( cx * cz ), - static_cast( sx ), - 0, - static_cast( sy * cz + -sx * cy * -sz ), - static_cast( sy * sz + -sx * cy * cz ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( cy * cz + sx * sy * -sz ), + static_cast( cy * sz + sx * sy * cz ), + static_cast( -cx * sy ), + 0, + static_cast( cx * -sz ), + static_cast( cx * cz ), + static_cast( sx ), + 0, + static_cast( sy * cz + -sx * cy * -sz ), + static_cast( sy * sz + -sx * cy * cz ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_y( euler[1] ), - matrix4_rotation_for_x( euler[0] ) - ), - matrix4_rotation_for_z( euler[2] ) - ); + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_y( euler[1] ), + matrix4_rotation_for_x( euler[0] ) + ), + matrix4_rotation_for_z( euler[2] ) + ); #endif } @@ -897,12 +897,12 @@ inline void matrix4_rotate_by_euler_yxz_degrees( Matrix4& self, const Vector3& e inline Matrix4 matrix4_rotation_for_euler_zxy( const Vector3& euler ){ #if 1 return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_z( euler[2] ), - matrix4_rotation_for_x( euler[0] ) - ), - matrix4_rotation_for_y( euler[1] ) - ); + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_z( euler[2] ), + matrix4_rotation_for_x( euler[0] ) + ), + matrix4_rotation_for_y( euler[1] ) + ); #else double cx = cos( euler[0] ); double sx = sin( euler[0] ); @@ -912,23 +912,23 @@ inline Matrix4 matrix4_rotation_for_euler_zxy( const Vector3& euler ){ double sz = sin( euler[2] ); return Matrix4( - static_cast( cz * cy + sz * sx * sy ), - static_cast( sz * cx ), - static_cast( cz * -sy + sz * sx * cy ), - 0, - static_cast( -sz * cy + cz * sx * sy ), - static_cast( cz * cx ), - static_cast( -sz * -sy + cz * cx * cy ), - 0, - static_cast( cx * sy ), - static_cast( -sx ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( cz * cy + sz * sx * sy ), + static_cast( sz * cx ), + static_cast( cz * -sy + sz * sx * cy ), + 0, + static_cast( -sz * cy + cz * sx * sy ), + static_cast( cz * cx ), + static_cast( -sz * -sy + cz * cx * cy ), + 0, + static_cast( cx * sy ), + static_cast( -sx ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #endif } @@ -961,33 +961,33 @@ inline Matrix4 matrix4_rotation_for_euler_zyx( const Vector3& euler ){ double sz = sin( euler[2] ); return Matrix4( - static_cast( cy * cz ), - static_cast( sx * sy * cz + cx * sz ), - static_cast( cx * -sy * cz + sx * sz ), - 0, - static_cast( cy * -sz ), - static_cast( sx * sy * -sz + cx * cz ), - static_cast( cx * -sy * -sz + sx * cz ), - 0, - static_cast( sy ), - static_cast( -sx * cy ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( cy * cz ), + static_cast( sx * sy * cz + cx * sz ), + static_cast( cx * -sy * cz + sx * sz ), + 0, + static_cast( cy * -sz ), + static_cast( sx * sy * -sz + cx * cz ), + static_cast( cx * -sy * -sz + sx * cz ), + 0, + static_cast( sy ), + static_cast( -sx * cy ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_z( euler[2] ), - matrix4_rotation_for_y( euler[1] ) - ), - matrix4_rotation_for_x( euler[0] ) - ); + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_z( euler[2] ), + matrix4_rotation_for_y( euler[1] ) + ), + matrix4_rotation_for_x( euler[0] ) + ); #endif } @@ -1006,18 +1006,18 @@ inline Vector3 matrix4_get_rotation_euler_xyz( const Matrix4& self ){ if ( fabs( ca ) > 0.005 ) { // Gimbal lock? return Vector3( - static_cast( atan2( self[6] / ca, self[10] / ca ) ), - static_cast( a ), - static_cast( atan2( self[1] / ca, self[0] / ca ) ) - ); + static_cast( atan2( self[6] / ca, self[10] / ca ) ), + static_cast( a ), + static_cast( atan2( self[1] / ca, self[0] / ca ) ) + ); } else // Gimbal lock has occurred { return Vector3( - static_cast( atan2( -self[9], self[5] ) ), - static_cast( a ), - 0 - ); + static_cast( atan2( -self[9], self[5] ) ), + static_cast( a ), + 0 + ); } } @@ -1034,18 +1034,18 @@ inline Vector3 matrix4_get_rotation_euler_yxz( const Matrix4& self ){ if ( fabs( ca ) > 0.005 ) { // Gimbal lock? return Vector3( - static_cast( a ), - static_cast( atan2( -self[2] / ca, self[10] / ca ) ), - static_cast( atan2( -self[4] / ca, self[5] / ca ) ) - ); + static_cast( a ), + static_cast( atan2( -self[2] / ca, self[10] / ca ) ), + static_cast( atan2( -self[4] / ca, self[5] / ca ) ) + ); } else // Gimbal lock has occurred { return Vector3( - static_cast( a ), - static_cast( atan2( self[8], self[0] ) ), - 0 - ); + static_cast( a ), + static_cast( atan2( self[8], self[0] ) ), + 0 + ); } } @@ -1062,18 +1062,18 @@ inline Vector3 matrix4_get_rotation_euler_zxy( const Matrix4& self ){ if ( fabs( ca ) > 0.005 ) { // Gimbal lock? return Vector3( - static_cast( a ), - static_cast( atan2( self[8] / ca, self[10] / ca ) ), - static_cast( atan2( self[1] / ca, self[5] / ca ) ) - ); + static_cast( a ), + static_cast( atan2( self[8] / ca, self[10] / ca ) ), + static_cast( atan2( self[1] / ca, self[5] / ca ) ) + ); } else // Gimbal lock has occurred { return Vector3( - static_cast( a ), - 0, - static_cast( atan2( -self[4], self[0] ) ) - ); + static_cast( a ), + 0, + static_cast( atan2( -self[4], self[0] ) ) + ); } } @@ -1090,18 +1090,18 @@ inline Vector3 matrix4_get_rotation_euler_zyx( const Matrix4& self ){ if ( fabs( ca ) > 0.005 ) { // Gimbal lock? return Vector3( - static_cast( atan2( -self[9] / ca, self[10] / ca ) ), - static_cast( a ), - static_cast( atan2( -self[4] / ca, self[0] / ca ) ) - ); + static_cast( atan2( -self[9] / ca, self[10] / ca ) ), + static_cast( a ), + static_cast( atan2( -self[4] / ca, self[0] / ca ) ) + ); } else // Gimbal lock has occurred { return Vector3( - 0, - static_cast( a ), - static_cast( atan2( self[1], self[5] ) ) - ); + 0, + static_cast( a ), + static_cast( atan2( self[1], self[5] ) ) + ); } } @@ -1122,21 +1122,21 @@ inline void matrix4_pivoted_rotate_by_euler_xyz_degrees( Matrix4& self, const Ve /// \brief Constructs a pure-scale matrix from \p scale. inline Matrix4 matrix4_scale_for_vec3( const Vector3& scale ){ return Matrix4( - scale[0], 0, 0, 0, - 0, scale[1], 0, 0, - 0, 0, scale[2], 0, - 0, 0, 0, 1 - ); + scale[0], 0, 0, 0, + 0, scale[1], 0, 0, + 0, 0, scale[2], 0, + 0, 0, 0, 1 + ); } /// \brief Calculates and returns the (x, y, z) scale values that produce the scale component of \p self. /// \p self must be affine and orthogonal to produce a meaningful result. inline Vector3 matrix4_get_scale_vec3( const Matrix4& self ){ return Vector3( - static_cast( vector3_length( vector4_to_vector3( self.x() ) ) ), - static_cast( vector3_length( vector4_to_vector3( self.y() ) ) ), - static_cast( vector3_length( vector4_to_vector3( self.z() ) ) ) - ); + static_cast( vector3_length( vector4_to_vector3( self.x() ) ) ), + static_cast( vector3_length( vector4_to_vector3( self.y() ) ) ), + static_cast( vector3_length( vector4_to_vector3( self.z() ) ) ) + ); } /// \brief Scales \p self by \p scale. diff --git a/libs/math/plane.h b/libs/math/plane.h index 3b4915b7..28552630 100644 --- a/libs/math/plane.h +++ b/libs/math/plane.h @@ -31,30 +31,30 @@ template class Plane3___ { public: -T a, b, c, d; + T a, b, c, d; -Plane3___(){ -} -Plane3___( double _a, double _b, double _c, double _d ) - : a( _a ), b( _b ), c( _c ), d( _d ){ -} -template -Plane3___( const BasicVector3& normal, double dist ) - : a( normal.x() ), b( normal.y() ), c( normal.z() ), d( dist ){ -} + Plane3___(){ + } + Plane3___( double _a, double _b, double _c, double _d ) + : a( _a ), b( _b ), c( _c ), d( _d ){ + } + template + Plane3___( const BasicVector3& normal, double dist ) + : a( normal.x() ), b( normal.y() ), c( normal.z() ), d( dist ){ + } -BasicVector3& normal(){ - return reinterpret_cast&>( *this ); -} -const BasicVector3& normal() const { - return reinterpret_cast&>( *this ); -} -T& dist(){ - return d; -} -const T& dist() const { - return d; -} + BasicVector3& normal(){ + return reinterpret_cast&>( *this ); + } + const BasicVector3& normal() const { + return reinterpret_cast&>( *this ); + } + T& dist(){ + return d; + } + const T& dist() const { + return d; + } }; /// \brief A plane equation stored in double-precision floating-point. @@ -65,11 +65,11 @@ using Plane3f = Plane3___; inline Plane3 plane3_normalised( const Plane3& plane ){ double rmagnitude = 1.0 / sqrt( plane.a * plane.a + plane.b * plane.b + plane.c * plane.c ); return Plane3( - plane.a * rmagnitude, - plane.b * rmagnitude, - plane.c * rmagnitude, - plane.d * rmagnitude - ); + plane.a * rmagnitude, + plane.b * rmagnitude, + plane.c * rmagnitude, + plane.d * rmagnitude + ); } inline Plane3 plane3_translated( const Plane3& plane, const Vector3& translation ){ @@ -78,8 +78,8 @@ inline Plane3 plane3_translated( const Plane3& plane, const Vector3& translation transformed.b = plane.b; transformed.c = plane.c; transformed.d = -( ( -plane.d * transformed.a + translation.x() ) * transformed.a + - ( -plane.d * transformed.b + translation.y() ) * transformed.b + - ( -plane.d * transformed.c + translation.z() ) * transformed.c ); + ( -plane.d * transformed.b + translation.y() ) * transformed.b + + ( -plane.d * transformed.c + translation.z() ) * transformed.c ); return transformed; } @@ -89,19 +89,19 @@ inline Plane3 plane3_transformed( const Plane3& plane, const Matrix4& transform transformed.b = transform[1] * plane.a + transform[5] * plane.b + transform[9] * plane.c; transformed.c = transform[2] * plane.a + transform[6] * plane.b + transform[10] * plane.c; transformed.d = -( ( -plane.d * transformed.a + transform[12] ) * transformed.a + - ( -plane.d * transformed.b + transform[13] ) * transformed.b + - ( -plane.d * transformed.c + transform[14] ) * transformed.c ); + ( -plane.d * transformed.b + transform[13] ) * transformed.b + + ( -plane.d * transformed.c + transform[14] ) * transformed.c ); return transformed; } inline Plane3 plane3_inverse_transformed( const Plane3& plane, const Matrix4& transform ){ return Plane3 - ( - transform[ 0] * plane.a + transform[ 1] * plane.b + transform[ 2] * plane.c + transform[ 3] * plane.d, - transform[ 4] * plane.a + transform[ 5] * plane.b + transform[ 6] * plane.c + transform[ 7] * plane.d, - transform[ 8] * plane.a + transform[ 9] * plane.b + transform[10] * plane.c + transform[11] * plane.d, - transform[12] * plane.a + transform[13] * plane.b + transform[14] * plane.c + transform[15] * plane.d - ); + ( + transform[ 0] * plane.a + transform[ 1] * plane.b + transform[ 2] * plane.c + transform[ 3] * plane.d, + transform[ 4] * plane.a + transform[ 5] * plane.b + transform[ 6] * plane.c + transform[ 7] * plane.d, + transform[ 8] * plane.a + transform[ 9] * plane.b + transform[10] * plane.c + transform[11] * plane.d, + transform[12] * plane.a + transform[13] * plane.b + transform[14] * plane.c + transform[15] * plane.d + ); } inline Plane3 plane3_transformed_affine_full( const Plane3& plane, const Matrix4& transform ){ @@ -120,7 +120,7 @@ const double c_PLANE_DIST_EPSILON = 0.02; inline bool plane3_equal( const Plane3& self, const Plane3& other ){ return vector3_equal_epsilon( self.normal(), other.normal(), c_PLANE_NORMAL_EPSILON ) - && float_equal_epsilon( self.dist(), other.dist(), c_PLANE_DIST_EPSILON ); + && float_equal_epsilon( self.dist(), other.dist(), c_PLANE_DIST_EPSILON ); } inline bool plane3_opposing( const Plane3& self, const Plane3& other ){ diff --git a/libs/math/quaternion.h b/libs/math/quaternion.h index 6eaa7166..19196fd8 100644 --- a/libs/math/quaternion.h +++ b/libs/math/quaternion.h @@ -34,11 +34,11 @@ const Quaternion c_quaternion_identity( 0, 0, 0, 1 ); inline Quaternion quaternion_multiplied_by_quaternion( const Quaternion& quaternion, const Quaternion& other ){ return Quaternion( - quaternion[3] * other[0] + quaternion[0] * other[3] + quaternion[1] * other[2] - quaternion[2] * other[1], - quaternion[3] * other[1] + quaternion[1] * other[3] + quaternion[2] * other[0] - quaternion[0] * other[2], - quaternion[3] * other[2] + quaternion[2] * other[3] + quaternion[0] * other[1] - quaternion[1] * other[0], - quaternion[3] * other[3] - quaternion[0] * other[0] - quaternion[1] * other[1] - quaternion[2] * other[2] - ); + quaternion[3] * other[0] + quaternion[0] * other[3] + quaternion[1] * other[2] - quaternion[2] * other[1], + quaternion[3] * other[1] + quaternion[1] * other[3] + quaternion[2] * other[0] - quaternion[0] * other[2], + quaternion[3] * other[2] + quaternion[2] * other[3] + quaternion[0] * other[1] - quaternion[1] * other[0], + quaternion[3] * other[3] - quaternion[0] * other[0] - quaternion[1] * other[1] - quaternion[2] * other[2] + ); } inline void quaternion_multiply_by_quaternion( Quaternion& quaternion, const Quaternion& other ){ @@ -83,11 +83,11 @@ inline void quaternion_conjugate( Quaternion& quaternion ){ inline Quaternion quaternion_normalised( const Quaternion& quaternion ){ const double n = ( 1.0 / sqrt( quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] + quaternion[3] * quaternion[3] ) ); return Quaternion( - static_cast( quaternion[0] * n ), - static_cast( quaternion[1] * n ), - static_cast( quaternion[2] * n ), - static_cast( quaternion[3] * n ) - ); + static_cast( quaternion[0] * n ), + static_cast( quaternion[1] * n ), + static_cast( quaternion[2] * n ), + static_cast( quaternion[3] * n ) + ); } inline void quaternion_normalise( Quaternion& quaternion ){ @@ -115,23 +115,23 @@ inline Matrix4 matrix4_rotation_for_quaternion( const Quaternion& quaternion ){ const double zw = quaternion[2] * quaternion[3]; return Matrix4( - static_cast( 1 - 2 * ( yy + zz ) ), - static_cast( 2 * ( xy + zw ) ), - static_cast( 2 * ( xz - yw ) ), - 0, - static_cast( 2 * ( xy - zw ) ), - static_cast( 1 - 2 * ( xx + zz ) ), - static_cast( 2 * ( yz + xw ) ), - 0, - static_cast( 2 * ( xz + yw ) ), - static_cast( 2 * ( yz - xw ) ), - static_cast( 1 - 2 * ( xx + yy ) ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( 1 - 2 * ( yy + zz ) ), + static_cast( 2 * ( xy + zw ) ), + static_cast( 2 * ( xz - yw ) ), + 0, + static_cast( 2 * ( xy - zw ) ), + static_cast( 1 - 2 * ( xx + zz ) ), + static_cast( 2 * ( yz + xw ) ), + 0, + static_cast( 2 * ( xz + yw ) ), + static_cast( 2 * ( yz - xw ) ), + static_cast( 1 - 2 * ( xx + yy ) ), + 0, + 0, + 0, + 0, + 1 + ); #else const double x2 = quaternion[0] + quaternion[0]; @@ -148,23 +148,23 @@ inline Matrix4 matrix4_rotation_for_quaternion( const Quaternion& quaternion ){ const double wz = quaternion[3] * z2; return Matrix4( - static_cast( 1.0 - ( yy + zz ) ), - static_cast( xy + wz ), - static_cast( xz - wy ), - 0, - static_cast( xy - wz ), - static_cast( 1.0 - ( xx + zz ) ), - static_cast( yz + wx ), - 0, - static_cast( xz + wy ), - static_cast( yz - wx ), - static_cast( 1.0 - ( xx + yy ) ), - 0, - 0, - 0, - 0, - 1 - ); + static_cast( 1.0 - ( yy + zz ) ), + static_cast( xy + wz ), + static_cast( xz - wy ), + 0, + static_cast( xy - wz ), + static_cast( 1.0 - ( xx + zz ) ), + static_cast( yz + wx ), + 0, + static_cast( xz + wy ), + static_cast( yz - wx ), + static_cast( 1.0 - ( xx + yy ) ), + 0, + 0, + 0, + 0, + 1 + ); #endif } @@ -178,23 +178,23 @@ inline bool quaternion_component_is_90( float component ){ inline Matrix4 matrix4_rotation_for_quaternion_quantised( const Quaternion& quaternion ){ if ( quaternion.y() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90( quaternion.x() ) - && quaternion_component_is_90( quaternion.w() ) ) { + && quaternion.z() == 0 + && quaternion_component_is_90( quaternion.x() ) + && quaternion_component_is_90( quaternion.w() ) ) { return matrix4_rotation_for_sincos_x( ( quaternion.x() > 0 ) ? 1.f : -1.f, 0 ); } if ( quaternion.x() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90( quaternion.y() ) - && quaternion_component_is_90( quaternion.w() ) ) { + && quaternion.z() == 0 + && quaternion_component_is_90( quaternion.y() ) + && quaternion_component_is_90( quaternion.w() ) ) { return matrix4_rotation_for_sincos_y( ( quaternion.y() > 0 ) ? 1.f : -1.f, 0 ); } if ( quaternion.x() == 0 - && quaternion.y() == 0 - && quaternion_component_is_90( quaternion.z() ) - && quaternion_component_is_90( quaternion.w() ) ) { + && quaternion.y() == 0 + && quaternion_component_is_90( quaternion.z() ) + && quaternion_component_is_90( quaternion.w() ) ) { return matrix4_rotation_for_sincos_z( ( quaternion.z() > 0 ) ? 1.f : -1.f, 0 ); } @@ -209,40 +209,40 @@ inline Quaternion quaternion_for_matrix4_rotation( const Matrix4& matrix4 ){ if ( trace > 0.0001 ) { double S = 0.5 / sqrt( trace ); return Quaternion( - static_cast( ( transposed[9] - transposed[6] ) * S ), - static_cast( ( transposed[2] - transposed[8] ) * S ), - static_cast( ( transposed[4] - transposed[1] ) * S ), - static_cast( 0.25 / S ) - ); + static_cast( ( transposed[9] - transposed[6] ) * S ), + static_cast( ( transposed[2] - transposed[8] ) * S ), + static_cast( ( transposed[4] - transposed[1] ) * S ), + static_cast( 0.25 / S ) + ); } if ( transposed[0] >= transposed[5] && transposed[0] >= transposed[10] ) { double S = 2.0 * sqrt( 1.0 + transposed[0] - transposed[5] - transposed[10] ); return Quaternion( - static_cast( 0.25 / S ), - static_cast( ( transposed[1] + transposed[4] ) / S ), - static_cast( ( transposed[2] + transposed[8] ) / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ) - ); + static_cast( 0.25 / S ), + static_cast( ( transposed[1] + transposed[4] ) / S ), + static_cast( ( transposed[2] + transposed[8] ) / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ) + ); } if ( transposed[5] >= transposed[0] && transposed[5] >= transposed[10] ) { double S = 2.0 * sqrt( 1.0 + transposed[5] - transposed[0] - transposed[10] ); return Quaternion( - static_cast( ( transposed[1] + transposed[4] ) / S ), - static_cast( 0.25 / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ), - static_cast( ( transposed[2] + transposed[8] ) / S ) - ); + static_cast( ( transposed[1] + transposed[4] ) / S ), + static_cast( 0.25 / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ), + static_cast( ( transposed[2] + transposed[8] ) / S ) + ); } double S = 2.0 * sqrt( 1.0 + transposed[10] - transposed[0] - transposed[5] ); return Quaternion( - static_cast( ( transposed[2] + transposed[8] ) / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ), - static_cast( 0.25 / S ), - static_cast( ( transposed[1] + transposed[4] ) / S ) - ); + static_cast( ( transposed[2] + transposed[8] ) / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ), + static_cast( 0.25 / S ), + static_cast( ( transposed[1] + transposed[4] ) / S ) + ); } /// \brief Returns \p self concatenated with the rotation transform produced by \p rotation. @@ -278,10 +278,10 @@ inline Vector3 quaternion_transformed_point( const Quaternion& quaternion, const double zw2 = quaternion.z() * quaternion.w() * 2; return Vector3( - static_cast( ww * point.x() + yw2 * point.z() - zw2 * point.y() + xx * point.x() + xy2 * point.y() + xz2 * point.z() - zz * point.x() - yy * point.x() ), - static_cast( xy2 * point.x() + yy * point.y() + yz2 * point.z() + zw2 * point.x() - zz * point.y() + ww * point.y() - xw2 * point.z() - xx * point.y() ), - static_cast( xz2 * point.x() + yz2 * point.y() + zz * point.z() - yw2 * point.x() - yy * point.z() + xw2 * point.y() - xx * point.z() + ww * point.z() ) - ); + static_cast( ww * point.x() + yw2 * point.z() - zw2 * point.y() + xx * point.x() + xy2 * point.y() + xz2 * point.z() - zz * point.x() - yy * point.x() ), + static_cast( xy2 * point.x() + yy * point.y() + yz2 * point.z() + zw2 * point.x() - zz * point.y() + ww * point.y() - xw2 * point.z() - xx * point.y() ), + static_cast( xz2 * point.x() + yz2 * point.y() + zz * point.z() - yw2 * point.x() - yy * point.z() + xw2 * point.y() - xx * point.z() + ww * point.z() ) + ); } /// \brief Constructs a pure-rotation transform from \p axis and \p angle (radians). diff --git a/libs/math/vector.h b/libs/math/vector.h index 187e1c94..b7f5a410 100644 --- a/libs/math/vector.h +++ b/libs/math/vector.h @@ -126,9 +126,9 @@ inline Element float_mod( const Element& self, const ModulusElement& modulus ){ template inline BasicVector2 vector2_added( const BasicVector2& self, const BasicVector2& other ){ return BasicVector2( - Element( self.x() + other.x() ), - Element( self.y() + other.y() ) - ); + Element( self.x() + other.x() ), + Element( self.y() + other.y() ) + ); } template inline BasicVector2 operator+( const BasicVector2& self, const BasicVector2& other ){ @@ -148,9 +148,9 @@ inline void operator+=( BasicVector2& self, const BasicVector2 inline BasicVector2 vector2_subtracted( const BasicVector2& self, const BasicVector2& other ){ return BasicVector2( - Element( self.x() - other.x() ), - Element( self.y() - other.y() ) - ); + Element( self.x() - other.x() ), + Element( self.y() - other.y() ) + ); } template inline BasicVector2 operator-( const BasicVector2& self, const BasicVector2& other ){ @@ -170,9 +170,9 @@ inline void operator-=( BasicVector2& self, const BasicVector2 inline BasicVector2 vector2_scaled( const BasicVector2& self, OtherElement other ){ return BasicVector2( - Element( self.x() * other ), - Element( self.y() * other ) - ); + Element( self.x() * other ), + Element( self.y() * other ) + ); } template inline BasicVector2 operator*( const BasicVector2& self, OtherElement other ){ @@ -192,9 +192,9 @@ inline void operator*=( BasicVector2& self, OtherElement other ){ template inline BasicVector2 vector2_scaled( const BasicVector2& self, const BasicVector2& other ){ return BasicVector2( - Element( self.x() * other.x() ), - Element( self.y() * other.y() ) - ); + Element( self.x() * other.x() ), + Element( self.y() * other.y() ) + ); } template inline BasicVector2 operator*( const BasicVector2& self, const BasicVector2& other ){ @@ -213,9 +213,9 @@ inline void operator*=( BasicVector2& self, const BasicVector2 inline BasicVector2 vector2_divided( const BasicVector2& self, const BasicVector2& other ){ return BasicVector2( - Element( self.x() / other.x() ), - Element( self.y() / other.y() ) - ); + Element( self.x() / other.x() ), + Element( self.y() / other.y() ) + ); } template inline BasicVector2 operator/( const BasicVector2& self, const BasicVector2& other ){ @@ -235,9 +235,9 @@ inline void operator/=( BasicVector2& self, const BasicVector2 inline BasicVector2 vector2_divided( const BasicVector2& self, OtherElement other ){ return BasicVector2( - Element( self.x() / other ), - Element( self.y() / other ) - ); + Element( self.x() / other ), + Element( self.y() / other ) + ); } template inline BasicVector2 operator/( const BasicVector2& self, OtherElement other ){ @@ -326,8 +326,8 @@ inline bool operator!=( const BasicVector3& self, const BasicVector3 inline bool vector3_equal_epsilon( const BasicVector3& self, const BasicVector3& other, Epsilon epsilon ){ return float_equal_epsilon( self.x(), other.x(), epsilon ) - && float_equal_epsilon( self.y(), other.y(), epsilon ) - && float_equal_epsilon( self.z(), other.z(), epsilon ); + && float_equal_epsilon( self.y(), other.y(), epsilon ) + && float_equal_epsilon( self.z(), other.z(), epsilon ); } @@ -335,10 +335,10 @@ inline bool vector3_equal_epsilon( const BasicVector3& self, const Basi template inline BasicVector3 vector3_added( const BasicVector3& self, const BasicVector3& other ){ return BasicVector3( - Element( self.x() + other.x() ), - Element( self.y() + other.y() ), - Element( self.z() + other.z() ) - ); + Element( self.x() + other.x() ), + Element( self.y() + other.y() ), + Element( self.z() + other.z() ) + ); } template inline BasicVector3 operator+( const BasicVector3& self, const BasicVector3& other ){ @@ -358,10 +358,10 @@ inline void operator+=( BasicVector3& self, const BasicVector3 inline BasicVector3 vector3_subtracted( const BasicVector3& self, const BasicVector3& other ){ return BasicVector3( - Element( self.x() - other.x() ), - Element( self.y() - other.y() ), - Element( self.z() - other.z() ) - ); + Element( self.x() - other.x() ), + Element( self.y() - other.y() ), + Element( self.z() - other.z() ) + ); } template inline BasicVector3 operator-( const BasicVector3& self, const BasicVector3& other ){ @@ -381,10 +381,10 @@ inline void operator-=( BasicVector3& self, const BasicVector3 inline BasicVector3 vector3_scaled( const BasicVector3& self, const BasicVector3& other ){ return BasicVector3( - Element( self.x() * other.x() ), - Element( self.y() * other.y() ), - Element( self.z() * other.z() ) - ); + Element( self.x() * other.x() ), + Element( self.y() * other.y() ), + Element( self.z() * other.z() ) + ); } template inline BasicVector3 operator*( const BasicVector3& self, const BasicVector3& other ){ @@ -404,10 +404,10 @@ inline void operator*=( BasicVector3& self, const BasicVector3 inline BasicVector3 vector3_scaled( const BasicVector3& self, const OtherElement& scale ){ return BasicVector3( - Element( self.x() * scale ), - Element( self.y() * scale ), - Element( self.z() * scale ) - ); + Element( self.x() * scale ), + Element( self.y() * scale ), + Element( self.z() * scale ) + ); } template inline BasicVector3 operator*( const BasicVector3& self, const OtherElement& scale ){ @@ -427,10 +427,10 @@ inline void operator*=( BasicVector3& self, const OtherElement& scale ) template inline BasicVector3 vector3_divided( const BasicVector3& self, const BasicVector3& other ){ return BasicVector3( - Element( self.x() / other.x() ), - Element( self.y() / other.y() ), - Element( self.z() / other.z() ) - ); + Element( self.x() / other.x() ), + Element( self.y() / other.y() ), + Element( self.z() / other.z() ) + ); } template inline BasicVector3 operator/( const BasicVector3& self, const BasicVector3& other ){ @@ -450,10 +450,10 @@ inline void operator/=( BasicVector3& self, const BasicVector3 inline BasicVector3 vector3_divided( const BasicVector3& self, const OtherElement& divisor ){ return BasicVector3( - Element( self.x() / divisor ), - Element( self.y() / divisor ), - Element( self.z() / divisor ) - ); + Element( self.x() / divisor ), + Element( self.y() / divisor ), + Element( self.z() / divisor ) + ); } template inline BasicVector3 operator/( const BasicVector3& self, const OtherElement& divisor ){ @@ -483,10 +483,10 @@ inline BasicVector3 vector3_mid( const BasicVector3& begin, co template inline BasicVector3 vector3_cross( const BasicVector3& self, const BasicVector3& other ){ return BasicVector3( - Element( self.y() * other.z() - self.z() * other.y() ), - Element( self.z() * other.x() - self.x() * other.z() ), - Element( self.x() * other.y() - self.y() * other.x() ) - ); + Element( self.y() * other.z() - self.z() * other.y() ), + Element( self.z() * other.x() - self.x() * other.z() ), + Element( self.x() * other.y() - self.y() * other.x() ) + ); } template @@ -527,10 +527,10 @@ inline void vector3_normalise( BasicVector3& self ){ template inline BasicVector3 vector3_snapped( const BasicVector3& self ){ return BasicVector3( - Element( float_to_integer( self.x() ) ), - Element( float_to_integer( self.y() ) ), - Element( float_to_integer( self.z() ) ) - ); + Element( float_to_integer( self.x() ) ), + Element( float_to_integer( self.y() ) ), + Element( float_to_integer( self.z() ) ) + ); } template inline void vector3_snap( BasicVector3& self ){ @@ -539,10 +539,10 @@ inline void vector3_snap( BasicVector3& self ){ template inline BasicVector3 vector3_snapped( const BasicVector3& self, const OtherElement& snap ){ return BasicVector3( - Element( float_snapped( self.x(), snap ) ), - Element( float_snapped( self.y(), snap ) ), - Element( float_snapped( self.z(), snap ) ) - ); + Element( float_snapped( self.x(), snap ) ), + Element( float_snapped( self.y(), snap ) ), + Element( float_snapped( self.z(), snap ) ) + ); } template inline void vector3_snap( BasicVector3& self, const OtherElement& snap ){ @@ -551,10 +551,10 @@ inline void vector3_snap( BasicVector3& self, const OtherElement& snap inline Vector3 vector3_for_spherical( double theta, double phi ){ return Vector3( - static_cast( cos( theta ) * cos( phi ) ), - static_cast( sin( theta ) * cos( phi ) ), - static_cast( sin( phi ) ) - ); + static_cast( cos( theta ) * cos( phi ) ), + static_cast( sin( theta ) * cos( phi ) ), + static_cast( sin( phi ) ) + ); } template @@ -588,19 +588,19 @@ inline bool operator!=( const BasicVector4& self, const BasicVector4 inline bool vector4_equal_epsilon( const BasicVector4& self, const BasicVector4& other, Element epsilon ){ return float_equal_epsilon( self.x(), other.x(), epsilon ) - && float_equal_epsilon( self.y(), other.y(), epsilon ) - && float_equal_epsilon( self.z(), other.z(), epsilon ) - && float_equal_epsilon( self.w(), other.w(), epsilon ); + && float_equal_epsilon( self.y(), other.y(), epsilon ) + && float_equal_epsilon( self.z(), other.z(), epsilon ) + && float_equal_epsilon( self.w(), other.w(), epsilon ); } template inline BasicVector4 vector4_added( const BasicVector4& self, const BasicVector4& other ){ return BasicVector4( - float(self.x() + other.x() ), - float(self.y() + other.y() ), - float(self.z() + other.z() ), - float(self.w() + other.w() ) - ); + float(self.x() + other.x() ), + float(self.y() + other.y() ), + float(self.z() + other.z() ), + float(self.w() + other.w() ) + ); } template inline BasicVector4 operator+( const BasicVector4& self, const BasicVector4& other ){ @@ -621,11 +621,11 @@ inline void operator+=( BasicVector4& self, const BasicVector4 inline BasicVector4 vector4_subtracted( const BasicVector4& self, const BasicVector4& other ){ return BasicVector4( - float(self.x() - other.x() ), - float(self.y() - other.y() ), - float(self.z() - other.z() ), - float(self.w() - other.w() ) - ); + float(self.x() - other.x() ), + float(self.y() - other.y() ), + float(self.z() - other.z() ), + float(self.w() - other.w() ) + ); } template inline BasicVector4 operator-( const BasicVector4& self, const BasicVector4& other ){ @@ -646,11 +646,11 @@ inline void operator-=( BasicVector4& self, const BasicVector4 inline BasicVector4 vector4_scaled( const BasicVector4& self, const BasicVector4& other ){ return BasicVector4( - float(self.x() * other.x() ), - float(self.y() * other.y() ), - float(self.z() * other.z() ), - float(self.w() * other.w() ) - ); + float(self.x() * other.x() ), + float(self.y() * other.y() ), + float(self.z() * other.z() ), + float(self.w() * other.w() ) + ); } template inline BasicVector4 operator*( const BasicVector4& self, const BasicVector4& other ){ @@ -671,11 +671,11 @@ inline void operator*=( BasicVector4& self, const BasicVector4 inline BasicVector4 vector4_scaled( const BasicVector4& self, OtherElement scale ){ return BasicVector4( - float(self.x() * scale), - float(self.y() * scale), - float(self.z() * scale), - float(self.w() * scale) - ); + float(self.x() * scale), + float(self.y() * scale), + float(self.z() * scale), + float(self.w() * scale) + ); } template inline BasicVector4 operator*( const BasicVector4& self, OtherElement scale ){ @@ -696,11 +696,11 @@ inline void operator*=( BasicVector4& self, OtherElement scale ){ template inline BasicVector4 vector4_divided( const BasicVector4& self, OtherElement divisor ){ return BasicVector4( - float(self.x() / divisor), - float(self.y() / divisor), - float(self.z() / divisor), - float(self.w() / divisor) - ); + float(self.x() / divisor), + float(self.y() / divisor), + float(self.z() / divisor), + float(self.w() / divisor) + ); } template inline BasicVector4 operator/( const BasicVector4& self, OtherElement divisor ){ diff --git a/libs/mathlib.h b/libs/mathlib.h index 05ac1786..1301d43a 100644 --- a/libs/mathlib.h +++ b/libs/mathlib.h @@ -426,7 +426,7 @@ void bbox_update_radius( bbox_t* bbox ); /*! Generate oriented bounding box from AABB and transformation matrix. */ /*!\todo Remove need to specify eulerZYX/scale. */ void bbox_for_oriented_aabb( bbox_t* bbox, const aabb_t* aabb, - const m4x4_t matrix, const vec3_t eulerZYX, const vec3_t scale ); + const m4x4_t matrix, const vec3_t eulerZYX, const vec3_t scale ); /*! Return 2 if bbox is behind plane, else return 1 if bbox intersects plane, else return 0. */ int bbox_intersect_plane( const bbox_t* bbox, const vec_t* plane ); diff --git a/libs/memory/allocator.cpp b/libs/memory/allocator.cpp index 0e4decf4..adb597cb 100644 --- a/libs/memory/allocator.cpp +++ b/libs/memory/allocator.cpp @@ -33,13 +33,13 @@ namespace { class Bleh { -int* m_blah; + int* m_blah; public: -Bleh( int* blah ) : m_blah( blah ){ -} -~Bleh(){ - *m_blah = 15; -} + Bleh( int* blah ) : m_blah( blah ){ + } + ~Bleh(){ + *m_blah = 15; + } }; void TestAllocator(){ diff --git a/libs/memory/allocator.h b/libs/memory/allocator.h index bef7d7cb..ce82b279 100644 --- a/libs/memory/allocator.h +++ b/libs/memory/allocator.h @@ -38,50 +38,50 @@ class DefaultAllocator { public: -typedef Type value_type; -typedef value_type* pointer; -typedef const Type* const_pointer; -typedef Type& reference; -typedef const Type& const_reference; -typedef size_t size_type; -typedef ptrdiff_t difference_type; + typedef Type value_type; + typedef value_type* pointer; + typedef const Type* const_pointer; + typedef Type& reference; + typedef const Type& const_reference; + typedef size_t size_type; + typedef ptrdiff_t difference_type; -template -struct rebind -{ - typedef DefaultAllocator other; -}; + template + struct rebind + { + typedef DefaultAllocator other; + }; -DefaultAllocator(){ -} -DefaultAllocator( const DefaultAllocator& ){ -} -template DefaultAllocator( const DefaultAllocator& ){ -} -~DefaultAllocator(){ -} + DefaultAllocator(){ + } + DefaultAllocator( const DefaultAllocator& ){ + } + template DefaultAllocator( const DefaultAllocator& ){ + } + ~DefaultAllocator(){ + } -pointer address( reference instance ) const { - return &instance; -} -const_pointer address( const_reference instance ) const { - return &instance; -} -Type* allocate( size_type size, const void* = 0 ){ - return static_cast( ::operator new( size * sizeof( Type ) ) ); -} -void deallocate( pointer p, size_type ){ - ::operator delete( p ); -} -size_type max_size() const { - return std::size_t( -1 ) / sizeof( Type ); -} -void construct( pointer p, const Type& value ){ - new(p) Type( value ); -} -void destroy( pointer p ){ - p->~Type(); -} + pointer address( reference instance ) const { + return &instance; + } + const_pointer address( const_reference instance ) const { + return &instance; + } + Type* allocate( size_type size, const void* = 0 ){ + return static_cast( ::operator new( size * sizeof( Type ) ) ); + } + void deallocate( pointer p, size_type ){ + ::operator delete( p ); + } + size_type max_size() const { + return std::size_t( -1 ) / sizeof( Type ); + } + void construct( pointer p, const Type& value ){ + new(p) Type( value ); + } + void destroy( pointer p ){ + p->~Type(); + } }; template @@ -99,66 +99,66 @@ inline bool operator==( const DefaultAllocator&, const OtherAllocator& ){ template class NamedAllocator : public DefaultAllocator { -typedef DefaultAllocator allocator_type; + typedef DefaultAllocator allocator_type; -const char* m_name; + const char* m_name; public: -typedef Type value_type; -typedef value_type* pointer; -typedef const Type* const_pointer; -typedef Type& reference; -typedef const Type& const_reference; -typedef size_t size_type; -typedef ptrdiff_t difference_type; + typedef Type value_type; + typedef value_type* pointer; + typedef const Type* const_pointer; + typedef Type& reference; + typedef const Type& const_reference; + typedef size_t size_type; + typedef ptrdiff_t difference_type; -template -struct rebind -{ - typedef NamedAllocator other; -}; + template + struct rebind + { + typedef NamedAllocator other; + }; -explicit NamedAllocator( const char* name ) : m_name( name ){ -} -NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ -} -template NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ -} -~NamedAllocator(){ -} + explicit NamedAllocator( const char* name ) : m_name( name ){ + } + NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ + } + template NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ + } + ~NamedAllocator(){ + } -pointer address( reference instance ) const { - return allocator_type::address( instance ); -} -const_pointer address( const_reference instance ) const { - return allocator_type::address( instance ); -} -Type* allocate( size_type size, const void* = 0 ){ - return allocator_type::allocate( size ); -} -void deallocate( pointer p, size_type size ){ - allocator_type::deallocate( p, size ); -} -size_type max_size() const { - return allocator_type::max_size(); -} -void construct( pointer p, const Type& value ){ - allocator_type::construct( p, value ); -} -void destroy( pointer p ){ - allocator_type::destroy( p ); -} + pointer address( reference instance ) const { + return allocator_type::address( instance ); + } + const_pointer address( const_reference instance ) const { + return allocator_type::address( instance ); + } + Type* allocate( size_type size, const void* = 0 ){ + return allocator_type::allocate( size ); + } + void deallocate( pointer p, size_type size ){ + allocator_type::deallocate( p, size ); + } + size_type max_size() const { + return allocator_type::max_size(); + } + void construct( pointer p, const Type& value ){ + allocator_type::construct( p, value ); + } + void destroy( pointer p ){ + allocator_type::destroy( p ); + } -template -bool operator==( const NamedAllocator& other ){ - return true; -} + template + bool operator==( const NamedAllocator& other ){ + return true; + } // returns true if the allocators are not interchangeable -template -bool operator!=( const NamedAllocator& other ){ - return false; -} + template + bool operator!=( const NamedAllocator& other ){ + return false; + } }; @@ -172,105 +172,105 @@ template class DefaultConstruct { public: -void operator()( Type& t ){ - constructor( t ); -} + void operator()( Type& t ){ + constructor( t ); + } }; template class Construct { -const T1& other; + const T1& other; public: -Construct( const T1& other_ ) : other( other_ ){ -} -void operator()( Type& t ){ - constructor( t, other ); -} + Construct( const T1& other_ ) : other( other_ ){ + } + void operator()( Type& t ){ + constructor( t, other ); + } }; template class Destroy { public: -void operator()( Type& t ){ - destructor( t ); -} + void operator()( Type& t ){ + destructor( t ); + } }; template > class New : public Allocator { public: -New(){ -} -explicit New( const Allocator& allocator ) : Allocator( allocator ){ -} + New(){ + } + explicit New( const Allocator& allocator ) : Allocator( allocator ){ + } -Type* scalar(){ - return new( Allocator::allocate( 1 ) )Type(); -} -template -Type* scalar( const T1& t1 ){ - return new( Allocator::allocate( 1 ) )Type( t1 ); -} -template -Type* scalar( const T1& t1, const T2& t2 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4, t5 ); -} -Type* vector( std::size_t size ){ + Type* scalar(){ + return new( Allocator::allocate( 1 ) )Type(); + } + template + Type* scalar( const T1& t1 ){ + return new( Allocator::allocate( 1 ) )Type( t1 ); + } + template + Type* scalar( const T1& t1, const T2& t2 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2 ); + } + template + Type* scalar( const T1& t1, const T2& t2, const T3& t3 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3 ); + } + template + Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4 ); + } + template + Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4, t5 ); + } + Type* vector( std::size_t size ){ #if 1 - Type* p = Allocator::allocate( size ); - std::for_each( p, p + size, DefaultConstruct() ); - return p; + Type* p = Allocator::allocate( size ); + std::for_each( p, p + size, DefaultConstruct() ); + return p; #else - // this does not work with msvc71 runtime - return new( Allocator::allocate( size ) )Type[size]; + // this does not work with msvc71 runtime + return new( Allocator::allocate( size ) )Type[size]; #endif -} -template -Type* vector( std::size_t size, const T1& t1 ){ - Type* p = Allocator::allocate( size ); - std::for_each( p, p + size, Construct( t1 ) ); - return p; -} + } + template + Type* vector( std::size_t size, const T1& t1 ){ + Type* p = Allocator::allocate( size ); + std::for_each( p, p + size, Construct( t1 ) ); + return p; + } }; template > class Delete : public Allocator { public: -Delete(){ -} -explicit Delete( const Allocator& allocator ) : Allocator( allocator ){ -} + Delete(){ + } + explicit Delete( const Allocator& allocator ) : Allocator( allocator ){ + } -void scalar( Type* p ){ - if ( p != 0 ) { - p->~Type(); - Allocator::deallocate( p, 1 ); + void scalar( Type* p ){ + if ( p != 0 ) { + p->~Type(); + Allocator::deallocate( p, 1 ); + } } -} -void vector( Type* p, std::size_t size ){ - // '::operator delete' handles null - // 'std::allocator::deallocate' requires non-null - if ( p != 0 ) { - std::for_each( p, p + size, Destroy() ); - Allocator::deallocate( p, size ); + void vector( Type* p, std::size_t size ){ + // '::operator delete' handles null + // 'std::allocator::deallocate' requires non-null + if ( p != 0 ) { + std::for_each( p, p + size, Destroy() ); + Allocator::deallocate( p, size ); + } } -} }; @@ -278,14 +278,14 @@ template class NamedNew { public: -typedef New > type; + typedef New > type; }; template class NamedDelete { public: -typedef Delete > type; + typedef Delete > type; }; #endif diff --git a/libs/moduleobservers.h b/libs/moduleobservers.h index 6476bee2..fbf8082d 100644 --- a/libs/moduleobservers.h +++ b/libs/moduleobservers.h @@ -28,32 +28,32 @@ class ModuleObservers { -typedef std::set Observers; -Observers m_observers; + typedef std::set Observers; + Observers m_observers; public: -~ModuleObservers(){ - ASSERT_MESSAGE( m_observers.empty(), "ModuleObservers::~ModuleObservers: observers still attached" ); -} -void attach( ModuleObserver& observer ){ - const bool inserted = m_observers.insert( &observer ).second; - ASSERT_MESSAGE( inserted, "ModuleObservers::attach: cannot attach observer" ); -} -void detach( ModuleObserver& observer ){ - const bool erased = m_observers.erase( &observer ); - ASSERT_MESSAGE( erased, "ModuleObservers::detach: cannot detach observer" ); -} -void realise(){ - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->realise(); + ~ModuleObservers(){ + ASSERT_MESSAGE( m_observers.empty(), "ModuleObservers::~ModuleObservers: observers still attached" ); } -} -void unrealise(){ - for ( Observers::reverse_iterator i = m_observers.rbegin(); i != m_observers.rend(); ++i ) - { - ( *i )->unrealise(); + void attach( ModuleObserver& observer ){ + const bool inserted = m_observers.insert( &observer ).second; + ASSERT_MESSAGE( inserted, "ModuleObservers::attach: cannot attach observer" ); + } + void detach( ModuleObserver& observer ){ + const bool erased = m_observers.erase( &observer ); + ASSERT_MESSAGE( erased, "ModuleObservers::detach: cannot detach observer" ); + } + void realise(){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->realise(); + } + } + void unrealise(){ + for ( Observers::reverse_iterator i = m_observers.rbegin(); i != m_observers.rend(); ++i ) + { + ( *i )->unrealise(); + } } -} }; #endif diff --git a/libs/modulesystem/moduleregistry.h b/libs/modulesystem/moduleregistry.h index abea5a05..7cd84f97 100644 --- a/libs/modulesystem/moduleregistry.h +++ b/libs/modulesystem/moduleregistry.h @@ -28,23 +28,23 @@ class ModuleRegisterable { public: -virtual void selfRegister() = 0; + virtual void selfRegister() = 0; }; class ModuleRegistryList { -typedef std::list RegisterableModules; -RegisterableModules m_modules; + typedef std::list RegisterableModules; + RegisterableModules m_modules; public: -void addModule( ModuleRegisterable& module ){ - m_modules.push_back( &module ); -} -void registerModules() const { - for ( RegisterableModules::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - ( *i )->selfRegister(); + void addModule( ModuleRegisterable& module ){ + m_modules.push_back( &module ); + } + void registerModules() const { + for ( RegisterableModules::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + ( *i )->selfRegister(); + } } -} }; typedef SmartStatic StaticModuleRegistryList; @@ -53,9 +53,9 @@ typedef SmartStatic StaticModuleRegistryList; class StaticRegisterModule : public StaticModuleRegistryList { public: -StaticRegisterModule( ModuleRegisterable& module ){ - StaticModuleRegistryList::instance().addModule( module ); -} + StaticRegisterModule( ModuleRegisterable& module ){ + StaticModuleRegistryList::instance().addModule( module ); + } }; diff --git a/libs/modulesystem/modulesmap.h b/libs/modulesystem/modulesmap.h index 1826390b..1675bfbb 100644 --- a/libs/modulesystem/modulesmap.h +++ b/libs/modulesystem/modulesmap.h @@ -30,109 +30,109 @@ template class ModulesMap : public Modules { -typedef std::map modules_t; -modules_t m_modules; + typedef std::map modules_t; + modules_t m_modules; public: -~ModulesMap(){ - for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - ( *i ).second->release(); + ~ModulesMap(){ + for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + ( *i ).second->release(); + } } -} -typedef modules_t::const_iterator iterator; + typedef modules_t::const_iterator iterator; -iterator begin() const { - return m_modules.begin(); -} -iterator end() const { - return m_modules.end(); -} - -void insert( const char* name, Module& module ){ - module.capture(); - if ( globalModuleServer().getError() ) { - module.release(); - globalModuleServer().setError( false ); + iterator begin() const { + return m_modules.begin(); } - else - { - m_modules.insert( modules_t::value_type( name, &module ) ); + iterator end() const { + return m_modules.end(); } -} -Type* find( const char* name ){ - modules_t::iterator i = m_modules.find( name ); - if ( i != m_modules.end() ) { - return static_cast( Module_getTable( *( *i ).second ) ); + void insert( const char* name, Module& module ){ + module.capture(); + if ( globalModuleServer().getError() ) { + module.release(); + globalModuleServer().setError( false ); + } + else + { + m_modules.insert( modules_t::value_type( name, &module ) ); + } } - return 0; -} -Type* findModule( const char* name ){ - return find( name ); -} -void foreachModule( const typename Modules::Visitor& visitor ){ - for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - visitor.visit( ( *i ).first.c_str(), *static_cast( Module_getTable( *( *i ).second ) ) ); + Type* find( const char* name ){ + modules_t::iterator i = m_modules.find( name ); + if ( i != m_modules.end() ) { + return static_cast( Module_getTable( *( *i ).second ) ); + } + return 0; + } + + Type* findModule( const char* name ){ + return find( name ); + } + void foreachModule( const typename Modules::Visitor& visitor ){ + for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + visitor.visit( ( *i ).first.c_str(), *static_cast( Module_getTable( *( *i ).second ) ) ); + } } -} }; template class InsertModules : public ModuleServer::Visitor { -ModulesMap& m_modules; + ModulesMap& m_modules; public: -InsertModules( ModulesMap& modules ) - : m_modules( modules ){ -} -void visit( const char* name, Module& module ) const { - m_modules.insert( name, module ); -} + InsertModules( ModulesMap& modules ) + : m_modules( modules ){ + } + void visit( const char* name, Module& module ) const { + m_modules.insert( name, module ); + } }; template class ModulesRef { -ModulesMap m_modules; + ModulesMap m_modules; public: -ModulesRef( const char* names ){ - if ( !globalModuleServer().getError() ) { - if ( string_equal( names, "*" ) ) { - InsertModules visitor( m_modules ); - globalModuleServer().foreachModule( typename Type::Name(), typename Type::Version(), visitor ); - } - else - { - StringTokeniser tokeniser( names ); - for (;; ) + ModulesRef( const char* names ){ + if ( !globalModuleServer().getError() ) { + if ( string_equal( names, "*" ) ) { + InsertModules visitor( m_modules ); + globalModuleServer().foreachModule( typename Type::Name(), typename Type::Version(), visitor ); + } + else { - const char* name = tokeniser.getToken(); - if ( string_empty( name ) ) { - break; - } - Module* module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); - if ( module == 0 ) { - globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; - // do not fail on missing image or model plugin, they can be optional - if ( !string_equal( typename Type::Name(), "image" ) && !string_equal( typename Type::Name(), "model" ) ){ - globalModuleServer().setError( true ); + StringTokeniser tokeniser( names ); + for (;; ) + { + const char* name = tokeniser.getToken(); + if ( string_empty( name ) ) { break; } - } - else - { - m_modules.insert( name, *module ); + Module* module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( module == 0 ) { + globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + // do not fail on missing image or model plugin, they can be optional + if ( !string_equal( typename Type::Name(), "image" ) && !string_equal( typename Type::Name(), "model" ) ){ + globalModuleServer().setError( true ); + break; + } + } + else + { + m_modules.insert( name, *module ); + } } } } } -} -ModulesMap& get(){ - return m_modules; -} + ModulesMap& get(){ + return m_modules; + } }; #endif diff --git a/libs/modulesystem/singletonmodule.cpp b/libs/modulesystem/singletonmodule.cpp index 207051a8..e1d55ce7 100644 --- a/libs/modulesystem/singletonmodule.cpp +++ b/libs/modulesystem/singletonmodule.cpp @@ -25,18 +25,18 @@ class NullType { public: -INTEGER_CONSTANT( Version, 1 ); -STRING_CONSTANT( Name, "" ); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "" ); }; class NullModule { public: -typedef NullType Type; -STRING_CONSTANT( Name, "" ); -void* getTable(){ - return NULL; -} + typedef NullType Type; + STRING_CONSTANT( Name, "" ); + void* getTable(){ + return NULL; + } }; void TEST_SINGLETONMODULE(){ diff --git a/libs/modulesystem/singletonmodule.h b/libs/modulesystem/singletonmodule.h index 2ca8600d..75367608 100644 --- a/libs/modulesystem/singletonmodule.h +++ b/libs/modulesystem/singletonmodule.h @@ -32,32 +32,32 @@ template class DefaultAPIConstructor { public: -const char* getName(){ - return typename API::Name(); -} + const char* getName(){ + return typename API::Name(); + } -API* constructAPI( Dependencies& dependencies ){ - return new API; -} -void destroyAPI( API* api ){ - delete api; -} + API* constructAPI( Dependencies& dependencies ){ + return new API; + } + void destroyAPI( API* api ){ + delete api; + } }; template class DependenciesAPIConstructor { public: -const char* getName(){ - return typename API::Name(); -} + const char* getName(){ + return typename API::Name(); + } -API* constructAPI( Dependencies& dependencies ){ - return new API( dependencies ); -} -void destroyAPI( API* api ){ - delete api; -} + API* constructAPI( Dependencies& dependencies ){ + return new API( dependencies ); + } + void destroyAPI( API* api ){ + delete api; + } }; class NullDependencies @@ -68,63 +68,63 @@ class NullDependencies template > class SingletonModule : public APIConstructor, public Module, public ModuleRegisterable { -Dependencies* m_dependencies; -API* m_api; -std::size_t m_refcount; -bool m_dependencyCheck; -bool m_cycleCheck; + Dependencies* m_dependencies; + API* m_api; + std::size_t m_refcount; + bool m_dependencyCheck; + bool m_cycleCheck; public: -typedef typename API::Type Type; + typedef typename API::Type Type; -SingletonModule() - : m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ -} -explicit SingletonModule( const APIConstructor& constructor ) - : APIConstructor( constructor ), m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ -} -~SingletonModule(){ - ASSERT_MESSAGE( m_refcount == 0, "module still referenced at shutdown" ); -} - -void selfRegister(){ - globalModuleServer().registerModule( typename Type::Name(), typename Type::Version(), APIConstructor::getName(), *this ); -} - -Dependencies& getDependencies(){ - return *m_dependencies; -} -void* getTable(){ - if ( m_api != 0 ) { - return m_api->getTable(); + SingletonModule() + : m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ } - return 0; -} -void capture(){ - if ( ++m_refcount == 1 ) { - globalOutputStream() << "Module Initialising: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - m_dependencies = new Dependencies(); - m_dependencyCheck = !globalModuleServer().getError(); - if ( m_dependencyCheck ) { - m_api = APIConstructor::constructAPI( *m_dependencies ); - globalOutputStream() << "Module Ready: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - } - else - { - globalErrorStream() << "Module Dependencies Failed: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - } - m_cycleCheck = true; + explicit SingletonModule( const APIConstructor& constructor ) + : APIConstructor( constructor ), m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ + } + ~SingletonModule(){ + ASSERT_MESSAGE( m_refcount == 0, "module still referenced at shutdown" ); } - ASSERT_MESSAGE( m_cycleCheck, "cyclic dependency detected" ); -} -void release(){ - if ( --m_refcount == 0 ) { - if ( m_dependencyCheck ) { - APIConstructor::destroyAPI( m_api ); - } - delete m_dependencies; + void selfRegister(){ + globalModuleServer().registerModule( typename Type::Name(), typename Type::Version(), APIConstructor::getName(), *this ); + } + + Dependencies& getDependencies(){ + return *m_dependencies; + } + void* getTable(){ + if ( m_api != 0 ) { + return m_api->getTable(); + } + return 0; + } + void capture(){ + if ( ++m_refcount == 1 ) { + globalOutputStream() << "Module Initialising: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + m_dependencies = new Dependencies(); + m_dependencyCheck = !globalModuleServer().getError(); + if ( m_dependencyCheck ) { + m_api = APIConstructor::constructAPI( *m_dependencies ); + globalOutputStream() << "Module Ready: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + } + else + { + globalErrorStream() << "Module Dependencies Failed: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + } + m_cycleCheck = true; + } + + ASSERT_MESSAGE( m_cycleCheck, "cyclic dependency detected" ); + } + void release(){ + if ( --m_refcount == 0 ) { + if ( m_dependencyCheck ) { + APIConstructor::destroyAPI( m_api ); + } + delete m_dependencies; + } } -} }; diff --git a/libs/os/path.h b/libs/os/path.h index b20e0336..286cf160 100644 --- a/libs/os/path.h +++ b/libs/os/path.h @@ -87,7 +87,7 @@ inline bool path_equal_n( const char* path, const char* other, std::size_t n ){ inline bool path_is_absolute( const char* path ){ #if defined( WIN32 ) return path[0] == '/' - || ( path[0] != '\0' && path[1] == ':' ); // local drive + || ( path[0] != '\0' && path[1] == ':' ); // local drive #elif defined( POSIX ) return path[0] == '/'; #endif @@ -188,17 +188,17 @@ inline bool extension_equal( const char* extension, const char* other ){ template class MatchFileExtension { -const char* m_extension; -const Functor& m_functor; + const char* m_extension; + const Functor& m_functor; public: -MatchFileExtension( const char* extension, const Functor& functor ) : m_extension( extension ), m_functor( functor ){ -} -void operator()( const char* name ) const { - const char* extension = path_get_extension( name ); - if ( extension_equal( extension, m_extension ) ) { - m_functor( name ); + MatchFileExtension( const char* extension, const Functor& functor ) : m_extension( extension ), m_functor( functor ){ + } + void operator()( const char* name ) const { + const char* extension = path_get_extension( name ); + if ( extension_equal( extension, m_extension ) ) { + m_functor( name ); + } } -} }; /// \brief A functor which invokes its contained \p functor if the \p name argument matches its \p extension. @@ -225,12 +225,12 @@ inline StringRange PathFilenameless( const char *path ){ class PathCleaned { public: -const char* m_path; -const char* m_end; -PathCleaned( const char* path ) : m_path( path ), m_end( path + std::strlen( path ) ){ -} -PathCleaned( const StringRange& range ) : m_path( range.first ), m_end( range.last ){ -} + const char* m_path; + const char* m_end; + PathCleaned( const char* path ) : m_path( path ), m_end( path + std::strlen( path ) ){ + } + PathCleaned( const StringRange& range ) : m_path( range.first ), m_end( range.last ){ + } }; /// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators. @@ -252,9 +252,9 @@ TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const PathCl class DirectoryCleaned { public: -const char* m_path; -DirectoryCleaned( const char* path ) : m_path( path ){ -} + const char* m_path; + DirectoryCleaned( const char* path ) : m_path( path ){ + } }; /// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators, and appends a separator if necessary. diff --git a/libs/picomodel/lwo/lwo2.h b/libs/picomodel/lwo/lwo2.h index d055c13e..49688fc6 100644 --- a/libs/picomodel/lwo/lwo2.h +++ b/libs/picomodel/lwo/lwo2.h @@ -552,19 +552,16 @@ int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ); int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ); void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ); int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ); -int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, - lwSurface **surf, int *nsurfs ); +int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, lwSurface **surf, int *nsurfs ); void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ); void lwFreeTags( lwTagList *tlist ); int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ); -int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, - lwPolygonList *plist ); +int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, lwPolygonList *plist ); /* vmap.c */ void lwFreeVMap( lwVMap *vmap ); -lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, - int perpoly ); +lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, int perpoly ); int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ); int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ); @@ -607,8 +604,7 @@ int lwValidateObject5( const char *filename, picoMemStream_t *fp, unsigned int * void lwListFree( void *list, void ( *freeNode )( void * ) ); void lwListAdd( void **list, void *node ); -void lwListInsert( void **vlist, void *vitem, - int ( *compare )( void *, void * ) ); +void lwListInsert( void **vlist, void *vitem, int ( *compare )( void *, void * ) ); /* vecmath.c */ diff --git a/libs/pivot.h b/libs/pivot.h index 0f578dbd..711a0672 100644 --- a/libs/pivot.h +++ b/libs/pivot.h @@ -39,31 +39,31 @@ inline void billboard_viewplaneOriented( Matrix4& rotation, const Matrix4& world Matrix4 screen2world( matrix4_full_inverse( world2screen ) ); Vector3 near_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 0, -1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( 0, 0, -1, 1 ) + ) + ) + ); Vector3 far_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 0, 1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( 0, 0, 1, 1 ) + ) + ) + ); Vector3 up( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 1, -1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( 0, 1, -1, 1 ) + ) + ) + ); rotation = g_matrix4_identity; vector4_to_vector3( rotation.y() ) = vector3_normalised( vector3_subtracted( up, near_ ) ); @@ -84,31 +84,31 @@ inline void billboard_viewpointOriented( Matrix4& rotation, const Matrix4& world vector4_to_vector3( rotation.y() ) = vector3_cross( vector4_to_vector3( rotation.z() ), vector4_to_vector3( rotation.x() ) ); #else Vector3 near_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], -1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], -1, 1 ) + ) + ) + ); Vector3 far_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], 1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], 1, 1 ) + ) + ) + ); Vector3 up( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15] + 1, -1, 1 ) - ) - ) - ); + vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15] + 1, -1, 1 ) + ) + ) + ); rotation = g_matrix4_identity; vector4_to_vector3( rotation.y() ) = vector3_normalised( vector3_subtracted( up, near_ ) ); @@ -232,51 +232,51 @@ class Shader; class RenderablePivot : public OpenGLRenderable { -VertexBuffer m_vertices; + VertexBuffer m_vertices; public: -mutable Matrix4 m_localToWorld; -typedef Static StaticShader; -static Shader* getShader(){ - return StaticShader::instance(); -} - -RenderablePivot( std::size_t size = 16 ){ - m_vertices.reserve( 6 ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_x ) ); - m_vertices.push_back( PointVertex( Vertex3f( size, 0, 0 ), g_colour_x ) ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_y ) ); - m_vertices.push_back( PointVertex( Vertex3f( 0, size, 0 ), g_colour_y ) ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_z ) ); - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, size ), g_colour_z ) ); -} - -void render( RenderStateFlags state ) const { - if ( m_vertices.size() == 0 ) { - return; + mutable Matrix4 m_localToWorld; + typedef Static StaticShader; + static Shader* getShader(){ + return StaticShader::instance(); } - if ( m_vertices.data() == 0 ) { - return; + + RenderablePivot( std::size_t size = 16 ){ + m_vertices.reserve( 6 ); + + m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_x ) ); + m_vertices.push_back( PointVertex( Vertex3f( size, 0, 0 ), g_colour_x ) ); + + m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_y ) ); + m_vertices.push_back( PointVertex( Vertex3f( 0, size, 0 ), g_colour_y ) ); + + m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_z ) ); + m_vertices.push_back( PointVertex( Vertex3f( 0, 0, size ), g_colour_z ) ); } - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); - glDrawArrays( GL_LINES, 0, m_vertices.size() ); -} -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.PushState(); + void render( RenderStateFlags state ) const { + if ( m_vertices.size() == 0 ) { + return; + } + if ( m_vertices.data() == 0 ) { + return; + } + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); + glDrawArrays( GL_LINES, 0, m_vertices.size() ); + } - Pivot2World_worldSpace( m_localToWorld, localToWorld, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.PushState(); - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.SetState( getShader(), Renderer::eWireframeOnly ); - renderer.SetState( getShader(), Renderer::eFullMaterials ); - renderer.addRenderable( *this, m_localToWorld ); + Pivot2World_worldSpace( m_localToWorld, localToWorld, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - renderer.PopState(); -} + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.SetState( getShader(), Renderer::eWireframeOnly ); + renderer.SetState( getShader(), Renderer::eFullMaterials ); + renderer.addRenderable( *this, m_localToWorld ); + + renderer.PopState(); + } }; diff --git a/libs/profile/file.h b/libs/profile/file.h index c4cdc149..d1e9dcdb 100644 --- a/libs/profile/file.h +++ b/libs/profile/file.h @@ -49,27 +49,27 @@ class IDataStream : public InputStream, public OutputStream { public: -typedef int offset_type; -typedef std::size_t position_type; + typedef int offset_type; + typedef std::size_t position_type; -virtual void IncRef() = 0; ///< Increment the number of references to this object -virtual void DecRef() = 0; ///< Decrement the reference count + virtual void IncRef() = 0; ///< Increment the number of references to this object + virtual void DecRef() = 0; ///< Decrement the reference count -virtual position_type GetPosition() const = 0; -virtual int Seek( offset_type lOff, int nFrom ) = 0; + virtual position_type GetPosition() const = 0; + virtual int Seek( offset_type lOff, int nFrom ) = 0; -virtual void SetLength( size_type nNewLen ) = 0; -virtual size_type GetLength() const = 0; + virtual void SetLength( size_type nNewLen ) = 0; + virtual size_type GetLength() const = 0; -virtual char* ReadString( char* pBuf, size_type nMax ) = 0; -virtual int GetChar() = 0; + virtual char* ReadString( char* pBuf, size_type nMax ) = 0; + virtual int GetChar() = 0; -virtual int PutChar( int c ) = 0; -virtual void printf( const char*, ... ) = 0; ///< completely matches the usual printf behaviour + virtual int PutChar( int c ) = 0; + virtual void printf( const char*, ... ) = 0; ///< completely matches the usual printf behaviour -virtual void Abort() = 0; -virtual void Flush() = 0; -virtual void Close() = 0; + virtual void Abort() = 0; + virtual void Flush() = 0; + virtual void Close() = 0; }; #include @@ -77,90 +77,98 @@ virtual void Close() = 0; class MemStream : public IDataStream { public: -MemStream(); -MemStream( size_type nLen ); -virtual ~MemStream(); + MemStream(); + MemStream( size_type nLen ); + virtual ~MemStream(); -int refCount; -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + int refCount; + void IncRef() { + refCount++; + } + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } } -} protected: // MemFile specific: -size_type m_nGrowBytes; -size_type m_nPosition; -size_type m_nBufferSize; -size_type m_nFileSize; -unsigned char* m_pBuffer; -bool m_bAutoDelete; -void GrowFile( size_type nNewLen ); + size_type m_nGrowBytes; + size_type m_nPosition; + size_type m_nBufferSize; + size_type m_nFileSize; + unsigned char* m_pBuffer; + bool m_bAutoDelete; + void GrowFile( size_type nNewLen ); public: -position_type GetPosition() const; -int Seek( offset_type lOff, int nFrom ); -void SetLength( size_type nNewLen ); -size_type GetLength() const; + position_type GetPosition() const; + int Seek( offset_type lOff, int nFrom ); + void SetLength( size_type nNewLen ); + size_type GetLength() const; -unsigned char* GetBuffer() const -{ return m_pBuffer; } + unsigned char* GetBuffer() const + { + return m_pBuffer; + } -size_type read( byte_type* buffer, size_type length ); -size_type write( const byte_type* buffer, size_type length ); + size_type read( byte_type* buffer, size_type length ); + size_type write( const byte_type* buffer, size_type length ); -char* ReadString( char* pBuf, size_type nMax ); -int GetChar(); + char* ReadString( char* pBuf, size_type nMax ); + int GetChar(); -int PutChar( int c ); -void printf( const char*, ... ); ///< \todo implement on MemStream + int PutChar( int c ); + void printf( const char*, ... ); ///< \todo implement on MemStream -void Abort(); -void Flush(); -void Close(); -bool Open( const char *filename, const char *mode ); + void Abort(); + void Flush(); + void Close(); + bool Open( const char *filename, const char *mode ); }; class FileStream : public IDataStream { public: -FileStream(); -virtual ~FileStream(); + FileStream(); + virtual ~FileStream(); -int refCount; -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + int refCount; + void IncRef() { + refCount++; + } + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } } -} protected: // DiscFile specific: -FILE* m_hFile; -bool m_bCloseOnDelete; + FILE* m_hFile; + bool m_bCloseOnDelete; public: -position_type GetPosition() const; -int Seek( offset_type lOff, int nFrom ); -void SetLength( size_type nNewLen ); -size_type GetLength() const; + position_type GetPosition() const; + int Seek( offset_type lOff, int nFrom ); + void SetLength( size_type nNewLen ); + size_type GetLength() const; -size_type read( byte_type* buffer, size_type length ); -size_type write( const byte_type* buffer, size_type length ); + size_type read( byte_type* buffer, size_type length ); + size_type write( const byte_type* buffer, size_type length ); -char* ReadString( char* pBuf, size_type nMax ); -int GetChar(); + char* ReadString( char* pBuf, size_type nMax ); + int GetChar(); -int PutChar( int c ); -void printf( const char*, ... ); ///< completely matches the usual printf behaviour + int PutChar( int c ); + void printf( const char*, ... ); ///< completely matches the usual printf behaviour -void Abort(); -void Flush(); -void Close(); -bool Open( const char *filename, const char *mode ); + void Abort(); + void Flush(); + void Close(); + bool Open( const char *filename, const char *mode ); }; #endif diff --git a/libs/render.h b/libs/render.h index be3ee7e3..2303461c 100644 --- a/libs/render.h +++ b/libs/render.h @@ -40,52 +40,52 @@ const GLenum RenderIndexTypeID = GL_UNSIGNED_INT; /// \brief A resizable buffer of indices. class IndexBuffer { -typedef std::vector Indices; -Indices m_data; + typedef std::vector Indices; + Indices m_data; public: -typedef Indices::iterator iterator; -typedef Indices::const_iterator const_iterator; + typedef Indices::iterator iterator; + typedef Indices::const_iterator const_iterator; -iterator begin(){ - return m_data.begin(); -} -const_iterator begin() const { - return m_data.begin(); -} -iterator end(){ - return m_data.end(); -} -const_iterator end() const { - return m_data.end(); -} + iterator begin(){ + return m_data.begin(); + } + const_iterator begin() const { + return m_data.begin(); + } + iterator end(){ + return m_data.end(); + } + const_iterator end() const { + return m_data.end(); + } -bool empty() const { - return m_data.empty(); -} -std::size_t size() const { - return m_data.size(); -} -const RenderIndex* data() const { - return &( *m_data.begin() ); -} -RenderIndex& operator[]( std::size_t index ){ - return m_data[index]; -} -const RenderIndex& operator[]( std::size_t index ) const { - return m_data[index]; -} -void clear(){ - m_data.clear(); -} -void reserve( std::size_t max_indices ){ - m_data.reserve( max_indices ); -} -void insert( RenderIndex index ){ - m_data.push_back( index ); -} -void swap( IndexBuffer& other ){ - std::swap( m_data, other.m_data ); -} + bool empty() const { + return m_data.empty(); + } + std::size_t size() const { + return m_data.size(); + } + const RenderIndex* data() const { + return &( *m_data.begin() ); + } + RenderIndex& operator[]( std::size_t index ){ + return m_data[index]; + } + const RenderIndex& operator[]( std::size_t index ) const { + return m_data[index]; + } + void clear(){ + m_data.clear(); + } + void reserve( std::size_t max_indices ){ + m_data.reserve( max_indices ); + } + void insert( RenderIndex index ){ + m_data.push_back( index ); + } + void swap( IndexBuffer& other ){ + std::swap( m_data, other.m_data ); + } }; namespace std @@ -102,50 +102,50 @@ inline void swap( IndexBuffer& self, IndexBuffer& other ){ template class VertexBuffer { -typedef typename std::vector Vertices; -Vertices m_data; + typedef typename std::vector Vertices; + Vertices m_data; public: -typedef typename Vertices::iterator iterator; -typedef typename Vertices::const_iterator const_iterator; + typedef typename Vertices::iterator iterator; + typedef typename Vertices::const_iterator const_iterator; -iterator begin(){ - return m_data.begin(); -} -iterator end(){ - return m_data.end(); -} -const_iterator begin() const { - return m_data.begin(); -} -const_iterator end() const { - return m_data.end(); -} + iterator begin(){ + return m_data.begin(); + } + iterator end(){ + return m_data.end(); + } + const_iterator begin() const { + return m_data.begin(); + } + const_iterator end() const { + return m_data.end(); + } -bool empty() const { - return m_data.empty(); -} -RenderIndex size() const { - return RenderIndex( m_data.size() ); -} -const Vertex* data() const { - return &( *m_data.begin() ); -} -Vertex& operator[]( std::size_t index ){ - return m_data[index]; -} -const Vertex& operator[]( std::size_t index ) const { - return m_data[index]; -} + bool empty() const { + return m_data.empty(); + } + RenderIndex size() const { + return RenderIndex( m_data.size() ); + } + const Vertex* data() const { + return &( *m_data.begin() ); + } + Vertex& operator[]( std::size_t index ){ + return m_data[index]; + } + const Vertex& operator[]( std::size_t index ) const { + return m_data[index]; + } -void clear(){ - m_data.clear(); -} -void reserve( std::size_t max_vertices ){ - m_data.reserve( max_vertices ); -} -void push_back( const Vertex& vertex ){ - m_data.push_back( vertex ); -} + void clear(){ + m_data.clear(); + } + void reserve( std::size_t max_vertices ){ + m_data.reserve( max_vertices ); + } + void push_back( const Vertex& vertex ){ + m_data.push_back( vertex ); + } }; /// \brief A wrapper around a VertexBuffer which inserts only vertices which have not already been inserted. @@ -154,122 +154,122 @@ void push_back( const Vertex& vertex ){ template class UniqueVertexBuffer { -typedef VertexBuffer Vertices; -Vertices& m_data; + typedef VertexBuffer Vertices; + Vertices& m_data; -struct bnode -{ - bnode() - : m_left( 0 ), m_right( 0 ){ - } - RenderIndex m_left; - RenderIndex m_right; -}; - -std::vector m_btree; -RenderIndex m_prev0; -RenderIndex m_prev1; -RenderIndex m_prev2; - -RenderIndex find_or_insert( const Vertex& vertex ){ - RenderIndex index = 0; - - while ( 1 ) + struct bnode { - if ( vertex < m_data[index] ) { - bnode& node = m_btree[index]; - if ( node.m_left != 0 ) { - index = node.m_left; - continue; - } - else - { - node.m_left = RenderIndex( m_btree.size() ); - m_btree.push_back( bnode() ); - m_data.push_back( vertex ); - return RenderIndex( m_btree.size() - 1 ); - } - } - if ( m_data[index] < vertex ) { - bnode& node = m_btree[index]; - if ( node.m_right != 0 ) { - index = node.m_right; - continue; - } - else - { - node.m_right = RenderIndex( m_btree.size() ); - m_btree.push_back( bnode() ); - m_data.push_back( vertex ); - return RenderIndex( m_btree.size() - 1 ); - } + bnode() + : m_left( 0 ), m_right( 0 ){ } + RenderIndex m_left; + RenderIndex m_right; + }; - return index; + std::vector m_btree; + RenderIndex m_prev0; + RenderIndex m_prev1; + RenderIndex m_prev2; + + RenderIndex find_or_insert( const Vertex& vertex ){ + RenderIndex index = 0; + + while ( 1 ) + { + if ( vertex < m_data[index] ) { + bnode& node = m_btree[index]; + if ( node.m_left != 0 ) { + index = node.m_left; + continue; + } + else + { + node.m_left = RenderIndex( m_btree.size() ); + m_btree.push_back( bnode() ); + m_data.push_back( vertex ); + return RenderIndex( m_btree.size() - 1 ); + } + } + if ( m_data[index] < vertex ) { + bnode& node = m_btree[index]; + if ( node.m_right != 0 ) { + index = node.m_right; + continue; + } + else + { + node.m_right = RenderIndex( m_btree.size() ); + m_btree.push_back( bnode() ); + m_data.push_back( vertex ); + return RenderIndex( m_btree.size() - 1 ); + } + } + + return index; + } } -} public: -UniqueVertexBuffer( Vertices& data ) - : m_data( data ), m_prev0( 0 ), m_prev1( 0 ), m_prev2( 0 ){ -} - -typedef typename Vertices::const_iterator iterator; - -iterator begin() const { - return m_data.begin(); -} -iterator end() const { - return m_data.end(); -} - -std::size_t size() const { - return m_data.size(); -} -const Vertex* data() const { - return &( *m_data.begin() ); -} -Vertex& operator[]( std::size_t index ){ - return m_data[index]; -} -const Vertex& operator[]( std::size_t index ) const { - return m_data[index]; -} - -void clear(){ - m_prev0 = 0; - m_prev1 = 0; - m_prev2 = 0; - m_data.clear(); - m_btree.clear(); -} -void reserve( std::size_t max_vertices ){ - m_data.reserve( max_vertices ); - m_btree.reserve( max_vertices ); -} -/// \brief Returns the index of the element equal to \p vertex. -RenderIndex insert( const Vertex& vertex ){ - if ( m_data.empty() ) { - m_data.push_back( vertex ); - m_btree.push_back( bnode() ); - return 0; + UniqueVertexBuffer( Vertices& data ) + : m_data( data ), m_prev0( 0 ), m_prev1( 0 ), m_prev2( 0 ){ } - if ( m_data[m_prev0] == vertex ) { + typedef typename Vertices::const_iterator iterator; + + iterator begin() const { + return m_data.begin(); + } + iterator end() const { + return m_data.end(); + } + + std::size_t size() const { + return m_data.size(); + } + const Vertex* data() const { + return &( *m_data.begin() ); + } + Vertex& operator[]( std::size_t index ){ + return m_data[index]; + } + const Vertex& operator[]( std::size_t index ) const { + return m_data[index]; + } + + void clear(){ + m_prev0 = 0; + m_prev1 = 0; + m_prev2 = 0; + m_data.clear(); + m_btree.clear(); + } + void reserve( std::size_t max_vertices ){ + m_data.reserve( max_vertices ); + m_btree.reserve( max_vertices ); + } +/// \brief Returns the index of the element equal to \p vertex. + RenderIndex insert( const Vertex& vertex ){ + if ( m_data.empty() ) { + m_data.push_back( vertex ); + m_btree.push_back( bnode() ); + return 0; + } + + if ( m_data[m_prev0] == vertex ) { + return m_prev0; + } + if ( m_prev1 != m_prev0 && m_data[m_prev1] == vertex ) { + return m_prev1; + } + if ( m_prev2 != m_prev0 && m_prev2 != m_prev1 && m_data[m_prev2] == vertex ) { + return m_prev2; + } + + m_prev2 = m_prev1; + m_prev1 = m_prev0; + m_prev0 = find_or_insert( vertex ); + return m_prev0; } - if ( m_prev1 != m_prev0 && m_data[m_prev1] == vertex ) { - return m_prev1; - } - if ( m_prev2 != m_prev0 && m_prev2 != m_prev1 && m_data[m_prev2] == vertex ) { - return m_prev2; - } - - m_prev2 = m_prev1; - m_prev1 = m_prev0; - m_prev0 = find_or_insert( vertex ); - - return m_prev0; -} }; @@ -519,8 +519,8 @@ enum UnitSphereOctant /// \brief Returns the octant for \p normal indicating the sign of the region of unit-sphere space it lies within. inline UnitSphereOctant normal3f_classify_octant( const Normal3f& normal ){ return static_cast( - ( ( normal.x() > 0 ) << 0 ) | ( ( normal.y() > 0 ) << 1 ) | ( ( normal.z() > 0 ) << 2 ) - ); + ( ( normal.x() > 0 ) << 0 ) | ( ( normal.y() > 0 ) << 1 ) | ( ( normal.z() > 0 ) << 2 ) + ); } /// \brief Returns \p normal with its components signs made positive based on \p octant. @@ -569,17 +569,17 @@ enum UnitSphereSextant /// \p normal must be normalised. inline UnitSphereSextant normal3f_classify_sextant( const Normal3f& normal ){ return - normal.x() >= normal.y() - ? normal.x() >= normal.z() - ? normal.y() >= normal.z() - ? UNITSPHERESEXTANT_XYZ - : UNITSPHERESEXTANT_XZY - : UNITSPHERESEXTANT_ZXY - : normal.y() >= normal.z() - ? normal.x() >= normal.z() - ? UNITSPHERESEXTANT_YXZ - : UNITSPHERESEXTANT_YZX - : UNITSPHERESEXTANT_ZYX; + normal.x() >= normal.y() + ? normal.x() >= normal.z() + ? normal.y() >= normal.z() + ? UNITSPHERESEXTANT_XYZ + : UNITSPHERESEXTANT_XZY + : UNITSPHERESEXTANT_ZXY + : normal.y() >= normal.z() + ? normal.x() >= normal.z() + ? UNITSPHERESEXTANT_YXZ + : UNITSPHERESEXTANT_YZX + : UNITSPHERESEXTANT_ZYX; } /// \brief Returns \p normal with its components sorted so that x > y > z based on \p sextant. @@ -622,10 +622,10 @@ inline Normal3f normal3f_folded_quantised( const Normal3f& folded ){ // decompress return normal3f_normalised( Normal3f( - static_cast( c_quantise_normal - zbits - ybits ), - static_cast( ybits ), - static_cast( zbits ) - ) ); + static_cast( c_quantise_normal - zbits - ybits ), + static_cast( ybits ), + static_cast( zbits ) + ) ); } /// \brief Returns \p normal quantised by compressing and then decompressing its representation. @@ -676,10 +676,10 @@ inline spherical_t spherical_from_normal3f( const Normal3f& normal ){ inline Normal3f normal3f_from_spherical( const spherical_t& spherical ){ return Normal3f( - static_cast( cos( spherical.longditude ) * sin( spherical.latitude ) ), - static_cast( sin( spherical.longditude ) * sin( spherical.latitude ) ), - static_cast( cos( spherical.latitude ) ) - ); + static_cast( cos( spherical.longditude ) * sin( spherical.latitude ) ), + static_cast( sin( spherical.longditude ) * sin( spherical.latitude ) ), + static_cast( cos( spherical.latitude ) ) + ); } inline uniformspherical_t uniformspherical_from_spherical( const spherical_t& spherical ){ @@ -851,171 +851,171 @@ inline void pointvertex_gl_array( const PointVertex_t* array ){ template class RenderablePointArray : public OpenGLRenderable { -const Array& m_array; -const GLenum m_mode; + const Array& m_array; + const GLenum m_mode; public: -RenderablePointArray( const Array& array, GLenum mode ) - : m_array( array ), m_mode( mode ){ -} -void render( RenderStateFlags state ) const { + RenderablePointArray( const Array& array, GLenum mode ) + : m_array( array ), m_mode( mode ){ + } + void render( RenderStateFlags state ) const { #define NV_DRIVER_BUG 0 #if NV_DRIVER_BUG - glColorPointer( 4, GL_UNSIGNED_BYTE, 0, 0 ); - glVertexPointer( 3, GL_FLOAT, 0, 0 ); - glDrawArrays( GL_TRIANGLE_FAN, 0, 0 ); + glColorPointer( 4, GL_UNSIGNED_BYTE, 0, 0 ); + glVertexPointer( 3, GL_FLOAT, 0, 0 ); + glDrawArrays( GL_TRIANGLE_FAN, 0, 0 ); #endif - pointvertex_gl_array( m_array.data() ); - glDrawArrays( m_mode, 0, GLsizei( m_array.size() ) ); -} + pointvertex_gl_array( m_array.data() ); + glDrawArrays( m_mode, 0, GLsizei( m_array.size() ) ); + } }; class RenderablePointVector : public OpenGLRenderable { -std::vector m_vector; -const GLenum m_mode; + std::vector m_vector; + const GLenum m_mode; public: -RenderablePointVector( GLenum mode ) - : m_mode( mode ){ -} + RenderablePointVector( GLenum mode ) + : m_mode( mode ){ + } -void render( RenderStateFlags state ) const { - pointvertex_gl_array( &m_vector.front() ); - glDrawArrays( m_mode, 0, GLsizei( m_vector.size() ) ); -} + void render( RenderStateFlags state ) const { + pointvertex_gl_array( &m_vector.front() ); + glDrawArrays( m_mode, 0, GLsizei( m_vector.size() ) ); + } -std::size_t size() const { - return m_vector.size(); -} -bool empty() const { - return m_vector.empty(); -} -void clear(){ - m_vector.clear(); -} -void reserve( std::size_t size ){ - m_vector.reserve( size ); -} -void push_back( const PointVertex& point ){ - m_vector.push_back( point ); -} + std::size_t size() const { + return m_vector.size(); + } + bool empty() const { + return m_vector.empty(); + } + void clear(){ + m_vector.clear(); + } + void reserve( std::size_t size ){ + m_vector.reserve( size ); + } + void push_back( const PointVertex& point ){ + m_vector.push_back( point ); + } }; class RenderableVertexBuffer : public OpenGLRenderable { -const GLenum m_mode; -const VertexBuffer& m_vertices; + const GLenum m_mode; + const VertexBuffer& m_vertices; public: -RenderableVertexBuffer( GLenum mode, const VertexBuffer& vertices ) - : m_mode( mode ), m_vertices( vertices ){ -} + RenderableVertexBuffer( GLenum mode, const VertexBuffer& vertices ) + : m_mode( mode ), m_vertices( vertices ){ + } -void render( RenderStateFlags state ) const { - pointvertex_gl_array( m_vertices.data() ); - glDrawArrays( m_mode, 0, m_vertices.size() ); -} + void render( RenderStateFlags state ) const { + pointvertex_gl_array( m_vertices.data() ); + glDrawArrays( m_mode, 0, m_vertices.size() ); + } }; class RenderableIndexBuffer : public OpenGLRenderable { -const GLenum m_mode; -const IndexBuffer& m_indices; -const VertexBuffer& m_vertices; + const GLenum m_mode; + const IndexBuffer& m_indices; + const VertexBuffer& m_vertices; public: -RenderableIndexBuffer( GLenum mode, const IndexBuffer& indices, const VertexBuffer& vertices ) - : m_mode( mode ), m_indices( indices ), m_vertices( vertices ){ -} + RenderableIndexBuffer( GLenum mode, const IndexBuffer& indices, const VertexBuffer& vertices ) + : m_mode( mode ), m_indices( indices ), m_vertices( vertices ){ + } -void render( RenderStateFlags state ) const { + void render( RenderStateFlags state ) const { #if 1 - pointvertex_gl_array( m_vertices.data() ); - glDrawElements( m_mode, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); + pointvertex_gl_array( m_vertices.data() ); + glDrawElements( m_mode, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); #else - glBegin( m_mode ); - if ( state & RENDER_COLOURARRAY != 0 ) { - for ( std::size_t i = 0; i < m_indices.size(); ++i ) - { - glColor4ubv( &m_vertices[m_indices[i]].colour.r ); - glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); + glBegin( m_mode ); + if ( state & RENDER_COLOURARRAY != 0 ) { + for ( std::size_t i = 0; i < m_indices.size(); ++i ) + { + glColor4ubv( &m_vertices[m_indices[i]].colour.r ); + glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); + } } - } - else - { - for ( std::size_t i = 0; i < m_indices.size(); ++i ) + else { - glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); + for ( std::size_t i = 0; i < m_indices.size(); ++i ) + { + glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); + } } - } - glEnd(); + glEnd(); #endif -} + } }; class RenderableDepthTestedPointArray : public OpenGLRenderable { -Array& m_array; -const GLenum m_mode; + Array& m_array; + const GLenum m_mode; public: -RenderableDepthTestedPointArray( Array& array, GLenum mode ) - : m_array( array ), m_mode( mode ){ -} -void render( RenderStateFlags state ) const { - if( state & RENDER_COLOURWRITE ){ // render depending on visibility - for( auto& p : m_array ){ - GLuint sampleCount; - glGetQueryObjectuiv( p.query, GL_QUERY_RESULT, &sampleCount ); - if ( sampleCount == 0 ){ - p.colour = colour_occluded; + RenderableDepthTestedPointArray( Array& array, GLenum mode ) + : m_array( array ), m_mode( mode ){ + } + void render( RenderStateFlags state ) const { + if( state & RENDER_COLOURWRITE ){ // render depending on visibility + for( auto& p : m_array ){ + GLuint sampleCount; + glGetQueryObjectuiv( p.query, GL_QUERY_RESULT, &sampleCount ); + if ( sampleCount == 0 ){ + p.colour = colour_occluded; + } + else{ + p.colour = colour_vertex; + } } - else{ - p.colour = colour_vertex; + pointvertex_gl_array( m_array.data() ); + glDrawArrays( m_mode, 0, GLsizei( m_array.size() ) ); + } + else{ // test visibility + for( auto& p : m_array ){ + if( p.query == 0 ) + glGenQueries( 1, &p.query ); + glBeginQuery( GL_SAMPLES_PASSED, p.query ); + glVertexPointer( 3, GL_FLOAT, 0, &p.vertex ); + glDrawArrays( m_mode, 0, 1 ); + glEndQuery( GL_SAMPLES_PASSED ); } } - pointvertex_gl_array( m_array.data() ); - glDrawArrays( m_mode, 0, GLsizei( m_array.size() ) ); } - else{ // test visibility - for( auto& p : m_array ){ - if( p.query == 0 ) - glGenQueries( 1, &p.query ); - glBeginQuery( GL_SAMPLES_PASSED, p.query ); - glVertexPointer( 3, GL_FLOAT, 0, &p.vertex ); - glDrawArrays( m_mode, 0, 1 ); - glEndQuery( GL_SAMPLES_PASSED ); - } - } -} }; class RemapXYZ { public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x() = x; - vertex.y() = y; - vertex.z() = z; -} + static void set( Vertex3f& vertex, float x, float y, float z ){ + vertex.x() = x; + vertex.y() = y; + vertex.z() = z; + } }; class RemapYZX { public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x() = z; - vertex.y() = x; - vertex.z() = y; -} + static void set( Vertex3f& vertex, float x, float y, float z ){ + vertex.x() = z; + vertex.y() = x; + vertex.z() = y; + } }; class RemapZXY { public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x() = y; - vertex.y() = z; - vertex.z() = x; -} + static void set( Vertex3f& vertex, float x, float y, float z ){ + vertex.x() = y; + vertex.y() = z; + vertex.z() = x; + } }; template @@ -1061,90 +1061,90 @@ inline void draw_circle( const std::size_t segments, const float radius, PointVe #if 0 class PointVertexArrayIterator { -PointVertex* m_point; + PointVertex* m_point; public: -PointVertexArrayIterator( PointVertex* point ) - : m_point( point ){ -} -PointVertexArrayIterator& operator++(){ - ++m_point; - return *this; -} -PointVertexArrayIterator operator++( int ){ - PointVertexArrayIterator tmp( *this ); - ++m_point; - return tmp; -} -Vertex3f& operator*(){ - return m_point.vertex; -} -Vertex3f* operator->(){ - return &( operator*() ); -} + PointVertexArrayIterator( PointVertex* point ) + : m_point( point ){ + } + PointVertexArrayIterator& operator++(){ + ++m_point; + return *this; + } + PointVertexArrayIterator operator++( int ){ + PointVertexArrayIterator tmp( *this ); + ++m_point; + return tmp; + } + Vertex3f& operator*(){ + return m_point.vertex; + } + Vertex3f* operator->(){ + return &( operator*() ); + } } template 0.000001f ) { s.x() = -cross.y() / cross.x(); @@ -1197,17 +1197,17 @@ inline void ArbitraryMeshTriangle_calcTangents( const ArbitraryMeshVertex& a, co { Vector3 cross( - vector3_cross( - vector3_subtracted( - Vector3( b.vertex.y(), b.texcoord.s(), b.texcoord.t() ), - Vector3( a.vertex.y(), a.texcoord.s(), a.texcoord.t() ) - ), - vector3_subtracted( - Vector3( c.vertex.y(), c.texcoord.s(), c.texcoord.t() ), - Vector3( a.vertex.y(), a.texcoord.s(), a.texcoord.t() ) - ) - ) - ); + vector3_cross( + vector3_subtracted( + Vector3( b.vertex.y(), b.texcoord.s(), b.texcoord.t() ), + Vector3( a.vertex.y(), a.texcoord.s(), a.texcoord.t() ) + ), + vector3_subtracted( + Vector3( c.vertex.y(), c.texcoord.s(), c.texcoord.t() ), + Vector3( a.vertex.y(), a.texcoord.s(), a.texcoord.t() ) + ) + ) + ); if ( fabs( cross.x() ) > 0.000001f ) { s.y() = -cross.y() / cross.x(); @@ -1220,17 +1220,17 @@ inline void ArbitraryMeshTriangle_calcTangents( const ArbitraryMeshVertex& a, co { Vector3 cross( - vector3_cross( - vector3_subtracted( - Vector3( b.vertex.z(), b.texcoord.s(), b.texcoord.t() ), - Vector3( a.vertex.z(), a.texcoord.s(), a.texcoord.t() ) - ), - vector3_subtracted( - Vector3( c.vertex.z(), c.texcoord.s(), c.texcoord.t() ), - Vector3( a.vertex.z(), a.texcoord.s(), a.texcoord.t() ) - ) - ) - ); + vector3_cross( + vector3_subtracted( + Vector3( b.vertex.z(), b.texcoord.s(), b.texcoord.t() ), + Vector3( a.vertex.z(), a.texcoord.s(), a.texcoord.t() ) + ), + vector3_subtracted( + Vector3( c.vertex.z(), c.texcoord.s(), c.texcoord.t() ), + Vector3( a.vertex.z(), a.texcoord.s(), a.texcoord.t() ) + ) + ) + ); if ( fabs( cross.x() ) > 0.000001f ) { s.z() = -cross.y() / cross.x(); @@ -1291,13 +1291,13 @@ public: //so that the result will be properly aligned. #if 0 const float verts[4][2] = { { screenPos.x(), screenPos.y() }, - { screenPos.x(), screenPos.y() + height + .01f }, - { screenPos.x() + width + .01f, screenPos.y() + height + .01f }, - { screenPos.x() + width + .01f, screenPos.y() } }; + { screenPos.x(), screenPos.y() + height + .01f }, + { screenPos.x() + width + .01f, screenPos.y() + height + .01f }, + { screenPos.x() + width + .01f, screenPos.y() } }; const float coords[4][2] = { { subTex / 3.f, 1 }, - { subTex / 3.f, 0 }, - { ( subTex + 1 ) / 3.f, 0 }, - { ( subTex + 1 ) / 3.f, 1 } }; + { subTex / 3.f, 0 }, + { ( subTex + 1 ) / 3.f, 0 }, + { ( subTex + 1 ) / 3.f, 1 } }; glVertexPointer( 2, GL_FLOAT, 0, verts ); glTexCoordPointer( 2, GL_FLOAT, 0, coords ); glDrawArrays( GL_QUADS, 0, 4 ); diff --git a/libs/scenelib.h b/libs/scenelib.h index f8d6f7b7..c2a1418e 100644 --- a/libs/scenelib.h +++ b/libs/scenelib.h @@ -45,12 +45,12 @@ class SelectionIntersection; class ComponentSelectionTestable { public: -STRING_CONSTANT( Name, "ComponentSelectionTestable" ); + STRING_CONSTANT( Name, "ComponentSelectionTestable" ); -virtual bool isSelectedComponents() const = 0; -virtual void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ) = 0; -virtual void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) = 0; -virtual void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const = 0; + virtual bool isSelectedComponents() const = 0; + virtual void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ) = 0; + virtual void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) = 0; + virtual void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const = 0; }; typedef std::function Vector3Callback; @@ -58,34 +58,34 @@ typedef std::function Vector3Callback; class ComponentEditable { public: -STRING_CONSTANT( Name, "ComponentEditable" ); + STRING_CONSTANT( Name, "ComponentEditable" ); -virtual const AABB& getSelectedComponentsBounds() const = 0; -virtual void gatherSelectedComponents( const Vector3Callback& callback ) const = 0; + virtual const AABB& getSelectedComponentsBounds() const = 0; + virtual void gatherSelectedComponents( const Vector3Callback& callback ) const = 0; }; class ComponentSnappable { public: -STRING_CONSTANT( Name, "ComponentSnappable" ); + STRING_CONSTANT( Name, "ComponentSnappable" ); -virtual void snapComponents( float snap ) = 0; + virtual void snapComponents( float snap ) = 0; }; class Bounded { public: -STRING_CONSTANT( Name, "Bounded" ); + STRING_CONSTANT( Name, "Bounded" ); -virtual const AABB& localAABB() const = 0; + virtual const AABB& localAABB() const = 0; }; class BrushDoom3 { public: -STRING_CONSTANT( Name, "BrushDoom3" ); + STRING_CONSTANT( Name, "BrushDoom3" ); -virtual void setDoom3GroupOrigin( const Vector3& origin ) = 0; + virtual void setDoom3GroupOrigin( const Vector3& origin ) = 0; }; @@ -96,32 +96,32 @@ typedef TypeCastTable NodeTypeCastTable; template class NodeType : public StaticTypeSystemInitialiser { -TypeId m_typeId; + TypeId m_typeId; public: -typedef typename Type::Name Name; -NodeType() : m_typeId( NODETYPEID_NONE ){ - StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); -} -void initialise(){ - m_typeId = GlobalSceneGraph().getNodeTypeId( Name() ); -} -typedef MemberCaller, &NodeType::initialise> InitialiseCaller; -TypeId getTypeId(){ + typedef typename Type::Name Name; + NodeType() : m_typeId( NODETYPEID_NONE ){ + StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); + } + void initialise(){ + m_typeId = GlobalSceneGraph().getNodeTypeId( Name() ); + } + typedef MemberCaller, &NodeType::initialise> InitialiseCaller; + TypeId getTypeId(){ #if defined( _DEBUG ) - ASSERT_MESSAGE( m_typeId != NODETYPEID_NONE, "node-type " << makeQuoted( Name() ) << " used before being initialised" ); + ASSERT_MESSAGE( m_typeId != NODETYPEID_NONE, "node-type " << makeQuoted( Name() ) << " used before being initialised" ); #endif - return m_typeId; -} + return m_typeId; + } }; template class StaticNodeType { public: -enum unnamed0 { SIZE = NODETYPEID_MAX }; -static TypeId getTypeId(){ - return Static< NodeType >::instance().getTypeId(); -} + enum unnamed0 { SIZE = NODETYPEID_MAX }; + static TypeId getTypeId(){ + return Static< NodeType >::instance().getTypeId(); + } }; template @@ -129,7 +129,7 @@ class NodeStaticCast : public CastInstaller< StaticNodeType, StaticCast - > + > { }; @@ -138,7 +138,7 @@ class NodeContainedCast : public CastInstaller< StaticNodeType, ContainedCast - > + > { }; @@ -147,7 +147,7 @@ class NodeIdentityCast : public CastInstaller< StaticNodeType, IdentityCast - > + > { }; @@ -156,99 +156,99 @@ namespace scene class Node { public: -enum unnamed0 { eVisible = 0 }; -enum unnamed1 { eHidden = 1 << 0 }; -enum unnamed2 { eFiltered = 1 << 1 }; -enum unnamed3 { eExcluded = 1 << 2 }; + enum unnamed0 { eVisible = 0 }; + enum unnamed1 { eHidden = 1 << 0 }; + enum unnamed2 { eFiltered = 1 << 1 }; + enum unnamed3 { eExcluded = 1 << 2 }; -class Symbiot -{ -public: -virtual void release() = 0; -virtual ~Symbiot(){ -} -}; + class Symbiot + { + public: + virtual void release() = 0; + virtual ~Symbiot(){ + } + }; private: -unsigned int m_state; -std::size_t m_refcount; -Symbiot* m_symbiot; -void* m_node; -NodeTypeCastTable& m_casts; + unsigned int m_state; + std::size_t m_refcount; + Symbiot* m_symbiot; + void* m_node; + NodeTypeCastTable& m_casts; public: -bool m_isRoot; + bool m_isRoot; -bool isRoot(){ - return m_isRoot; -} - -Node( Symbiot* symbiot, void* node, NodeTypeCastTable& casts ) : - m_state( eVisible ), - m_refcount( 0 ), - m_symbiot( symbiot ), - m_node( node ), - m_casts( casts ), - m_isRoot( false ){ -} -~Node(){ -} - -void IncRef(){ - ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); - ++m_refcount; -} -void DecRef(){ - ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); - if ( --m_refcount == 0 ) { - m_symbiot->release(); + bool isRoot(){ + return m_isRoot; } -} -std::size_t getReferenceCount() const { - return m_refcount; -} -void* cast( TypeId typeId ) const { - return m_casts.cast( typeId, m_node ); -} + Node( Symbiot* symbiot, void* node, NodeTypeCastTable& casts ) : + m_state( eVisible ), + m_refcount( 0 ), + m_symbiot( symbiot ), + m_node( node ), + m_casts( casts ), + m_isRoot( false ){ + } + ~Node(){ + } -void enable( unsigned int state ){ - m_state |= state; -} -void disable( unsigned int state ){ - m_state &= ~state; -} -bool visible(){ - return m_state == eVisible; -} -bool excluded(){ - return ( m_state & eExcluded ) != 0; -} -bool operator<( const scene::Node& other ){ - return this < &other; -} -bool operator==( const scene::Node& other ){ - return this == &other; -} -bool operator!=( const scene::Node& other ){ - return this != &other; -} + void IncRef(){ + ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); + ++m_refcount; + } + void DecRef(){ + ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); + if ( --m_refcount == 0 ) { + m_symbiot->release(); + } + } + std::size_t getReferenceCount() const { + return m_refcount; + } + + void* cast( TypeId typeId ) const { + return m_casts.cast( typeId, m_node ); + } + + void enable( unsigned int state ){ + m_state |= state; + } + void disable( unsigned int state ){ + m_state &= ~state; + } + bool visible(){ + return m_state == eVisible; + } + bool excluded(){ + return ( m_state & eExcluded ) != 0; + } + bool operator<( const scene::Node& other ){ + return this < &other; + } + bool operator==( const scene::Node& other ){ + return this == &other; + } + bool operator!=( const scene::Node& other ){ + return this != &other; + } }; class NullNode : public Node::Symbiot { -NodeTypeCastTable m_casts; -Node m_node; + NodeTypeCastTable m_casts; + Node m_node; public: -NullNode() : m_node( this, 0, m_casts ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + NullNode() : m_node( this, 0, m_casts ){ + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } }; } @@ -256,12 +256,12 @@ template class NodeTypeCast { public: -static Type* cast( scene::Node& node ){ - return static_cast( node.cast( StaticNodeType::getTypeId() ) ); -} -static const Type* cast( const scene::Node& node ){ - return static_cast( node.cast( StaticNodeType::getTypeId() ) ); -} + static Type* cast( scene::Node& node ){ + return static_cast( node.cast( StaticNodeType::getTypeId() ) ); + } + static const Type* cast( const scene::Node& node ){ + return static_cast( node.cast( StaticNodeType::getTypeId() ) ); + } }; @@ -302,16 +302,16 @@ inline void Path_deleteTop( const scene::Path& path ){ class delete_all : public scene::Traversable::Walker { -scene::Node& m_parent; + scene::Node& m_parent; public: -delete_all( scene::Node& parent ) : m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - return false; -} -void post( scene::Node& node ) const { - Node_getTraversable( m_parent )->erase( node ); -} + delete_all( scene::Node& parent ) : m_parent( parent ){ + } + bool pre( scene::Node& node ) const { + return false; + } + void post( scene::Node& node ) const { + Node_getTraversable( m_parent )->erase( node ); + } }; inline void DeleteSubgraph( scene::Node& subgraph ){ @@ -322,7 +322,7 @@ inline void DeleteSubgraph( scene::Node& subgraph ){ class EntityUndefined { public: -STRING_CONSTANT( Name, "Entity" ); + STRING_CONSTANT( Name, "Entity" ); }; inline bool Node_isEntity( scene::Node& node ){ @@ -332,17 +332,17 @@ inline bool Node_isEntity( scene::Node& node ){ template class EntityWalker : public scene::Graph::Walker { -const Functor& functor; + const Functor& functor; public: -EntityWalker( const Functor& functor ) : functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( Node_isEntity( path.top() ) ) { - functor( instance ); - return false; + EntityWalker( const Functor& functor ) : functor( functor ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( Node_isEntity( path.top() ) ) { + functor( instance ); + return false; + } + return true; } - return true; -} }; template @@ -354,7 +354,7 @@ inline const Functor& Scene_forEachEntity( const Functor& functor ){ class BrushUndefined { public: -STRING_CONSTANT( Name, "Brush" ); + STRING_CONSTANT( Name, "Brush" ); }; inline bool Node_isBrush( scene::Node& node ){ @@ -364,7 +364,7 @@ inline bool Node_isBrush( scene::Node& node ){ class PatchUndefined { public: -STRING_CONSTANT( Name, "Patch" ); + STRING_CONSTANT( Name, "Patch" ); }; inline bool Node_isPatch( scene::Node& node ){ @@ -381,19 +381,19 @@ inline bool Node_isPrimitive( scene::Node& node ){ class ParentBrushes : public scene::Traversable::Walker { -scene::Node& m_parent; + scene::Node& m_parent; public: -ParentBrushes( scene::Node& parent ) - : m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - return false; -} -void post( scene::Node& node ) const { - if ( Node_isPrimitive( node ) ) { - Node_getTraversable( m_parent )->insert( node ); + ParentBrushes( scene::Node& parent ) + : m_parent( parent ){ + } + bool pre( scene::Node& node ) const { + return false; + } + void post( scene::Node& node ) const { + if ( Node_isPrimitive( node ) ) { + Node_getTraversable( m_parent )->insert( node ); + } } -} }; inline void parentBrushes( scene::Node& subgraph, scene::Node& parent ){ @@ -402,18 +402,18 @@ inline void parentBrushes( scene::Node& subgraph, scene::Node& parent ){ class HasBrushes : public scene::Traversable::Walker { -bool& m_hasBrushes; + bool& m_hasBrushes; public: -HasBrushes( bool& hasBrushes ) - : m_hasBrushes( hasBrushes ){ - m_hasBrushes = true; -} -bool pre( scene::Node& node ) const { - if ( !Node_isPrimitive( node ) ) { - m_hasBrushes = false; + HasBrushes( bool& hasBrushes ) + : m_hasBrushes( hasBrushes ){ + m_hasBrushes = true; + } + bool pre( scene::Node& node ) const { + if ( !Node_isPrimitive( node ) ) { + m_hasBrushes = false; + } + return false; } - return false; -} }; inline bool node_is_group( scene::Node& node ){ @@ -431,32 +431,32 @@ typedef TypeCastTable InstanceTypeCastTable; template class InstanceType : public StaticTypeSystemInitialiser { -TypeId m_typeId; + TypeId m_typeId; public: -typedef typename Type::Name Name; -InstanceType() : m_typeId( INSTANCETYPEID_NONE ){ - StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); -} -void initialise(){ - m_typeId = GlobalSceneGraph().getInstanceTypeId( Name() ); -} -typedef MemberCaller, &InstanceType::initialise> InitialiseCaller; -TypeId getTypeId(){ + typedef typename Type::Name Name; + InstanceType() : m_typeId( INSTANCETYPEID_NONE ){ + StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); + } + void initialise(){ + m_typeId = GlobalSceneGraph().getInstanceTypeId( Name() ); + } + typedef MemberCaller, &InstanceType::initialise> InitialiseCaller; + TypeId getTypeId(){ #if defined( _DEBUG ) - ASSERT_MESSAGE( m_typeId != INSTANCETYPEID_NONE, "instance-type " << makeQuoted( Name() ) << " used before being initialised" ); + ASSERT_MESSAGE( m_typeId != INSTANCETYPEID_NONE, "instance-type " << makeQuoted( Name() ) << " used before being initialised" ); #endif - return m_typeId; -} + return m_typeId; + } }; template class StaticInstanceType { public: -enum unnamed0 { SIZE = INSTANCETYPEID_MAX }; -static TypeId getTypeId(){ - return Static< InstanceType >::instance().getTypeId(); -} + enum unnamed0 { SIZE = INSTANCETYPEID_MAX }; + static TypeId getTypeId(){ + return Static< InstanceType >::instance().getTypeId(); + } }; template @@ -464,7 +464,7 @@ class InstanceStaticCast : public CastInstaller< StaticInstanceType, StaticCast - > + > { }; @@ -473,7 +473,7 @@ class InstanceContainedCast : public CastInstaller< StaticInstanceType, ContainedCast - > + > { }; @@ -482,7 +482,7 @@ class InstanceIdentityCast : public CastInstaller< StaticInstanceType, IdentityCast - > + > { }; @@ -497,251 +497,251 @@ namespace scene { class Instance { -class AABBAccumulateWalker : public scene::Graph::Walker -{ -AABB& m_aabb; -mutable std::size_t m_depth; -public: -AABBAccumulateWalker( AABB& aabb ) : m_aabb( aabb ), m_depth( 0 ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_depth == 1 ) { - aabb_extend_by_aabb_safe( m_aabb, instance.worldAABB() ); - } - return ++m_depth != 2; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} -}; - - -class TransformChangedWalker : public scene::Graph::Walker -{ -public: -bool pre( const scene::Path& path, scene::Instance& instance ) const { - instance.transformChangedLocal(); - return true; -} -}; - -class ParentSelectedChangedWalker : public scene::Graph::Walker -{ -public: -bool pre( const scene::Path& path, scene::Instance& instance ) const { - instance.parentSelectedChanged(); - return true; -} -}; - -class ChildSelectedWalker : public scene::Graph::Walker -{ -bool& m_childSelected; -mutable std::size_t m_depth; -public: -ChildSelectedWalker( bool& childSelected ) : m_childSelected( childSelected ), m_depth( 0 ){ - m_childSelected = false; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_depth == 1 && !m_childSelected ) { - m_childSelected = instance.isSelected() || instance.childSelected(); - } - return ++m_depth != 2; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} -}; - -Path m_path; -Instance* m_parent; -void* m_instance; -InstanceTypeCastTable& m_casts; - -mutable Matrix4 m_local2world; -mutable AABB m_bounds; -mutable AABB m_childBounds; -mutable bool m_transformChanged; -mutable bool m_transformMutex; -mutable bool m_boundsChanged; -mutable bool m_boundsMutex; -mutable bool m_childBoundsChanged; -mutable bool m_childBoundsMutex; -mutable bool m_isSelected; -mutable bool m_isSelectedChanged; -mutable bool m_childSelected; -mutable bool m_childSelectedChanged; -mutable bool m_parentSelected; -mutable bool m_parentSelectedChanged; -Callback m_childSelectedChangedCallback; -Callback m_transformChangedCallback; - - -void evaluateTransform() const { - if ( m_transformChanged ) { - ASSERT_MESSAGE( !m_transformMutex, "re-entering transform evaluation" ); - m_transformMutex = true; - - m_local2world = ( m_parent != 0 ) ? m_parent->localToWorld() : g_matrix4_identity; - TransformNode* transformNode = Node_getTransformNode( m_path.top() ); - if ( transformNode != 0 ) { - matrix4_multiply_by_matrix4( m_local2world, transformNode->localToParent() ); + class AABBAccumulateWalker : public scene::Graph::Walker + { + AABB& m_aabb; + mutable std::size_t m_depth; + public: + AABBAccumulateWalker( AABB& aabb ) : m_aabb( aabb ), m_depth( 0 ){ } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_depth == 1 ) { + aabb_extend_by_aabb_safe( m_aabb, instance.worldAABB() ); + } + return ++m_depth != 2; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; + } + }; - m_transformMutex = false; - m_transformChanged = false; + + class TransformChangedWalker : public scene::Graph::Walker + { + public: + bool pre( const scene::Path& path, scene::Instance& instance ) const { + instance.transformChangedLocal(); + return true; + } + }; + + class ParentSelectedChangedWalker : public scene::Graph::Walker + { + public: + bool pre( const scene::Path& path, scene::Instance& instance ) const { + instance.parentSelectedChanged(); + return true; + } + }; + + class ChildSelectedWalker : public scene::Graph::Walker + { + bool& m_childSelected; + mutable std::size_t m_depth; + public: + ChildSelectedWalker( bool& childSelected ) : m_childSelected( childSelected ), m_depth( 0 ){ + m_childSelected = false; + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_depth == 1 && !m_childSelected ) { + m_childSelected = instance.isSelected() || instance.childSelected(); + } + return ++m_depth != 2; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; + } + }; + + Path m_path; + Instance* m_parent; + void* m_instance; + InstanceTypeCastTable& m_casts; + + mutable Matrix4 m_local2world; + mutable AABB m_bounds; + mutable AABB m_childBounds; + mutable bool m_transformChanged; + mutable bool m_transformMutex; + mutable bool m_boundsChanged; + mutable bool m_boundsMutex; + mutable bool m_childBoundsChanged; + mutable bool m_childBoundsMutex; + mutable bool m_isSelected; + mutable bool m_isSelectedChanged; + mutable bool m_childSelected; + mutable bool m_childSelectedChanged; + mutable bool m_parentSelected; + mutable bool m_parentSelectedChanged; + Callback m_childSelectedChangedCallback; + Callback m_transformChangedCallback; + + + void evaluateTransform() const { + if ( m_transformChanged ) { + ASSERT_MESSAGE( !m_transformMutex, "re-entering transform evaluation" ); + m_transformMutex = true; + + m_local2world = ( m_parent != 0 ) ? m_parent->localToWorld() : g_matrix4_identity; + TransformNode* transformNode = Node_getTransformNode( m_path.top() ); + if ( transformNode != 0 ) { + matrix4_multiply_by_matrix4( m_local2world, transformNode->localToParent() ); + } + + m_transformMutex = false; + m_transformChanged = false; + } } -} -void evaluateChildBounds() const { - if ( m_childBoundsChanged ) { - ASSERT_MESSAGE( !m_childBoundsMutex, "re-entering bounds evaluation" ); - m_childBoundsMutex = true; + void evaluateChildBounds() const { + if ( m_childBoundsChanged ) { + ASSERT_MESSAGE( !m_childBoundsMutex, "re-entering bounds evaluation" ); + m_childBoundsMutex = true; - m_childBounds = AABB(); + m_childBounds = AABB(); - GlobalSceneGraph().traverse_subgraph( AABBAccumulateWalker( m_childBounds ), m_path ); + GlobalSceneGraph().traverse_subgraph( AABBAccumulateWalker( m_childBounds ), m_path ); - m_childBoundsMutex = false; - m_childBoundsChanged = false; + m_childBoundsMutex = false; + m_childBoundsChanged = false; + } } -} -void evaluateBounds() const { - if ( m_boundsChanged ) { - ASSERT_MESSAGE( !m_boundsMutex, "re-entering bounds evaluation" ); - m_boundsMutex = true; + void evaluateBounds() const { + if ( m_boundsChanged ) { + ASSERT_MESSAGE( !m_boundsMutex, "re-entering bounds evaluation" ); + m_boundsMutex = true; - m_bounds = childBounds(); + m_bounds = childBounds(); - const Bounded* bounded = Instance_getBounded( *this ); - if ( bounded != 0 ) { - aabb_extend_by_aabb_safe( - m_bounds, - aabb_for_oriented_aabb_safe( bounded->localAABB(), localToWorld() ) + const Bounded* bounded = Instance_getBounded( *this ); + if ( bounded != 0 ) { + aabb_extend_by_aabb_safe( + m_bounds, + aabb_for_oriented_aabb_safe( bounded->localAABB(), localToWorld() ) ); + } + + m_boundsMutex = false; + m_boundsChanged = false; } - - m_boundsMutex = false; - m_boundsChanged = false; } -} -Instance( const scene::Instance& other ); -Instance& operator=( const scene::Instance& other ); + Instance( const scene::Instance& other ); + Instance& operator=( const scene::Instance& other ); public: -Instance( const scene::Path& path, Instance* parent, void* instance, InstanceTypeCastTable& casts ) : - m_path( path ), - m_parent( parent ), - m_instance( instance ), - m_casts( casts ), - m_local2world( g_matrix4_identity ), - m_transformChanged( true ), - m_transformMutex( false ), - m_boundsChanged( true ), - m_boundsMutex( false ), - m_childBoundsChanged( true ), - m_childBoundsMutex( false ), - m_isSelectedChanged( true ), - m_childSelectedChanged( true ), - m_parentSelectedChanged( true ){ - ASSERT_MESSAGE( ( parent == 0 ) == ( path.size() == 1 ), "instance has invalid parent" ); -} -virtual ~Instance(){ -} - -const scene::Path& path() const { - return m_path; -} - -void* cast( TypeId typeId ) const { - return m_casts.cast( typeId, m_instance ); -} - -const Matrix4& localToWorld() const { - evaluateTransform(); - return m_local2world; -} -void transformChangedLocal(){ - ASSERT_NOTNULL( m_parent ); - m_transformChanged = true; - m_boundsChanged = true; - m_childBoundsChanged = true; - m_transformChangedCallback(); -} -void transformChanged(){ - GlobalSceneGraph().traverse_subgraph( TransformChangedWalker(), m_path ); - boundsChanged(); -} -void setTransformChangedCallback( const Callback& callback ){ - m_transformChangedCallback = callback; -} - - -const AABB& worldAABB() const { - evaluateBounds(); - return m_bounds; -} -const AABB& childBounds() const { - evaluateChildBounds(); - return m_childBounds; -} -void boundsChanged(){ - m_boundsChanged = true; - m_childBoundsChanged = true; - if ( m_parent != 0 ) { - m_parent->boundsChanged(); + Instance( const scene::Path& path, Instance* parent, void* instance, InstanceTypeCastTable& casts ) : + m_path( path ), + m_parent( parent ), + m_instance( instance ), + m_casts( casts ), + m_local2world( g_matrix4_identity ), + m_transformChanged( true ), + m_transformMutex( false ), + m_boundsChanged( true ), + m_boundsMutex( false ), + m_childBoundsChanged( true ), + m_childBoundsMutex( false ), + m_isSelectedChanged( true ), + m_childSelectedChanged( true ), + m_parentSelectedChanged( true ){ + ASSERT_MESSAGE( ( parent == 0 ) == ( path.size() == 1 ), "instance has invalid parent" ); + } + virtual ~Instance(){ } - GlobalSceneGraph().boundsChanged(); -} -void childSelectedChanged(){ - m_childSelectedChanged = true; - m_childSelectedChangedCallback(); - if ( m_parent != 0 ) { - m_parent->childSelectedChanged(); + const scene::Path& path() const { + return m_path; } -} -bool childSelected() const { - if ( m_childSelectedChanged ) { - m_childSelectedChanged = false; - GlobalSceneGraph().traverse_subgraph( ChildSelectedWalker( m_childSelected ), m_path ); - } - return m_childSelected; -} -void setChildSelectedChangedCallback( const Callback& callback ){ - m_childSelectedChangedCallback = callback; -} -void selectedChanged(){ - m_isSelectedChanged = true; - if ( m_parent != 0 ) { - m_parent->childSelectedChanged(); + void* cast( TypeId typeId ) const { + return m_casts.cast( typeId, m_instance ); } - GlobalSceneGraph().traverse_subgraph( ParentSelectedChangedWalker(), m_path ); -} -bool isSelected() const { - if ( m_isSelectedChanged ) { - m_isSelectedChanged = false; - const Selectable* selectable = Instance_getSelectable( *this ); - m_isSelected = selectable != 0 && selectable->isSelected(); - } - return m_isSelected; -} -void parentSelectedChanged(){ - m_parentSelectedChanged = true; -} -bool parentSelected() const { - if ( m_parentSelectedChanged ) { - m_parentSelectedChanged = false; - m_parentSelected = m_parent != 0 && ( m_parent->isSelected() || m_parent->parentSelected() ); + const Matrix4& localToWorld() const { + evaluateTransform(); + return m_local2world; + } + void transformChangedLocal(){ + ASSERT_NOTNULL( m_parent ); + m_transformChanged = true; + m_boundsChanged = true; + m_childBoundsChanged = true; + m_transformChangedCallback(); + } + void transformChanged(){ + GlobalSceneGraph().traverse_subgraph( TransformChangedWalker(), m_path ); + boundsChanged(); + } + void setTransformChangedCallback( const Callback& callback ){ + m_transformChangedCallback = callback; + } + + + const AABB& worldAABB() const { + evaluateBounds(); + return m_bounds; + } + const AABB& childBounds() const { + evaluateChildBounds(); + return m_childBounds; + } + void boundsChanged(){ + m_boundsChanged = true; + m_childBoundsChanged = true; + if ( m_parent != 0 ) { + m_parent->boundsChanged(); + } + GlobalSceneGraph().boundsChanged(); + } + + void childSelectedChanged(){ + m_childSelectedChanged = true; + m_childSelectedChangedCallback(); + if ( m_parent != 0 ) { + m_parent->childSelectedChanged(); + } + } + bool childSelected() const { + if ( m_childSelectedChanged ) { + m_childSelectedChanged = false; + GlobalSceneGraph().traverse_subgraph( ChildSelectedWalker( m_childSelected ), m_path ); + } + return m_childSelected; + } + + void setChildSelectedChangedCallback( const Callback& callback ){ + m_childSelectedChangedCallback = callback; + } + void selectedChanged(){ + m_isSelectedChanged = true; + if ( m_parent != 0 ) { + m_parent->childSelectedChanged(); + } + GlobalSceneGraph().traverse_subgraph( ParentSelectedChangedWalker(), m_path ); + } + bool isSelected() const { + if ( m_isSelectedChanged ) { + m_isSelectedChanged = false; + const Selectable* selectable = Instance_getSelectable( *this ); + m_isSelected = selectable != 0 && selectable->isSelected(); + } + return m_isSelected; + } + + void parentSelectedChanged(){ + m_parentSelectedChanged = true; + } + bool parentSelected() const { + if ( m_parentSelectedChanged ) { + m_parentSelectedChanged = false; + m_parentSelected = m_parent != 0 && ( m_parent->isSelected() || m_parent->parentSelected() ); + } + return m_parentSelected; + } + Instance* parent() const + { + return m_parent; } - return m_parentSelected; -} -Instance* parent() const -{ - return m_parent; -} }; } @@ -749,65 +749,65 @@ template class InstanceTypeCast { public: -static Type* cast( scene::Instance& instance ){ - return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); -} -static const Type* cast( const scene::Instance& instance ){ - return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); -} + static Type* cast( scene::Instance& instance ){ + return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); + } + static const Type* cast( const scene::Instance& instance ){ + return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); + } }; template class InstanceWalker : public scene::Graph::Walker { -const Functor& m_functor; + const Functor& m_functor; public: -InstanceWalker( const Functor& functor ) : m_functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - //m_functor( instance ); - //return true; - if ( path.top().get().visible() ) { - m_functor( instance ); + InstanceWalker( const Functor& functor ) : m_functor( functor ){ } - else{ - return false; + bool pre( const scene::Path& path, scene::Instance& instance ) const { + //m_functor( instance ); + //return true; + if ( path.top().get().visible() ) { + m_functor( instance ); + } + else{ + return false; + } + return true; } - return true; -} }; template class ChildInstanceWalker : public scene::Graph::Walker { -const Functor& m_functor; -mutable std::size_t m_depth; + const Functor& m_functor; + mutable std::size_t m_depth; public: -ChildInstanceWalker( const Functor& functor ) : m_functor( functor ), m_depth( 0 ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_depth == 1 ) { - m_functor( instance ); + ChildInstanceWalker( const Functor& functor ) : m_functor( functor ), m_depth( 0 ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_depth == 1 ) { + m_functor( instance ); + } + return ++m_depth != 2; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; } - return ++m_depth != 2; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} }; template class InstanceApply : public Functor { public: -InstanceApply( const Functor& functor ) : Functor( functor ){ -} -void operator()( scene::Instance& instance ) const { - Type* result = InstanceTypeCast::cast( instance ); - if ( result != 0 ) { - Functor::operator()( *result ); + InstanceApply( const Functor& functor ) : Functor( functor ){ + } + void operator()( scene::Instance& instance ) const { + Type* result = InstanceTypeCast::cast( instance ); + if ( result != 0 ) { + Functor::operator()( *result ); + } } -} }; inline Selectable* Instance_getSelectable( scene::Instance& instance ){ @@ -824,13 +824,13 @@ inline void Scene_forEachChildSelectable( const Functor& functor, const scene::P class SelectableSetSelected { -bool m_selected; + bool m_selected; public: -SelectableSetSelected( bool selected ) : m_selected( selected ){ -} -void operator()( Selectable& selectable ) const { - selectable.setSelected( m_selected ); -} + SelectableSetSelected( bool selected ) : m_selected( selected ){ + } + void operator()( Selectable& selectable ) const { + selectable.setSelected( m_selected ); + } }; inline Bounded* Instance_getBounded( scene::Instance& instance ){ @@ -876,7 +876,7 @@ inline bool Instance_isSelected( const scene::Instance& instance ){ inline bool Instance_isSelectedComponents( scene::Instance& instance ){ ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); return componentSelectionTestable != 0 - && componentSelectionTestable->isSelectedComponents(); + && componentSelectionTestable->isSelectedComponents(); } inline scene::Instance& findInstance( const scene::Path& path ){ @@ -891,19 +891,19 @@ inline void selectPath( const scene::Path& path, bool selected ){ class SelectChildren : public scene::Traversable::Walker { -mutable scene::Path m_path; + mutable scene::Path m_path; public: -SelectChildren( const scene::Path& root ) - : m_path( root ){ -} -bool pre( scene::Node& node ) const { - m_path.push( makeReference( node ) ); - selectPath( m_path, true ); - return false; -} -void post( scene::Node& node ) const { - m_path.pop(); -} + SelectChildren( const scene::Path& root ) + : m_path( root ){ + } + bool pre( scene::Node& node ) const { + m_path.push( makeReference( node ) ); + selectPath( m_path, true ); + return false; + } + void post( scene::Node& node ) const { + m_path.pop(); + } }; inline void Entity_setSelected( scene::Instance& entity, bool selected ){ @@ -929,38 +929,38 @@ inline bool Entity_isSelected( scene::Instance& entity ){ class InstanceCounter { public: -unsigned int m_count; -InstanceCounter() : m_count( 0 ){ -} + unsigned int m_count; + InstanceCounter() : m_count( 0 ){ + } }; class Counter { public: -virtual void increment() = 0; -virtual void decrement() = 0; + virtual void increment() = 0; + virtual void decrement() = 0; }; class SimpleCounter : public Counter { -Callback m_countChanged; -std::size_t m_count; + Callback m_countChanged; + std::size_t m_count; public: -void setCountChangedCallback( const Callback& countChanged ){ - m_countChanged = countChanged; -} -void increment(){ - ++m_count; - m_countChanged(); -} -void decrement(){ - --m_count; - m_countChanged(); -} -std::size_t get() const { - return m_count; -} + void setCountChangedCallback( const Callback& countChanged ){ + m_countChanged = countChanged; + } + void increment(){ + ++m_count; + m_countChanged(); + } + void decrement(){ + --m_count; + m_countChanged(); + } + std::size_t get() const { + return m_count; + } }; diff --git a/libs/script/scripttokeniser.h b/libs/script/scripttokeniser.h index c3ff2b03..a086af25 100644 --- a/libs/script/scripttokeniser.h +++ b/libs/script/scripttokeniser.h @@ -26,312 +26,324 @@ class ScriptTokeniser final : public Tokeniser { -enum CharType -{ - eWhitespace, - eCharToken, - eNewline, - eCharQuote, - eCharSolidus, - eCharStar, - eCharSpecial, -}; - -typedef bool ( ScriptTokeniser::*Tokenise )( char c ); - -Tokenise m_stack[3]; -Tokenise* m_state; -SingleCharacterInputStreamDoubleBuffered m_istream; -std::size_t m_scriptline; -std::size_t m_scriptcolumn; - -char m_token[MAXTOKEN]; -char* m_write; - -char m_current; -bool m_eof; -bool m_crossline; -bool m_unget; -bool m_emit; - -bool m_special; - -CharType charType( const char c ){ - switch ( c ) + enum CharType { - case '\n': return eNewline; - case '"': return eCharQuote; - case '/': return eCharSolidus; - case '*': return eCharStar; - case '{': case '(': case '}': case ')': case '[': case ']': case ',': case ':': return ( m_special ) ? eCharSpecial : eCharToken; - } + eWhitespace, + eCharToken, + eNewline, + eCharQuote, + eCharSolidus, + eCharStar, + eCharSpecial, + }; - if ( c > 32 ) { - return eCharToken; - } - return eWhitespace; -} + typedef bool ( ScriptTokeniser::*Tokenise )( char c ); -Tokenise state(){ - return *m_state; -} -void push( Tokenise state ){ - ASSERT_MESSAGE( m_state != m_stack + 2, "token parser: illegal stack push" ); - *( ++m_state ) = state; -} -void pop(){ - ASSERT_MESSAGE( m_state != m_stack, "token parser: illegal stack pop" ); - --m_state; -} -void add( const char c ){ - if ( m_write < m_token + MAXTOKEN - 1 ) { - *m_write++ = c; - } -} -void remove(){ - ASSERT_MESSAGE( m_write > m_token, "no char to remove" ); - --m_write; -} + Tokenise m_stack[3]; + Tokenise* m_state; + SingleCharacterInputStreamDoubleBuffered m_istream; + std::size_t m_scriptline; + std::size_t m_scriptcolumn; -bool tokeniseDefault( char c ){ - switch ( charType( c ) ) - { - case eNewline: - if ( !m_crossline ) { - globalErrorStream() << Unsigned( getLine() ) << ":" << Unsigned( getColumn() ) << ": unexpected end-of-line before token\n"; - return false; + char m_token[MAXTOKEN]; + char* m_write; + + char m_current; + bool m_eof; + bool m_crossline; + bool m_unget; + bool m_emit; + + bool m_special; + + CharType charType( const char c ){ + switch ( c ) + { + case '\n': + return eNewline; + case '"': + return eCharQuote; + case '/': + return eCharSolidus; + case '*': + return eCharStar; + case '{': + case '(': + case '}': + case ')': + case '[': + case ']': + case ',': + case ':': + return ( m_special ) ? eCharSpecial : eCharToken; } - break; - case eCharToken: - case eCharStar: - push( Tokenise( &ScriptTokeniser::tokeniseToken ) ); - add( c ); - break; - case eCharSpecial: - push( Tokenise( &ScriptTokeniser::tokeniseSpecial ) ); - add( c ); - break; - case eCharQuote: - push( Tokenise( &ScriptTokeniser::tokeniseQuotedToken ) ); - break; - case eCharSolidus: - push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); - break; - default: - break; + + if ( c > 32 ) { + return eCharToken; + } + return eWhitespace; } - return true; -} -bool tokeniseToken( char c ){ - switch ( charType( c ) ) - { - case eNewline: - case eWhitespace: - case eCharQuote: - case eCharSpecial: - pop(); - m_emit = true; // emit token - break; - case eCharSolidus: + + Tokenise state(){ + return *m_state; + } + void push( Tokenise state ){ + ASSERT_MESSAGE( m_state != m_stack + 2, "token parser: illegal stack push" ); + *( ++m_state ) = state; + } + void pop(){ + ASSERT_MESSAGE( m_state != m_stack, "token parser: illegal stack pop" ); + --m_state; + } + void add( const char c ){ + if ( m_write < m_token + MAXTOKEN - 1 ) { + *m_write++ = c; + } + } + void remove(){ + ASSERT_MESSAGE( m_write > m_token, "no char to remove" ); + --m_write; + } + + bool tokeniseDefault( char c ){ + switch ( charType( c ) ) + { + case eNewline: + if ( !m_crossline ) { + globalErrorStream() << Unsigned( getLine() ) << ":" << Unsigned( getColumn() ) << ": unexpected end-of-line before token\n"; + return false; + } + break; + case eCharToken: + case eCharStar: + push( Tokenise( &ScriptTokeniser::tokeniseToken ) ); + add( c ); + break; + case eCharSpecial: + push( Tokenise( &ScriptTokeniser::tokeniseSpecial ) ); + add( c ); + break; + case eCharQuote: + push( Tokenise( &ScriptTokeniser::tokeniseQuotedToken ) ); + break; + case eCharSolidus: + push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); + break; + default: + break; + } + return true; + } + bool tokeniseToken( char c ){ + switch ( charType( c ) ) + { + case eNewline: + case eWhitespace: + case eCharQuote: + case eCharSpecial: + pop(); + m_emit = true; // emit token + break; + case eCharSolidus: #if 0 //SPoG: ignore comments in the middle of tokens. - push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); - break; + push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); + break; #endif - case eCharToken: - case eCharStar: - add( c ); - break; - default: - break; - } - return true; -} -bool tokeniseQuotedToken( char c ){ - switch ( charType( c ) ) - { - case eNewline: - if ( m_crossline ) { - globalErrorStream() << Unsigned( getLine() ) << ":" << Unsigned( getColumn() ) << ": unexpected end-of-line in quoted token\n"; - return false; + case eCharToken: + case eCharStar: + add( c ); + break; + default: + break; } - break; - case eWhitespace: - case eCharToken: - case eCharSolidus: - case eCharStar: - case eCharSpecial: - add( c ); - break; - case eCharQuote: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseEndQuote ) ); - break; - default: - break; + return true; } - return true; -} -bool tokeniseSolidus( char c ){ - switch ( charType( c ) ) - { - case eNewline: - case eWhitespace: - case eCharQuote: - case eCharSpecial: - pop(); - add( '/' ); - m_emit = true; // emit single slash - break; - case eCharToken: - pop(); - add( '/' ); - add( c ); - break; - case eCharSolidus: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseComment ) ); - break; // dont emit single slash - case eCharStar: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); - break; // dont emit single slash - default: - break; - } - return true; -} -bool tokeniseComment( char c ){ - if ( c == '\n' ) { - pop(); - if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { + bool tokeniseQuotedToken( char c ){ + switch ( charType( c ) ) + { + case eNewline: + if ( m_crossline ) { + globalErrorStream() << Unsigned( getLine() ) << ":" << Unsigned( getColumn() ) << ": unexpected end-of-line in quoted token\n"; + return false; + } + break; + case eWhitespace: + case eCharToken: + case eCharSolidus: + case eCharStar: + case eCharSpecial: + add( c ); + break; + case eCharQuote: pop(); - m_emit = true; // emit token immediatly preceding comment + push( Tokenise( &ScriptTokeniser::tokeniseEndQuote ) ); + break; + default: + break; } + return true; } - return true; -} -bool tokeniseBlockComment( char c ){ - if ( c == '*' ) { - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseEndBlockComment ) ); - } - return true; -} -bool tokeniseEndBlockComment( char c ){ - switch ( c ) - { - case '/': - pop(); - if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { + bool tokeniseSolidus( char c ){ + switch ( charType( c ) ) + { + case eNewline: + case eWhitespace: + case eCharQuote: + case eCharSpecial: pop(); - m_emit = true; // emit token immediatly preceding comment + add( '/' ); + m_emit = true; // emit single slash + break; + case eCharToken: + pop(); + add( '/' ); + add( c ); + break; + case eCharSolidus: + pop(); + push( Tokenise( &ScriptTokeniser::tokeniseComment ) ); + break; // dont emit single slash + case eCharStar: + pop(); + push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); + break; // dont emit single slash + default: + break; } - break; // dont emit comment - case '*': - break; // no state change - default: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); - break; + return true; + } + bool tokeniseComment( char c ){ + if ( c == '\n' ) { + pop(); + if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { + pop(); + m_emit = true; // emit token immediatly preceding comment + } + } + return true; + } + bool tokeniseBlockComment( char c ){ + if ( c == '*' ) { + pop(); + push( Tokenise( &ScriptTokeniser::tokeniseEndBlockComment ) ); + } + return true; + } + bool tokeniseEndBlockComment( char c ){ + switch ( c ) + { + case '/': + pop(); + if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { + pop(); + m_emit = true; // emit token immediatly preceding comment + } + break; // dont emit comment + case '*': + break; // no state change + default: + pop(); + push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); + break; + } + return true; + } + bool tokeniseEndQuote( char c ){ + pop(); + m_emit = true; // emit quoted token + return true; + } + bool tokeniseSpecial( char c ){ + pop(); + m_emit = true; // emit single-character token + return true; } - return true; -} -bool tokeniseEndQuote( char c ){ - pop(); - m_emit = true; // emit quoted token - return true; -} -bool tokeniseSpecial( char c ){ - pop(); - m_emit = true; // emit single-character token - return true; -} /// Returns true if a token was successfully parsed. -bool tokenise(){ - m_write = m_token; - while ( !eof() ) - { - char c = m_current; - - if ( !( ( *this ).*state() )( c ) ) { - // parse error - m_eof = true; - return false; - } - if ( m_emit ) { - m_emit = false; - return true; - } - - if ( c == '\n' ) { - ++m_scriptline; - m_scriptcolumn = 1; - } - else + bool tokenise(){ + m_write = m_token; + while ( !eof() ) { - ++m_scriptcolumn; + char c = m_current; + + if ( !( ( *this ).*state() )( c ) ) { + // parse error + m_eof = true; + return false; + } + if ( m_emit ) { + m_emit = false; + return true; + } + + if ( c == '\n' ) { + ++m_scriptline; + m_scriptcolumn = 1; + } + else + { + ++m_scriptcolumn; + } + + m_eof = !m_istream.readChar( m_current ); + } + return m_write != m_token; + } + + const char* fillToken(){ + if ( !tokenise() ) { + return 0; } - m_eof = !m_istream.readChar( m_current ); - } - return m_write != m_token; -} - -const char* fillToken(){ - if ( !tokenise() ) { - return 0; - } - - add( '\0' ); - return m_token; -} - -bool eof(){ - return m_eof; -} - -public: -ScriptTokeniser( TextInputStream& istream, bool special ) - : m_state( m_stack ), - m_istream( istream ), - m_scriptline( 1 ), - m_scriptcolumn( 1 ), - m_crossline( false ), - m_unget( false ), - m_emit( false ), - m_special( special ){ - m_stack[0] = Tokenise( &ScriptTokeniser::tokeniseDefault ); - m_eof = !m_istream.readChar( m_current ); - m_token[MAXTOKEN - 1] = '\0'; -} -void release(){ - delete this; -} -void nextLine(){ - m_crossline = true; -} -const char* getToken(){ - if ( m_unget ) { - m_unget = false; + add( '\0' ); return m_token; } - return fillToken(); -} -void ungetToken(){ - ASSERT_MESSAGE( !m_unget, "can't unget more than one token" ); - m_unget = true; -} -std::size_t getLine() const { - return m_scriptline; -} -std::size_t getColumn() const { - return m_scriptcolumn; -} -bool bufferContains( const char* str ){ - return m_istream.bufferContains( str ); -} + bool eof(){ + return m_eof; + } + +public: + ScriptTokeniser( TextInputStream& istream, bool special ) : + m_state( m_stack ), + m_istream( istream ), + m_scriptline( 1 ), + m_scriptcolumn( 1 ), + m_crossline( false ), + m_unget( false ), + m_emit( false ), + m_special( special ){ + m_stack[0] = Tokenise( &ScriptTokeniser::tokeniseDefault ); + m_eof = !m_istream.readChar( m_current ); + m_token[MAXTOKEN - 1] = '\0'; + } + void release(){ + delete this; + } + void nextLine(){ + m_crossline = true; + } + const char* getToken(){ + if ( m_unget ) { + m_unget = false; + return m_token; + } + + return fillToken(); + } + void ungetToken(){ + ASSERT_MESSAGE( !m_unget, "can't unget more than one token" ); + m_unget = true; + } + std::size_t getLine() const { + return m_scriptline; + } + std::size_t getColumn() const { + return m_scriptcolumn; + } + bool bufferContains( const char* str ){ + return m_istream.bufferContains( str ); + } }; diff --git a/libs/script/scripttokenwriter.h b/libs/script/scripttokenwriter.h index 27252313..35caed48 100644 --- a/libs/script/scripttokenwriter.h +++ b/libs/script/scripttokenwriter.h @@ -27,47 +27,47 @@ class SimpleTokenWriter final : public TokenWriter { public: -SimpleTokenWriter( TextOutputStream& ostream ) - : m_ostream( ostream ), m_separator( '\n' ){ -} -~SimpleTokenWriter(){ - writeSeparator(); -} -void release(){ - delete this; -} -void nextLine(){ - m_separator = '\n'; -} -void writeToken( const char* token ){ - ASSERT_MESSAGE( strchr( token, ' ' ) == 0, "token contains whitespace: " ); - writeSeparator(); - m_ostream << token; -} -void writeString( const char* string ){ - writeSeparator(); - m_ostream << '"' << string << '"'; -} -void writeInteger( int i ){ - writeSeparator(); - m_ostream << i; -} -void writeUnsigned( std::size_t i ){ - writeSeparator(); - m_ostream << Unsigned( i ); -} -void writeFloat( double f ){ - writeSeparator(); - m_ostream << Decimal( f ); -} + SimpleTokenWriter( TextOutputStream& ostream ) + : m_ostream( ostream ), m_separator( '\n' ){ + } + ~SimpleTokenWriter(){ + writeSeparator(); + } + void release(){ + delete this; + } + void nextLine(){ + m_separator = '\n'; + } + void writeToken( const char* token ){ + ASSERT_MESSAGE( strchr( token, ' ' ) == 0, "token contains whitespace: " ); + writeSeparator(); + m_ostream << token; + } + void writeString( const char* string ){ + writeSeparator(); + m_ostream << '"' << string << '"'; + } + void writeInteger( int i ){ + writeSeparator(); + m_ostream << i; + } + void writeUnsigned( std::size_t i ){ + writeSeparator(); + m_ostream << Unsigned( i ); + } + void writeFloat( double f ){ + writeSeparator(); + m_ostream << Decimal( f ); + } private: -void writeSeparator(){ - m_ostream << m_separator; - m_separator = ' '; -} -TextOutputStream& m_ostream; -char m_separator; + void writeSeparator(){ + m_ostream << m_separator; + m_separator = ' '; + } + TextOutputStream& m_ostream; + char m_separator; }; inline TokenWriter& NewSimpleTokenWriter( TextOutputStream& ostream ){ diff --git a/libs/selectionlib.h b/libs/selectionlib.h index 2862bad7..54a77328 100644 --- a/libs/selectionlib.h +++ b/libs/selectionlib.h @@ -29,92 +29,92 @@ class SelectableBool : public Selectable { -bool m_selected; + bool m_selected; public: -SelectableBool() - : m_selected( false ) -{} + SelectableBool() + : m_selected( false ) + {} -void setSelected( bool select = true ){ - m_selected = select; -} -bool isSelected() const { - return m_selected; -} + void setSelected( bool select = true ){ + m_selected = select; + } + bool isSelected() const { + return m_selected; + } }; class ObservedSelectable : public Selectable { -SelectionChangeCallback m_onchanged; -bool m_selected; + SelectionChangeCallback m_onchanged; + bool m_selected; public: -ObservedSelectable( const SelectionChangeCallback& onchanged ) : m_onchanged( onchanged ), m_selected( false ){ -} -ObservedSelectable( const ObservedSelectable& other ) : Selectable( other ), m_onchanged( other.m_onchanged ), m_selected( false ){ - setSelected( other.isSelected() ); -} -ObservedSelectable& operator=( const ObservedSelectable& other ){ - setSelected( other.isSelected() ); - return *this; -} -~ObservedSelectable(){ - setSelected( false ); -} - -void setSelected( bool select ){ - if ( select ^ m_selected ) { - m_selected = select; - - m_onchanged( *this ); + ObservedSelectable( const SelectionChangeCallback& onchanged ) : m_onchanged( onchanged ), m_selected( false ){ + } + ObservedSelectable( const ObservedSelectable& other ) : Selectable( other ), m_onchanged( other.m_onchanged ), m_selected( false ){ + setSelected( other.isSelected() ); + } + ObservedSelectable& operator=( const ObservedSelectable& other ){ + setSelected( other.isSelected() ); + return *this; + } + ~ObservedSelectable(){ + setSelected( false ); + } + + void setSelected( bool select ){ + if ( select ^ m_selected ) { + m_selected = select; + + m_onchanged( *this ); + } + } + bool isSelected() const { + return m_selected; } -} -bool isSelected() const { - return m_selected; -} }; class SelectableInstance : public scene::Instance { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceContainedCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceContainedCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -ObservedSelectable m_selectable; + ObservedSelectable m_selectable; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -SelectableInstance( const scene::Path& path, scene::Instance* parent, void* instance = 0, InstanceTypeCastTable& casts = StaticTypeCasts::instance().get() ) : - Instance( path, parent, instance != 0 ? instance : this, casts ), - m_selectable( SelectedChangedCaller( *this ) ){ -} + SelectableInstance( const scene::Path& path, scene::Instance* parent, void* instance = 0, InstanceTypeCastTable& casts = StaticTypeCasts::instance().get() ) : + Instance( path, parent, instance != 0 ? instance : this, casts ), + m_selectable( SelectedChangedCaller( *this ) ){ + } -Selectable& get( NullType){ - return m_selectable; -} + Selectable& get( NullType){ + return m_selectable; + } -Selectable& getSelectable(){ - return m_selectable; -} -const Selectable& getSelectable() const { - return m_selectable; -} + Selectable& getSelectable(){ + return m_selectable; + } + const Selectable& getSelectable() const { + return m_selectable; + } -void selectedChanged( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); - GlobalSelectionSystem().onSelectedChanged( *this, selectable ); + void selectedChanged( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); + GlobalSelectionSystem().onSelectedChanged( *this, selectable ); - Instance::selectedChanged(); -} -typedef MemberCaller1 SelectedChangedCaller; + Instance::selectedChanged(); + } + typedef MemberCaller1 SelectedChangedCaller; }; @@ -125,68 +125,68 @@ typedef MemberCaller1 class SelectionList { -typedef std::list List; -List m_selection; + typedef std::list List; + List m_selection; public: -typedef typename List::iterator iterator; -typedef typename List::const_iterator const_iterator; + typedef typename List::iterator iterator; + typedef typename List::const_iterator const_iterator; private: -struct Compare{ - using is_transparent = void; + struct Compare{ + using is_transparent = void; - bool operator()( const const_iterator& one, const const_iterator& other ) const { - return *one < *other; - } - bool operator()( const Selected* va, const const_iterator& it ) const { - return va < *it; - } - bool operator()( const const_iterator& it, const Selected* va ) const { - return *it < va; - } -}; -std::multiset m_set; + bool operator()( const const_iterator& one, const const_iterator& other ) const { + return *one < *other; + } + bool operator()( const Selected* va, const const_iterator& it ) const { + return va < *it; + } + bool operator()( const const_iterator& it, const Selected* va ) const { + return *it < va; + } + }; + std::multiset m_set; public: -SelectionList() = default; -SelectionList( const SelectionList& ) = delete; -SelectionList( SelectionList&& ) noexcept = delete; -SelectionList& operator=( const SelectionList& ) = delete; -SelectionList& operator=( SelectionList&& ) noexcept = delete; + SelectionList() = default; + SelectionList( const SelectionList& ) = delete; + SelectionList( SelectionList&& ) noexcept = delete; + SelectionList& operator=( const SelectionList& ) = delete; + SelectionList& operator=( SelectionList&& ) noexcept = delete; -iterator begin(){ - return m_selection.begin(); -} -const_iterator begin() const { - return m_selection.begin(); -} -iterator end(){ - return m_selection.end(); -} -const_iterator end() const { - return m_selection.end(); -} -bool empty() const { - return m_selection.empty(); -} -std::size_t size() const { - return m_selection.size(); -} -Selected& back(){ - return *m_selection.back(); -} -Selected& back() const { - return *m_selection.back(); -} -void append( Selected& selected ){ - m_selection.push_back( &selected ); - m_set.emplace( --end() ); -} -void erase( Selected& selected ){ - const auto it = m_set.find( &selected ); - ASSERT_MESSAGE( it != m_set.cend(), "selection-tracking error" ); - m_selection.erase( *it ); - m_set.erase( it ); -} + iterator begin(){ + return m_selection.begin(); + } + const_iterator begin() const { + return m_selection.begin(); + } + iterator end(){ + return m_selection.end(); + } + const_iterator end() const { + return m_selection.end(); + } + bool empty() const { + return m_selection.empty(); + } + std::size_t size() const { + return m_selection.size(); + } + Selected& back(){ + return *m_selection.back(); + } + Selected& back() const { + return *m_selection.back(); + } + void append( Selected& selected ){ + m_selection.push_back( &selected ); + m_set.emplace( --end() ); + } + void erase( Selected& selected ){ + const auto it = m_set.find( &selected ); + ASSERT_MESSAGE( it != m_set.cend(), "selection-tracking error" ); + m_selection.erase( *it ); + m_set.erase( it ); + } }; diff --git a/libs/shaderlib.h b/libs/shaderlib.h index ee972437..712c3f47 100644 --- a/libs/shaderlib.h +++ b/libs/shaderlib.h @@ -45,19 +45,19 @@ inline bool shader_equal_prefix( const char* string, const char* prefix ){ class shader_less_t { public: -bool operator()( const CopiedString& shader, const CopiedString& other ) const { - return shader_less( shader.c_str(), other.c_str() ); -} + bool operator()( const CopiedString& shader, const CopiedString& other ) const { + return shader_less( shader.c_str(), other.c_str() ); + } }; inline bool shader_valid( const char* shader ){ return string_is_ascii( shader ) - && strchr( shader, ' ' ) == 0 - && strchr( shader, '\n' ) == 0 - && strchr( shader, '\r' ) == 0 - && strchr( shader, '\t' ) == 0 - && strchr( shader, '\v' ) == 0 - && strchr( shader, '\\' ) == 0; + && strchr( shader, ' ' ) == 0 + && strchr( shader, '\n' ) == 0 + && strchr( shader, '\r' ) == 0 + && strchr( shader, '\t' ) == 0 + && strchr( shader, '\v' ) == 0 + && strchr( shader, '\\' ) == 0; } inline const char* GlobalTexturePrefix_get(){ diff --git a/libs/signal/isignal.h b/libs/signal/isignal.h index b6342190..7877b2f7 100644 --- a/libs/signal/isignal.h +++ b/libs/signal/isignal.h @@ -7,16 +7,16 @@ class SignalHandlerResult { -bool value; + bool value; public: -explicit SignalHandlerResult( bool value ) : value( value ){ -} -bool operator==( SignalHandlerResult other ) const { - return value == other.value; -} -bool operator!=( SignalHandlerResult other ) const { - return !operator==( other ); -} + explicit SignalHandlerResult( bool value ) : value( value ){ + } + bool operator==( SignalHandlerResult other ) const { + return value == other.value; + } + bool operator!=( SignalHandlerResult other ) const { + return !operator==( other ); + } }; const SignalHandlerResult SIGNAL_CONTINUE_EMISSION = SignalHandlerResult( false ); @@ -26,68 +26,68 @@ template class SignalHandlerCaller1 { public: -typedef typename Caller::first_argument_type first_argument_type; -typedef SignalHandlerResult result_type; -static result_type call( first_argument_type a1 ){ - Caller::call( a1 ); - return SIGNAL_CONTINUE_EMISSION; -} + typedef typename Caller::first_argument_type first_argument_type; + typedef SignalHandlerResult result_type; + static result_type call( first_argument_type a1 ){ + Caller::call( a1 ); + return SIGNAL_CONTINUE_EMISSION; + } }; template class SignalHandlerCaller2 { public: -typedef typename Caller::first_argument_type first_argument_type; -typedef typename Caller::second_argument_type second_argument_type; -typedef SignalHandlerResult result_type; -static result_type call( first_argument_type a1, second_argument_type a2 ){ - Caller::call( a1, a2 ); - return SIGNAL_CONTINUE_EMISSION; -} + typedef typename Caller::first_argument_type first_argument_type; + typedef typename Caller::second_argument_type second_argument_type; + typedef SignalHandlerResult result_type; + static result_type call( first_argument_type a1, second_argument_type a2 ){ + Caller::call( a1, a2 ); + return SIGNAL_CONTINUE_EMISSION; + } }; template class SignalHandlerCaller3 { public: -typedef typename Caller::first_argument_type first_argument_type; -typedef typename Caller::second_argument_type second_argument_type; -typedef typename Caller::third_argument_type third_argument_type; -typedef SignalHandlerResult result_type; -static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ - Caller::call( a1, a2, a3 ); - return SIGNAL_CONTINUE_EMISSION; -} + typedef typename Caller::first_argument_type first_argument_type; + typedef typename Caller::second_argument_type second_argument_type; + typedef typename Caller::third_argument_type third_argument_type; + typedef SignalHandlerResult result_type; + static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ + Caller::call( a1, a2, a3 ); + return SIGNAL_CONTINUE_EMISSION; + } }; template class SignalHandlerCaller4 { public: -typedef typename Caller::first_argument_type first_argument_type; -typedef typename Caller::second_argument_type second_argument_type; -typedef typename Caller::third_argument_type third_argument_type; -typedef typename Caller::fourth_argument_type fourth_argument_type; -typedef SignalHandlerResult result_type; -static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ - Caller::call( a1, a2, a3, a4 ); - return SIGNAL_CONTINUE_EMISSION; -} + typedef typename Caller::first_argument_type first_argument_type; + typedef typename Caller::second_argument_type second_argument_type; + typedef typename Caller::third_argument_type third_argument_type; + typedef typename Caller::fourth_argument_type fourth_argument_type; + typedef SignalHandlerResult result_type; + static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + Caller::call( a1, a2, a3, a4 ); + return SIGNAL_CONTINUE_EMISSION; + } }; class SignalHandler : public Callback0 { public: -template -SignalHandler( const BindFirstOpaque& caller ) - : Callback0( BindFirstOpaque, - typename Caller::result_type - >::type>( caller.getBound() ) ){ -} + template + SignalHandler( const BindFirstOpaque& caller ) + : Callback0( BindFirstOpaque, + typename Caller::result_type + >::type>( caller.getBound() ) ){ + } }; template @@ -104,15 +104,15 @@ template class SignalHandler1 : public Callback1 { public: -template -SignalHandler1( const BindFirstOpaque1& caller ) - : Callback1( BindFirstOpaque1, - typename Caller::result_type - >::type>( caller.getBound() ) ){ -} + template + SignalHandler1( const BindFirstOpaque1& caller ) + : Callback1( BindFirstOpaque1, + typename Caller::result_type + >::type>( caller.getBound() ) ){ + } }; template @@ -129,36 +129,36 @@ template class SignalHandler2 : public Callback2 { public: -template -SignalHandler2( const BindFirstOpaque2& caller ) - : Callback2( BindFirstOpaque2, - typename Caller::result_type - >::type>( caller.getBound() ) ){ -} + template + SignalHandler2( const BindFirstOpaque2& caller ) + : Callback2( BindFirstOpaque2, + typename Caller::result_type + >::type>( caller.getBound() ) ){ + } }; template inline SignalHandler2< - typename Caller::second_argument_type, - typename Caller::third_argument_type - > makeSignalHandler2( const BindFirstOpaque2& caller ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type +> makeSignalHandler2( const BindFirstOpaque2& caller ){ return SignalHandler2< - typename Caller::second_argument_type, - typename Caller::third_argument_type - >( caller ); + typename Caller::second_argument_type, + typename Caller::third_argument_type + >( caller ); } template inline SignalHandler2< - typename Caller::second_argument_type, - typename Caller::third_argument_type - > makeSignalHandler2( const Caller& caller, typename Caller::first_argument_type callee ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type +> makeSignalHandler2( const Caller& caller, typename Caller::first_argument_type callee ){ return SignalHandler2< - typename Caller::second_argument_type, - typename Caller::third_argument_type - >( BindFirstOpaque2( callee ) ); + typename Caller::second_argument_type, + typename Caller::third_argument_type + >( BindFirstOpaque2( callee ) ); } @@ -166,40 +166,40 @@ template { public: -template -SignalHandler3( const BindFirstOpaque3& caller ) - : Callback3( BindFirstOpaque3, - typename Caller::result_type - >::type>( caller.getBound() ) ){ -} + template + SignalHandler3( const BindFirstOpaque3& caller ) + : Callback3( BindFirstOpaque3, + typename Caller::result_type + >::type>( caller.getBound() ) ){ + } }; template inline SignalHandler3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type - > makeSignalHandler3( const BindFirstOpaque3& caller ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type +> makeSignalHandler3( const BindFirstOpaque3& caller ){ return SignalHandler3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type - >( caller ); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type + >( caller ); } template inline SignalHandler3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type - > makeSignalHandler3( const Caller& caller, typename Caller::first_argument_type callee ){ + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type +> makeSignalHandler3( const Caller& caller, typename Caller::first_argument_type callee ){ return SignalHandler3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type - >( BindFirstOpaque3( callee ) ); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type + >( BindFirstOpaque3( callee ) ); } #endif diff --git a/libs/signal/signal.h b/libs/signal/signal.h index f435f027..96b02f7c 100644 --- a/libs/signal/signal.h +++ b/libs/signal/signal.h @@ -69,229 +69,229 @@ template class NonConstTraits { public: -typedef Type value_type; -typedef value_type* pointer; -typedef value_type& reference; + typedef Type value_type; + typedef value_type* pointer; + typedef value_type& reference; -template -struct rebind -{ - typedef NonConstTraits other; -}; + template + struct rebind + { + typedef NonConstTraits other; + }; }; template class ConstTraits { public: -typedef Type value_type; -typedef const value_type* pointer; -typedef const value_type& reference; + typedef Type value_type; + typedef const value_type* pointer; + typedef const value_type& reference; -template -struct rebind -{ - typedef ConstTraits other; -}; + template + struct rebind + { + typedef ConstTraits other; + }; }; template class ListIterator { public: -typedef std::bidirectional_iterator_tag iterator_category; -typedef std::ptrdiff_t difference_type; -typedef difference_type distance_type; -typedef typename Traits::value_type value_type; -typedef typename Traits::pointer pointer; -typedef typename Traits::reference reference; + typedef std::bidirectional_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + typedef difference_type distance_type; + typedef typename Traits::value_type value_type; + typedef typename Traits::pointer pointer; + typedef typename Traits::reference reference; private: -typedef ListNode Node; -typedef typename Traits::template rebind::other NodeTraits; -typedef typename NodeTraits::pointer NodePointer; -typedef typename Traits::template rebind< Opaque >::other OpaqueTraits; -typedef typename OpaqueTraits::pointer OpaquePointer; -NodePointer m_node; + typedef ListNode Node; + typedef typename Traits::template rebind::other NodeTraits; + typedef typename NodeTraits::pointer NodePointer; + typedef typename Traits::template rebind< Opaque >::other OpaqueTraits; + typedef typename OpaqueTraits::pointer OpaquePointer; + NodePointer m_node; -void increment(){ - m_node = m_node->getNext(); -} -void decrement(){ - m_node = m_node->getPrev(); -} + void increment(){ + m_node = m_node->getNext(); + } + void decrement(){ + m_node = m_node->getPrev(); + } public: -explicit ListIterator( NodePointer node ) : m_node( node ){ -} -explicit ListIterator( OpaquePointer p ) : m_node( reinterpret_cast( p ) ){ -} + explicit ListIterator( NodePointer node ) : m_node( node ){ + } + explicit ListIterator( OpaquePointer p ) : m_node( reinterpret_cast( p ) ){ + } -NodePointer node(){ - return m_node; -} -OpaquePointer opaque() const { - return reinterpret_cast( m_node ); -} + NodePointer node(){ + return m_node; + } + OpaquePointer opaque() const { + return reinterpret_cast( m_node ); + } -bool operator==( const ListIterator& other ) const { - return m_node == other.m_node; -} -bool operator!=( const ListIterator& other ) const { - return !operator==( other ); -} -ListIterator& operator++(){ - increment(); - return *this; -} -ListIterator operator++( int ){ - ListIterator tmp = *this; - increment(); - return tmp; -} -ListIterator& operator--(){ - decrement(); - return *this; -} -ListIterator operator--( int ){ - ListIterator tmp = *this; - decrement(); - return tmp; -} -reference operator*() const { - return m_node->value; -} -pointer operator->() const { - return &( operator*() ); -} + bool operator==( const ListIterator& other ) const { + return m_node == other.m_node; + } + bool operator!=( const ListIterator& other ) const { + return !operator==( other ); + } + ListIterator& operator++(){ + increment(); + return *this; + } + ListIterator operator++( int ){ + ListIterator tmp = *this; + increment(); + return tmp; + } + ListIterator& operator--(){ + decrement(); + return *this; + } + ListIterator operator--( int ){ + ListIterator tmp = *this; + decrement(); + return tmp; + } + reference operator*() const { + return m_node->value; + } + pointer operator->() const { + return &( operator*() ); + } }; } template > class List : private Allocator { -typedef ListDetail::ListNode Node; -ListDetail::ListNodeBase list; -typedef typename Allocator::template rebind::other NodeAllocator; + typedef ListDetail::ListNode Node; + ListDetail::ListNodeBase list; + typedef typename Allocator::template rebind::other NodeAllocator; -Node* newNode( const Value& value ){ - return new ( NodeAllocator( *this ).allocate( 1 ) )Node( value ); -} -void deleteNode( Node* node ){ - node->~Node(); - NodeAllocator( *this ).deallocate( node, 1 ); -} -public: -typedef Value value_type; -typedef ListDetail::ListIterator< ListDetail::NonConstTraits > iterator; -typedef ListDetail::ListIterator< ListDetail::ConstTraits > const_iterator; - -List(){ - list_initialise( list ); -} -explicit List( const Allocator& allocator ) : Allocator( allocator ){ - list_initialise( list ); -} -~List(){ - for (; list.next != &list; ) - { - Node* node = static_cast( list.next ); - list.next = list.next->next; - deleteNode( node ); + Node* newNode( const Value& value ){ + return new ( NodeAllocator( *this ).allocate( 1 ) )Node( value ); + } + void deleteNode( Node* node ){ + node->~Node(); + NodeAllocator( *this ).deallocate( node, 1 ); + } +public: + typedef Value value_type; + typedef ListDetail::ListIterator< ListDetail::NonConstTraits > iterator; + typedef ListDetail::ListIterator< ListDetail::ConstTraits > const_iterator; + + List(){ + list_initialise( list ); + } + explicit List( const Allocator& allocator ) : Allocator( allocator ){ + list_initialise( list ); + } + ~List(){ + for (; list.next != &list; ) + { + Node* node = static_cast( list.next ); + list.next = list.next->next; + deleteNode( node ); + } + } + iterator begin(){ + return iterator( static_cast( list.next ) ); + } + iterator end(){ + return iterator( static_cast( &list ) ); + } + const_iterator begin() const { + return const_iterator( static_cast( list.next ) ); + } + const_iterator end() const { + return const_iterator( static_cast( &list ) ); + } + void push_back( const Value& value ){ + insert( end(), value ); + } + void pop_back( const Value& value ){ + erase( --end(), value ); + } + void push_front( const Value& value ){ + insert( begin(), value ); + } + void pop_front( const Value& value ){ + erase( begin(), value ); + } + iterator insert( iterator pos, const Value& value ){ + Node* node = newNode( value ); + node_link( node, pos.node() ); + return iterator( node ); + } + iterator erase( iterator pos ){ + Node* node = pos.node(); + Node* next = node->getNext(); + node_unlink( node ); + deleteNode( node ); + return iterator( next ); } -} -iterator begin(){ - return iterator( static_cast( list.next ) ); -} -iterator end(){ - return iterator( static_cast( &list ) ); -} -const_iterator begin() const { - return const_iterator( static_cast( list.next ) ); -} -const_iterator end() const { - return const_iterator( static_cast( &list ) ); -} -void push_back( const Value& value ){ - insert( end(), value ); -} -void pop_back( const Value& value ){ - erase( --end(), value ); -} -void push_front( const Value& value ){ - insert( begin(), value ); -} -void pop_front( const Value& value ){ - erase( begin(), value ); -} -iterator insert( iterator pos, const Value& value ){ - Node* node = newNode( value ); - node_link( node, pos.node() ); - return iterator( node ); -} -iterator erase( iterator pos ){ - Node* node = pos.node(); - Node* next = node->getNext(); - node_unlink( node ); - deleteNode( node ); - return iterator( next ); -} }; template class SignalBase { -typedef List SignalList; -SignalList events; + typedef List SignalList; + SignalList events; public: -typedef Functor handler_type; -typedef Handle< Opaque > handler_id_type; -typedef typename SignalList::iterator iterator; -typedef typename SignalList::const_iterator const_iterator; -iterator begin(){ - return events.begin(); -} -iterator end(){ - return events.end(); -} -const_iterator begin() const { - return events.begin(); -} -const_iterator end() const { - return events.end(); -} -handler_id_type connectFirst( const Functor& event ){ - events.push_front( event ); - return handler_id_type( begin().opaque() ); -} -handler_id_type connectLast( const Functor& event ){ - events.push_back( event ); - return handler_id_type( ( --end() ).opaque() ); -} -bool isConnected( handler_id_type id ){ - for ( iterator i = begin(); i != end(); ++i ) - { - if ( id.get() == i.opaque() ) { - return true; - } + typedef Functor handler_type; + typedef Handle< Opaque > handler_id_type; + typedef typename SignalList::iterator iterator; + typedef typename SignalList::const_iterator const_iterator; + iterator begin(){ + return events.begin(); + } + iterator end(){ + return events.end(); + } + const_iterator begin() const { + return events.begin(); + } + const_iterator end() const { + return events.end(); + } + handler_id_type connectFirst( const Functor& event ){ + events.push_front( event ); + return handler_id_type( begin().opaque() ); + } + handler_id_type connectLast( const Functor& event ){ + events.push_back( event ); + return handler_id_type( ( --end() ).opaque() ); + } + bool isConnected( handler_id_type id ){ + for ( iterator i = begin(); i != end(); ++i ) + { + if ( id.get() == i.opaque() ) { + return true; + } + } + return false; + } + handler_id_type connectBefore( handler_id_type id, const Functor& event ){ + ASSERT_MESSAGE( isConnected( id ), "SignalBase::connectBefore: invalid id" ); + return events.insert( iterator( id.get() ), event ).opaque(); + } + handler_id_type connectAfter( handler_id_type id, const Functor& event ){ + ASSERT_MESSAGE( isConnected( id ), "SignalBase::connectAfter: invalid id" ); + return events.insert( ++iterator( id.get() ), event ).opaque(); + } + void disconnect( handler_id_type id ){ + ASSERT_MESSAGE( isConnected( id ), "SignalBase::disconnect: invalid id" ); + events.erase( iterator( id.get() ) ); } - return false; -} -handler_id_type connectBefore( handler_id_type id, const Functor& event ){ - ASSERT_MESSAGE( isConnected( id ), "SignalBase::connectBefore: invalid id" ); - return events.insert( iterator( id.get() ), event ).opaque(); -} -handler_id_type connectAfter( handler_id_type id, const Functor& event ){ - ASSERT_MESSAGE( isConnected( id ), "SignalBase::connectAfter: invalid id" ); - return events.insert( ++iterator( id.get() ), event ).opaque(); -} -void disconnect( handler_id_type id ){ - ASSERT_MESSAGE( isConnected( id ), "SignalBase::disconnect: invalid id" ); - events.erase( iterator( id.get() ) ); -} }; ///\brief @@ -304,39 +304,39 @@ inline void invokeSignalHandlers( InputIterator first, InputIterator last, Signa class Signal0 : public SignalBase { public: -void operator()() const { - invokeSignalHandlers( begin(), end(), FunctorInvoke() ); -} + void operator()() const { + invokeSignalHandlers( begin(), end(), FunctorInvoke() ); + } }; template class Signal1 : public SignalBase< SignalHandler1 > { -typedef SignalBase< SignalHandler1 > Base; + typedef SignalBase< SignalHandler1 > Base; public: -void operator()( FirstArgument a1 ) const { - invokeSignalHandlers( Base::begin(), Base::end(), Functor1Invoke( a1 ) ); -} + void operator()( FirstArgument a1 ) const { + invokeSignalHandlers( Base::begin(), Base::end(), Functor1Invoke( a1 ) ); + } }; template class Signal2 : public SignalBase< SignalHandler2 > { -typedef SignalBase< SignalHandler2 > Base; + typedef SignalBase< SignalHandler2 > Base; public: -void operator()( FirstArgument a1, SecondArgument a2 ) const { - invokeSignalHandlers( Base::begin(), Base::end(), Functor2Invoke( a1, a2 ) ); -} + void operator()( FirstArgument a1, SecondArgument a2 ) const { + invokeSignalHandlers( Base::begin(), Base::end(), Functor2Invoke( a1, a2 ) ); + } }; template class Signal3 : public SignalBase< SignalHandler3 > { -typedef SignalBase< SignalHandler3 > Base; + typedef SignalBase< SignalHandler3 > Base; public: -void operator()( FirstArgument a1, SecondArgument a2, ThirdArgument a3 ) const { - invokeSignalHandlers( Base::begin(), Base::end(), Functor3Invoke( a1, a2, a3 ) ); -} + void operator()( FirstArgument a1, SecondArgument a2, ThirdArgument a3 ) const { + invokeSignalHandlers( Base::begin(), Base::end(), Functor3Invoke( a1, a2, a3 ) ); + } }; #endif diff --git a/libs/signal/signalfwd.h b/libs/signal/signalfwd.h index 507c0e70..6427b1c4 100644 --- a/libs/signal/signalfwd.h +++ b/libs/signal/signalfwd.h @@ -18,25 +18,25 @@ class Opaque; template class Handle { -Type* p; + Type* p; public: -Handle() : p( 0 ){ -} -explicit Handle( Type* p ) : p( p ){ -} -Type* get() const { - return p; -} -bool isNull() const { - return p == 0; -} + Handle() : p( 0 ){ + } + explicit Handle( Type* p ) : p( p ){ + } + Type* get() const { + return p; + } + bool isNull() const { + return p == 0; + } }; template class SignalFwd { public: -typedef Handle< Opaque > handler_id_type; + typedef Handle< Opaque > handler_id_type; }; typedef SignalFwd::handler_id_type SignalHandlerId; diff --git a/libs/splines/math_angles.h b/libs/splines/math_angles.h index f356b569..ee1d1f82 100644 --- a/libs/splines/math_angles.h +++ b/libs/splines/math_angles.h @@ -34,50 +34,50 @@ typedef idVec3 &vec3_p; class angles_t { public: -float pitch; -float yaw; -float roll; + float pitch; + float yaw; + float roll; -angles_t(); -angles_t( float pitch, float yaw, float roll ); -angles_t( const idVec3 &vec ); + angles_t(); + angles_t( float pitch, float yaw, float roll ); + angles_t( const idVec3 &vec ); -friend void toAngles( idVec3 &src, angles_t &dst ); -friend void toAngles( quat_t &src, angles_t &dst ); -friend void toAngles( mat3_t &src, angles_t &dst ); + friend void toAngles( idVec3 &src, angles_t &dst ); + friend void toAngles( quat_t &src, angles_t &dst ); + friend void toAngles( mat3_t &src, angles_t &dst ); -operator vec3_p(); + operator vec3_p(); -float operator[]( int index ) const; -float& operator[]( int index ); + float operator[]( int index ) const; + float& operator[]( int index ); -void set( float pitch, float yaw, float roll ); + void set( float pitch, float yaw, float roll ); -void operator=( angles_t const &a ); -void operator=( idVec3 const &a ); + void operator=( angles_t const &a ); + void operator=( idVec3 const &a ); -friend angles_t operator+( const angles_t &a, const angles_t &b ); -angles_t &operator+=( angles_t const &a ); -angles_t &operator+=( idVec3 const &a ); + friend angles_t operator+( const angles_t &a, const angles_t &b ); + angles_t &operator+=( angles_t const &a ); + angles_t &operator+=( idVec3 const &a ); -friend angles_t operator-( angles_t &a, angles_t &b ); -angles_t &operator-=( angles_t &a ); + friend angles_t operator-( angles_t &a, angles_t &b ); + angles_t &operator-=( angles_t &a ); -friend angles_t operator*( const angles_t &a, float b ); -friend angles_t operator*( float a, const angles_t &b ); -angles_t &operator*=( float a ); + friend angles_t operator*( const angles_t &a, float b ); + friend angles_t operator*( float a, const angles_t &b ); + angles_t &operator*=( float a ); -friend int operator==( angles_t &a, angles_t &b ); + friend int operator==( angles_t &a, angles_t &b ); -friend int operator!=( angles_t &a, angles_t &b ); + friend int operator!=( angles_t &a, angles_t &b ); -void toVectors( idVec3 *forward, idVec3 *right = NULL, idVec3 *up = NULL ); -idVec3 toForward( void ); + void toVectors( idVec3 *forward, idVec3 *right = NULL, idVec3 *up = NULL ); + idVec3 toForward( void ); -angles_t &Zero( void ); + angles_t &Zero( void ); -angles_t &Normalize360( void ); -angles_t &Normalize180( void ); + angles_t &Normalize360( void ); + angles_t &Normalize180( void ); }; extern angles_t ang_zero; diff --git a/libs/splines/math_matrix.h b/libs/splines/math_matrix.h index 8b653b0e..38061d5c 100644 --- a/libs/splines/math_matrix.h +++ b/libs/splines/math_matrix.h @@ -38,46 +38,46 @@ class angles_t; class mat3_t { public: -idVec3 mat[ 3 ]; + idVec3 mat[ 3 ]; -mat3_t(); -mat3_t( float src[ 3 ][ 3 ] ); -mat3_t( idVec3 const &x, idVec3 const &y, idVec3 const &z ); -mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ); + mat3_t(); + mat3_t( float src[ 3 ][ 3 ] ); + mat3_t( idVec3 const &x, idVec3 const &y, idVec3 const &z ); + mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ); -friend void toMatrix( quat_t const &src, mat3_t &dst ); -friend void toMatrix( angles_t const &src, mat3_t &dst ); -friend void toMatrix( idVec3 const &src, mat3_t &dst ); + friend void toMatrix( quat_t const &src, mat3_t &dst ); + friend void toMatrix( angles_t const &src, mat3_t &dst ); + friend void toMatrix( idVec3 const &src, mat3_t &dst ); -idVec3 operator[]( int index ) const; -idVec3 &operator[]( int index ); + idVec3 operator[]( int index ) const; + idVec3 &operator[]( int index ); -idVec3 operator*( const idVec3 &vec ) const; -mat3_t operator*( const mat3_t &a ) const; -mat3_t operator*( float a ) const; -mat3_t operator+( mat3_t const &a ) const; -mat3_t operator-( mat3_t const &a ) const; + idVec3 operator*( const idVec3 &vec ) const; + mat3_t operator*( const mat3_t &a ) const; + mat3_t operator*( float a ) const; + mat3_t operator+( mat3_t const &a ) const; + mat3_t operator-( mat3_t const &a ) const; -friend idVec3 operator*( const idVec3 &vec, const mat3_t &mat ); -friend mat3_t operator*( float a, mat3_t const &b ); + friend idVec3 operator*( const idVec3 &vec, const mat3_t &mat ); + friend mat3_t operator*( float a, mat3_t const &b ); -mat3_t &operator*=( float a ); -mat3_t &operator+=( mat3_t const &a ); -mat3_t &operator-=( mat3_t const &a ); + mat3_t &operator*=( float a ); + mat3_t &operator+=( mat3_t const &a ); + mat3_t &operator-=( mat3_t const &a ); -void Clear( void ); + void Clear( void ); -void ProjectVector( const idVec3 &src, idVec3 &dst ) const; -void UnprojectVector( const idVec3 &src, idVec3 &dst ) const; + void ProjectVector( const idVec3 &src, idVec3 &dst ) const; + void UnprojectVector( const idVec3 &src, idVec3 &dst ) const; -void OrthoNormalize( void ); -void Transpose( mat3_t &matrix ); -void Transpose( void ); -mat3_t Inverse( void ) const; -void Identity( void ); + void OrthoNormalize( void ); + void Transpose( mat3_t &matrix ); + void Transpose( void ); + mat3_t Inverse( void ) const; + void Identity( void ); -friend void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ); -friend mat3_t SkewSymmetric( idVec3 const &src ); + friend void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ); + friend mat3_t SkewSymmetric( idVec3 const &src ); }; ID_INLINE mat3_t::mat3_t() { @@ -116,57 +116,57 @@ ID_INLINE idVec3& mat3_t::operator[]( int index ) { ID_INLINE idVec3 mat3_t::operator*( const idVec3 &vec ) const { return idVec3( - mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, - mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, - mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); + mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, + mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, + mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); } ID_INLINE mat3_t mat3_t::operator*( const mat3_t &a ) const { return mat3_t( - mat[0].x * a[0].x + mat[0].y * a[1].x + mat[0].z * a[2].x, - mat[0].x * a[0].y + mat[0].y * a[1].y + mat[0].z * a[2].y, - mat[0].x * a[0].z + mat[0].y * a[1].z + mat[0].z * a[2].z, - mat[1].x * a[0].x + mat[1].y * a[1].x + mat[1].z * a[2].x, - mat[1].x * a[0].y + mat[1].y * a[1].y + mat[1].z * a[2].y, - mat[1].x * a[0].z + mat[1].y * a[1].z + mat[1].z * a[2].z, - mat[2].x * a[0].x + mat[2].y * a[1].x + mat[2].z * a[2].x, - mat[2].x * a[0].y + mat[2].y * a[1].y + mat[2].z * a[2].y, - mat[2].x * a[0].z + mat[2].y * a[1].z + mat[2].z * a[2].z ); + mat[0].x * a[0].x + mat[0].y * a[1].x + mat[0].z * a[2].x, + mat[0].x * a[0].y + mat[0].y * a[1].y + mat[0].z * a[2].y, + mat[0].x * a[0].z + mat[0].y * a[1].z + mat[0].z * a[2].z, + mat[1].x * a[0].x + mat[1].y * a[1].x + mat[1].z * a[2].x, + mat[1].x * a[0].y + mat[1].y * a[1].y + mat[1].z * a[2].y, + mat[1].x * a[0].z + mat[1].y * a[1].z + mat[1].z * a[2].z, + mat[2].x * a[0].x + mat[2].y * a[1].x + mat[2].z * a[2].x, + mat[2].x * a[0].y + mat[2].y * a[1].y + mat[2].z * a[2].y, + mat[2].x * a[0].z + mat[2].y * a[1].z + mat[2].z * a[2].z ); } ID_INLINE mat3_t mat3_t::operator*( float a ) const { return mat3_t( - mat[0].x * a, mat[0].y * a, mat[0].z * a, - mat[1].x * a, mat[1].y * a, mat[1].z * a, - mat[2].x * a, mat[2].y * a, mat[2].z * a ); + mat[0].x * a, mat[0].y * a, mat[0].z * a, + mat[1].x * a, mat[1].y * a, mat[1].z * a, + mat[2].x * a, mat[2].y * a, mat[2].z * a ); } ID_INLINE mat3_t mat3_t::operator+( mat3_t const &a ) const { return mat3_t( - mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, - mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, - mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z ); + mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, + mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, + mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z ); } ID_INLINE mat3_t mat3_t::operator-( mat3_t const &a ) const { return mat3_t( - mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, - mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, - mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z ); + mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, + mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, + mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z ); } ID_INLINE idVec3 operator*( const idVec3 &vec, const mat3_t &mat ) { return idVec3( - mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, - mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, - mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); + mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, + mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, + mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); } ID_INLINE mat3_t operator*( float a, mat3_t const &b ) { return mat3_t( - b[0].x * a, b[0].y * a, b[0].z * a, - b[1].x * a, b[1].y * a, b[1].z * a, - b[2].x * a, b[2].y * a, b[2].z * a ); + b[0].x * a, b[0].y * a, b[0].z * a, + b[1].x * a, b[1].y * a, b[1].z * a, + b[2].x * a, b[2].y * a, b[2].z * a ); } ID_INLINE mat3_t &mat3_t::operator*=( float a ) { diff --git a/libs/splines/math_quaternion.h b/libs/splines/math_quaternion.h index 8632661d..4600006a 100644 --- a/libs/splines/math_quaternion.h +++ b/libs/splines/math_quaternion.h @@ -31,44 +31,44 @@ class mat3_t; class quat_t { public: -float x; -float y; -float z; -float w; + float x; + float y; + float z; + float w; -quat_t(); -quat_t( float x, float y, float z, float w ); + quat_t(); + quat_t( float x, float y, float z, float w ); -friend void toQuat( idVec3_t &src, quat_t &dst ); -friend void toQuat( angles_t &src, quat_t &dst ); -friend void toQuat( mat3_t &src, quat_t &dst ); + friend void toQuat( idVec3_t &src, quat_t &dst ); + friend void toQuat( angles_t &src, quat_t &dst ); + friend void toQuat( mat3_t &src, quat_t &dst ); -float *vec4( void ); + float *vec4( void ); -float operator[]( int index ) const; -float &operator[]( int index ); + float operator[]( int index ) const; + float &operator[]( int index ); -void set( float x, float y, float z, float w ); + void set( float x, float y, float z, float w ); -void operator=( quat_t a ); + void operator=( quat_t a ); -friend quat_t operator+( quat_t a, quat_t b ); -quat_t &operator+=( quat_t a ); + friend quat_t operator+( quat_t a, quat_t b ); + quat_t &operator+=( quat_t a ); -friend quat_t operator-( quat_t a, quat_t b ); -quat_t &operator-=( quat_t a ); + friend quat_t operator-( quat_t a, quat_t b ); + quat_t &operator-=( quat_t a ); -friend quat_t operator*( quat_t a, float b ); -friend quat_t operator*( float a, quat_t b ); -quat_t &operator*=( float a ); + friend quat_t operator*( quat_t a, float b ); + friend quat_t operator*( float a, quat_t b ); + quat_t &operator*=( float a ); -friend int operator==( quat_t a, quat_t b ); -friend int operator!=( quat_t a, quat_t b ); + friend int operator==( quat_t a, quat_t b ); + friend int operator!=( quat_t a, quat_t b ); -float Length( void ); -quat_t &Normalize( void ); + float Length( void ); + quat_t &Normalize( void ); -quat_t operator-(); + quat_t operator-(); }; inline quat_t::quat_t() { diff --git a/libs/splines/math_vector.h b/libs/splines/math_vector.h index dde07257..03eb9270 100644 --- a/libs/splines/math_vector.h +++ b/libs/splines/math_vector.h @@ -126,59 +126,61 @@ static inline double idSqrt( double x ) { class idVec3 { public: #ifndef FAT_VEC3 -float x,y,z; + float x,y,z; #else -float x,y,z,dist; + float x,y,z,dist; #endif #ifndef FAT_VEC3 -idVec3() {}; + idVec3() {}; #else -idVec3() {dist = 0.0f; }; + idVec3() { + dist = 0.0f; + }; #endif -idVec3( const float x, const float y, const float z ); + idVec3( const float x, const float y, const float z ); -operator float *(); + operator float *(); -float operator[]( const int index ) const; -float &operator[]( const int index ); + float operator[]( const int index ) const; + float &operator[]( const int index ); -void set( const float x, const float y, const float z ); + void set( const float x, const float y, const float z ); -idVec3 operator-() const; + idVec3 operator-() const; -idVec3 &operator=( const idVec3 &a ); + idVec3 &operator=( const idVec3 &a ); -float operator*( const idVec3 &a ) const; -idVec3 operator*( const float a ) const; -friend idVec3 operator*( float a, idVec3 b ); + float operator*( const idVec3 &a ) const; + idVec3 operator*( const float a ) const; + friend idVec3 operator*( float a, idVec3 b ); -idVec3 operator+( const idVec3 &a ) const; -idVec3 operator-( const idVec3 &a ) const; + idVec3 operator+( const idVec3 &a ) const; + idVec3 operator-( const idVec3 &a ) const; -idVec3 &operator+=( const idVec3 &a ); -idVec3 &operator-=( const idVec3 &a ); -idVec3 &operator*=( const float a ); + idVec3 &operator+=( const idVec3 &a ); + idVec3 &operator-=( const idVec3 &a ); + idVec3 &operator*=( const float a ); -int operator==( const idVec3 &a ) const; -int operator!=( const idVec3 &a ) const; + int operator==( const idVec3 &a ) const; + int operator!=( const idVec3 &a ) const; -idVec3 Cross( const idVec3 &a ) const; -idVec3 &Cross( const idVec3 &a, const idVec3 &b ); + idVec3 Cross( const idVec3 &a ) const; + idVec3 &Cross( const idVec3 &a, const idVec3 &b ); -float Length( void ) const; -float Normalize( void ); + float Length( void ) const; + float Normalize( void ); -void Zero( void ); -void Snap( void ); -void SnapTowards( const idVec3 &to ); + void Zero( void ); + void Snap( void ); + void SnapTowards( const idVec3 &to ); -float toYaw( void ); -float toPitch( void ); -angles_t toAngles( void ); -friend idVec3 LerpVector( const idVec3 &w1, const idVec3 &w2, const float t ); + float toYaw( void ); + float toPitch( void ); + angles_t toAngles( void ); + friend idVec3 LerpVector( const idVec3 &w1, const idVec3 &w2, const float t ); -char *string( void ); + char *string( void ); }; extern idVec3 vec_zero; @@ -381,20 +383,20 @@ ID_INLINE void idVec3::SnapTowards( const idVec3 &to ) { class Bounds { public: -idVec3 b[2]; + idVec3 b[2]; -Bounds(); -Bounds( const idVec3 &mins, const idVec3 &maxs ); + Bounds(); + Bounds( const idVec3 &mins, const idVec3 &maxs ); -void Clear(); -void Zero(); -float Radius(); // radius from origin, not from center -idVec3 Center(); -void AddPoint( const idVec3 &v ); -void AddBounds( const Bounds &bb ); -bool IsCleared(); -bool ContainsPoint( const idVec3 &p ); -bool IntersectsBounds( const Bounds &b2 ); // touching is NOT intersecting + void Clear(); + void Zero(); + float Radius(); // radius from origin, not from center + idVec3 Center(); + void AddPoint( const idVec3 &v ); + void AddBounds( const Bounds &bb ); + bool IsCleared(); + bool ContainsPoint( const idVec3 &p ); + bool IntersectsBounds( const Bounds &b2 ); // touching is NOT intersecting }; extern Bounds boundsZero; @@ -408,7 +410,7 @@ ID_INLINE bool Bounds::IsCleared() { ID_INLINE bool Bounds::ContainsPoint( const idVec3 &p ) { if ( p[0] < b[0][0] || p[1] < b[0][1] || p[2] < b[0][2] - || p[0] > b[1][0] || p[1] > b[1][1] || p[2] > b[1][2] ) { + || p[0] > b[1][0] || p[1] > b[1][1] || p[2] > b[1][2] ) { return false; } return true; @@ -416,7 +418,7 @@ ID_INLINE bool Bounds::ContainsPoint( const idVec3 &p ) { ID_INLINE bool Bounds::IntersectsBounds( const Bounds &b2 ) { if ( b2.b[1][0] < b[0][0] || b2.b[1][1] < b[0][1] || b2.b[1][2] < b[0][2] - || b2.b[0][0] > b[1][0] || b2.b[0][1] > b[1][1] || b2.b[0][2] > b[1][2] ) { + || b2.b[0][0] > b[1][0] || b2.b[0][1] > b[1][1] || b2.b[0][2] > b[1][2] ) { return false; } return true; @@ -438,7 +440,7 @@ ID_INLINE void Bounds::Clear() { ID_INLINE void Bounds::Zero() { b[0][0] = b[0][1] = b[0][2] = - b[1][0] = b[1][1] = b[1][2] = 0; + b[1][0] = b[1][1] = b[1][2] = 0; } ID_INLINE void Bounds::AddPoint( const idVec3 &v ) { @@ -508,12 +510,12 @@ ID_INLINE float Bounds::Radius() { class idVec2 { public: -float x; -float y; + float x; + float y; -operator float *(); -float operator[]( int index ) const; -float &operator[]( int index ); + operator float *(); + float operator[]( int index ) const; + float &operator[]( int index ); }; ID_INLINE float idVec2::operator[]( int index ) const { @@ -531,14 +533,14 @@ ID_INLINE idVec2::operator float *( void ) { class idVec4 : public idVec3 { public: #ifndef FAT_VEC3 -float dist; + float dist; #endif -idVec4(); -~idVec4() {}; + idVec4(); + ~idVec4() {}; -idVec4( float x, float y, float z, float dist ); -float operator[]( int index ) const; -float &operator[]( int index ); + idVec4( float x, float y, float z, float dist ); + float operator[]( int index ) const; + float &operator[]( int index ); }; ID_INLINE idVec4::idVec4() {} @@ -560,10 +562,10 @@ ID_INLINE float& idVec4::operator[]( int index ) { class idVec5_t : public idVec3 { public: -float s; -float t; -float operator[]( int index ) const; -float &operator[]( int index ); + float s; + float t; + float operator[]( int index ) const; + float &operator[]( int index ); }; diff --git a/libs/splines/q_parse.cpp b/libs/splines/q_parse.cpp index 528b1f77..653d46c2 100644 --- a/libs/splines/q_parse.cpp +++ b/libs/splines/q_parse.cpp @@ -252,7 +252,7 @@ static char *Com_ParseExt( const char *( *data_p ), qboolean allowLineBreaks ) { // check for a number // is this parsing of negative numbers going to cause expression problems if ( ( c >= '0' && c <= '9' ) || ( c == '-' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) || - ( c == '.' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ) { + ( c == '.' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ) { do { if ( len < MAX_TOKEN_CHARS - 1 ) { @@ -315,7 +315,7 @@ static char *Com_ParseExt( const char *( *data_p ), qboolean allowLineBreaks ) { c = *data; } while ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_' - || ( c >= '0' && c <= '9' ) || c == '/' || c == '\\' || c == ':' || c == '.' ); + || ( c >= '0' && c <= '9' ) || c == '/' || c == '\\' || c == ':' || c == '.' ); if ( len == MAX_TOKEN_CHARS ) { len = 0; diff --git a/libs/splines/q_shared.cpp b/libs/splines/q_shared.cpp index 033a6ee3..7bcc3c91 100644 --- a/libs/splines/q_shared.cpp +++ b/libs/splines/q_shared.cpp @@ -81,7 +81,7 @@ int Com_AddToGrowList( growList_t *list, void *data ) { void *Com_GrowListElement( const growList_t *list, int index ) { if ( index < 0 || index >= list->currentElements ) { Com_Error( ERR_DROP, "Com_GrowListElement: %i out of range of %i", - index, list->currentElements ); + index, list->currentElements ); } return list->elements[index]; } @@ -190,7 +190,7 @@ int Com_Filter( const char *filter, const char *name, int casesensitive ){ } else { if ( toupper( *name ) >= toupper( *filter ) && - toupper( *name ) <= toupper( *( filter + 2 ) ) ) { + toupper( *name ) <= toupper( *( filter + 2 ) ) ) { found = qtrue; } } @@ -345,12 +345,24 @@ static int ( *_LittleLong )( int l ); static float ( *_BigFloat )( float l ); static float ( *_LittleFloat )( float l ); -short BigShort( short l ){return _BigShort( l ); } -short LittleShort( short l ) {return _LittleShort( l ); } -int BigLong( int l ) {return _BigLong( l ); } -int LittleLong( int l ) {return _LittleLong( l ); } -float BigFloat( float l ) {return _BigFloat( l ); } -float LittleFloat( float l ) {return _LittleFloat( l ); } +short BigShort( short l ){ + return _BigShort( l ); +} +short LittleShort( short l ) { + return _LittleShort( l ); +} +int BigLong( int l ) { + return _BigLong( l ); +} +int LittleLong( int l ) { + return _LittleLong( l ); +} +float BigFloat( float l ) { + return _BigFloat( l ); +} +float LittleFloat( float l ) { + return _LittleFloat( l ); +} short ShortSwap( short l ){ byte b1,b2; diff --git a/libs/splines/splines.cpp b/libs/splines/splines.cpp index 05cb3bf9..7e9eaa6c 100644 --- a/libs/splines/splines.cpp +++ b/libs/splines/splines.cpp @@ -23,13 +23,13 @@ #include "splines.h" extern "C" { -int FS_Write( const void *buffer, int len, fileHandle_t h ); -int FS_ReadFile( const char *qpath, void **buffer ); -void FS_FreeFile( void *buffer ); -fileHandle_t FS_FOpenFileWrite( const char *filename ); -void FS_FCloseFile( fileHandle_t f ); -void Cbuf_AddText( const char *text ); -void Cbuf_Execute( void ); + int FS_Write( const void *buffer, int len, fileHandle_t h ); + int FS_ReadFile( const char *qpath, void **buffer ); + void FS_FreeFile( void *buffer ); + fileHandle_t FS_FOpenFileWrite( const char *filename ); + void FS_FCloseFile( fileHandle_t f ); + void Cbuf_AddText( const char *text ); + void Cbuf_Execute( void ); } float Q_fabs( float f ) { @@ -48,39 +48,39 @@ float Q_fabs( float f ) { idCameraDef camera[MAX_CAMERAS]; extern "C" { -qboolean loadCamera( int camNum, const char *name ) { - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { + qboolean loadCamera( int camNum, const char *name ) { + if ( camNum < 0 || camNum >= MAX_CAMERAS ) { + return qfalse; + } + camera[camNum].clear(); + return (qboolean)camera[camNum].load( name ); + } + + qboolean getCameraInfo( int camNum, int time, float *origin, float *angles, float *fov ) { + idVec3 dir, org; + if ( camNum < 0 || camNum >= MAX_CAMERAS ) { + return qfalse; + } + org[0] = origin[0]; + org[1] = origin[1]; + org[2] = origin[2]; + if ( camera[camNum].getCameraInfo( time, org, dir, fov ) ) { + origin[0] = org[0]; + origin[1] = org[1]; + origin[2] = org[2]; + angles[1] = atan2( dir[1], dir[0] ) * 180 / 3.14159; + angles[0] = asin( dir[2] ) * 180 / 3.14159; + return qtrue; + } return qfalse; } - camera[camNum].clear(); - return (qboolean)camera[camNum].load( name ); -} -qboolean getCameraInfo( int camNum, int time, float *origin, float *angles, float *fov ) { - idVec3 dir, org; - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { - return qfalse; + void startCamera( int camNum, int time ) { + if ( camNum < 0 || camNum >= MAX_CAMERAS ) { + return; + } + camera[camNum].startCamera( time ); } - org[0] = origin[0]; - org[1] = origin[1]; - org[2] = origin[2]; - if ( camera[camNum].getCameraInfo( time, org, dir, fov ) ) { - origin[0] = org[0]; - origin[1] = org[1]; - origin[2] = org[2]; - angles[1] = atan2( dir[1], dir[0] ) * 180 / 3.14159; - angles[0] = asin( dir[2] ) * 180 / 3.14159; - return qtrue; - } - return qfalse; -} - -void startCamera( int camNum, int time ) { - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { - return; - } - camera[camNum].startCamera( time ); -} } @@ -359,10 +359,14 @@ void idSplineList::initPosition( long bt, long totalTime ) { float idSplineList::calcSpline( int step, float tension ) { switch ( step ) { - case 0: return ( pow( 1 - tension, 3 ) ) / 6; - case 1: return ( 3 * pow( tension, 3 ) - 6 * pow( tension, 2 ) + 4 ) / 6; - case 2: return ( -3 * pow( tension, 3 ) + 3 * pow( tension, 2 ) + 3 * tension + 1 ) / 6; - case 3: return pow( tension, 3 ) / 6; + case 0: + return ( pow( 1 - tension, 3 ) ) / 6; + case 1: + return ( 3 * pow( tension, 3 ) - 6 * pow( tension, 2 ) + 4 ) / 6; + case 2: + return ( -3 * pow( tension, 3 ) + 3 * pow( tension, 2 ) + 3 * tension + 1 ) / 6; + case 3: + return pow( tension, 3 ) / 6; } return 0.0; } @@ -500,31 +504,31 @@ void idCameraDef::getActiveSegmentInfo( int segment, idVec3 &origin, idVec3 &dir getCameraInfo( d * totalTime * 1000, origin, direction, fov ); #endif /* - if (!cameraSpline.validTime()) { - buildCamera(); - } - origin = *cameraSpline.getSegmentPoint(segment); + if (!cameraSpline.validTime()) { + buildCamera(); + } + origin = *cameraSpline.getSegmentPoint(segment); - idVec3 temp; + idVec3 temp; - int numTargets = getTargetSpline()->controlPoints.Num(); - int count = cameraSpline.splineTime.Num(); - if (numTargets == 0) { - // follow the path - if (cameraSpline.getActiveSegment() < count - 1) { - temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; - } - } else if (numTargets == 1) { - temp = *getTargetSpline()->controlPoints[0]; - } else { - temp = *getTargetSpline()->getSegmentPoint(segment); - } + int numTargets = getTargetSpline()->controlPoints.Num(); + int count = cameraSpline.splineTime.Num(); + if (numTargets == 0) { + // follow the path + if (cameraSpline.getActiveSegment() < count - 1) { + temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; + } + } else if (numTargets == 1) { + temp = *getTargetSpline()->controlPoints[0]; + } else { + temp = *getTargetSpline()->getSegmentPoint(segment); + } - temp -= origin; - temp.Normalize(); - direction = temp; - */ + temp -= origin; + temp.Normalize(); + direction = temp; +*/ } bool idCameraDef::getCameraInfo( long time, idVec3 &origin, idVec3 &direction, float *fv ) { @@ -603,16 +607,16 @@ bool idCameraDef::getCameraInfo( long time, idVec3 &origin, idVec3 &direction, f int numTargets = targetPositions.Num(); if ( numTargets == 0 ) { /* - // follow the path - if (cameraSpline.getActiveSegment() < count - 1) { - temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; - if (temp == origin) { - int index = cameraSpline.getActiveSegment() + 2; - while (temp == origin && index < count - 1) { - temp = *cameraSpline.splinePoints[index++]; - } - } - } + // follow the path + if (cameraSpline.getActiveSegment() < count - 1) { + temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; + if (temp == origin) { + int index = cameraSpline.getActiveSegment() + 2; + while (temp == origin && index < count - 1) { + temp = *cameraSpline.splinePoints[index++]; + } + } + } */ } else { @@ -720,35 +724,35 @@ void idCameraDef::buildCamera() { } case idCameraEvent::EVENT_SPEED: { /* - // take the average delay between up to the next five segments - float adjust = atof(events[i]->getParam()); - int index = events[i]->getSegment(); - total = 0; - count = 0; + // take the average delay between up to the next five segments + float adjust = atof(events[i]->getParam()); + int index = events[i]->getSegment(); + total = 0; + count = 0; - // get total amount of time over the remainder of the segment - for (j = index; j < cameraSpline.numSegments() - 1; j++) { - total += cameraSpline.getSegmentTime(j + 1) - cameraSpline.getSegmentTime(j); - count++; - } + // get total amount of time over the remainder of the segment + for (j = index; j < cameraSpline.numSegments() - 1; j++) { + total += cameraSpline.getSegmentTime(j + 1) - cameraSpline.getSegmentTime(j); + count++; + } - // multiply that by the adjustment - double newTotal = total * adjust; - // what is the difference.. - newTotal -= total; - totalTime += newTotal / 1000; + // multiply that by the adjustment + double newTotal = total * adjust; + // what is the difference.. + newTotal -= total; + totalTime += newTotal / 1000; - // per segment difference - newTotal /= count; - int additive = newTotal; + // per segment difference + newTotal /= count; + int additive = newTotal; - // now propogate that difference out to each segment - for (j = index; j < cameraSpline.numSegments(); j++) { - cameraSpline.addSegmentTime(j, additive); - additive += newTotal; - } - break; - */ + // now propogate that difference out to each segment + for (j = index; j < cameraSpline.numSegments(); j++) { + cameraSpline.addSegmentTime(j, additive); + additive += newTotal; + } + break; +*/ } } } diff --git a/libs/splines/splines.h b/libs/splines/splines.h index 952d93e6..44b57e62 100644 --- a/libs/splines/splines.h +++ b/libs/splines/splines.h @@ -42,121 +42,123 @@ static idVec4 red( 1, 0, 0, 1 ); class idPointListInterface { public: -idPointListInterface() { - selectedPoints.Clear(); -}; -virtual ~idPointListInterface() {}; + idPointListInterface() { + selectedPoints.Clear(); + }; + virtual ~idPointListInterface() {}; -virtual int numPoints() { - return 0; -} - -virtual void addPoint( const float x, const float y, const float z ) {} -virtual void addPoint( const idVec3 &v ) {} -virtual void removePoint( int index ) {} -virtual idVec3 *getPoint( int index ) { return NULL; } - -int selectPointByRay( float ox, float oy, float oz, float dx, float dy, float dz, bool single ) { - idVec3 origin( ox, oy, oz ); - idVec3 dir( dx, dy, dz ); - return selectPointByRay( origin, dir, single ); -} - -int selectPointByRay( const idVec3 origin, const idVec3 direction, bool single ) { - int i, besti, count; - float d, bestd; - idVec3 temp, temp2; - - // find the point closest to the ray - besti = -1; - bestd = 8; - count = numPoints(); - - for ( i = 0; i < count; i++ ) { - temp = *getPoint( i ); - temp2 = temp; - temp -= origin; - d = DotProduct( temp, direction ); - __VectorMA( origin, d, direction, temp ); - temp2 -= temp; - d = temp2.Length(); - if ( d <= bestd ) { - bestd = d; - besti = i; - } + virtual int numPoints() { + return 0; } - if ( besti >= 0 ) { - selectPoint( besti, single ); + virtual void addPoint( const float x, const float y, const float z ) {} + virtual void addPoint( const idVec3 &v ) {} + virtual void removePoint( int index ) {} + virtual idVec3 *getPoint( int index ) { + return NULL; } - return besti; -} - -int isPointSelected( int index ) { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - if ( selectedPoints[i] == index ) { - return i; - } + int selectPointByRay( float ox, float oy, float oz, float dx, float dy, float dz, bool single ) { + idVec3 origin( ox, oy, oz ); + idVec3 dir( dx, dy, dz ); + return selectPointByRay( origin, dir, single ); } - return -1; -} -int selectPoint( int index, bool single ) { - if ( index >= 0 && index < numPoints() ) { - if ( single ) { - deselectAll(); - } - else { - if ( isPointSelected( index ) >= 0 ) { - selectedPoints.Remove( index ); + int selectPointByRay( const idVec3 origin, const idVec3 direction, bool single ) { + int i, besti, count; + float d, bestd; + idVec3 temp, temp2; + + // find the point closest to the ray + besti = -1; + bestd = 8; + count = numPoints(); + + for ( i = 0; i < count; i++ ) { + temp = *getPoint( i ); + temp2 = temp; + temp -= origin; + d = DotProduct( temp, direction ); + __VectorMA( origin, d, direction, temp ); + temp2 -= temp; + d = temp2.Length(); + if ( d <= bestd ) { + bestd = d; + besti = i; } } - return selectedPoints.Append( index ); + + if ( besti >= 0 ) { + selectPoint( besti, single ); + } + + return besti; } - return -1; -} -void selectAll() { - selectedPoints.Clear(); - for ( int i = 0; i < numPoints(); i++ ) { - selectedPoints.Append( i ); + int isPointSelected( int index ) { + int count = selectedPoints.Num(); + for ( int i = 0; i < count; i++ ) { + if ( selectedPoints[i] == index ) { + return i; + } + } + return -1; } -} -void deselectAll() { - selectedPoints.Clear(); -} - -int numSelectedPoints(); - -idVec3 *getSelectedPoint( int index ) { - assert( index >= 0 && index < numSelectedPoints() ); - return getPoint( selectedPoints[index] ); -} - -virtual void updateSelection( float x, float y, float z ) { - idVec3 move( x, y, z ); - updateSelection( move ); -} - -virtual void updateSelection( const idVec3 &move ) { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - *getPoint( selectedPoints[i] ) += move; + int selectPoint( int index, bool single ) { + if ( index >= 0 && index < numPoints() ) { + if ( single ) { + deselectAll(); + } + else { + if ( isPointSelected( index ) >= 0 ) { + selectedPoints.Remove( index ); + } + } + return selectedPoints.Append( index ); + } + return -1; } -} -void drawSelection() { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - glBox( red, *getPoint( selectedPoints[i] ), 4 ); + void selectAll() { + selectedPoints.Clear(); + for ( int i = 0; i < numPoints(); i++ ) { + selectedPoints.Append( i ); + } + } + + void deselectAll() { + selectedPoints.Clear(); + } + + int numSelectedPoints(); + + idVec3 *getSelectedPoint( int index ) { + assert( index >= 0 && index < numSelectedPoints() ); + return getPoint( selectedPoints[index] ); + } + + virtual void updateSelection( float x, float y, float z ) { + idVec3 move( x, y, z ); + updateSelection( move ); + } + + virtual void updateSelection( const idVec3 &move ) { + int count = selectedPoints.Num(); + for ( int i = 0; i < count; i++ ) { + *getPoint( selectedPoints[i] ) += move; + } + } + + void drawSelection() { + int count = selectedPoints.Num(); + for ( int i = 0; i < count; i++ ) { + glBox( red, *getPoint( selectedPoints[i] ), 4 ); + } } -} protected: -idList selectedPoints; + idList selectedPoints; }; @@ -165,185 +167,185 @@ class idSplineList { public: -idSplineList() { - clear(); -} - -idSplineList( const char *p ) { - clear(); - name = p; -}; - -~idSplineList() { - clear(); -}; - -void clearControl() { - for ( int i = 0; i < controlPoints.Num(); i++ ) { - delete controlPoints[i]; + idSplineList() { + clear(); } - controlPoints.Clear(); -} -void clearSpline() { - for ( int i = 0; i < splinePoints.Num(); i++ ) { - delete splinePoints[i]; + idSplineList( const char *p ) { + clear(); + name = p; + }; + + ~idSplineList() { + clear(); + }; + + void clearControl() { + for ( int i = 0; i < controlPoints.Num(); i++ ) { + delete controlPoints[i]; + } + controlPoints.Clear(); } - splinePoints.Clear(); -} -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -void clear() { - clearControl(); - clearSpline(); - splineTime.Clear(); - selected = NULL; - dirty = true; - activeSegment = 0; - granularity = 0.025f; - pathColor.set( 1.0f, 0.5f, 0.0f ); - controlColor.set( 0.7f, 0.0f, 1.0f ); - segmentColor.set( 0.0f, 0.0f, 1.0f ); - activeColor.set( 1.0f, 0.0f, 0.0f ); -} - -void initPosition( long startTime, long totalTime ); -const idVec3 *getPosition( long time ); - - -void draw( bool editMode ); -void addToRenderer(); - -void setSelectedPoint( idVec3 *p ); -idVec3 *getSelectedPoint() { - return selected; -} - -void addPoint( const idVec3 &v ) { - controlPoints.Append( new idVec3( v ) ); - dirty = true; -} - -void addPoint( float x, float y, float z ) { - controlPoints.Append( new idVec3( x, y, z ) ); - dirty = true; -} - -void updateSelection( const idVec3 &move ); - -void startEdit() { - editMode = true; -} - -void stopEdit() { - editMode = false; -} - -void buildSpline(); - -void setGranularity( float f ) { - granularity = f; -} - -float getGranularity() { - return granularity; -} - -int numPoints() { - return controlPoints.Num(); -} - -idVec3 *getPoint( int index ) { - assert( index >= 0 && index < controlPoints.Num() ); - return controlPoints[index]; -} - -idVec3 *getSegmentPoint( int index ) { - assert( index >= 0 && index < splinePoints.Num() ); - return splinePoints[index]; -} - - -void setSegmentTime( int index, int time ) { - assert( index >= 0 && index < splinePoints.Num() ); - splineTime[index] = time; -} - -int getSegmentTime( int index ) { - assert( index >= 0 && index < splinePoints.Num() ); - return (int)splineTime[index]; -} -void addSegmentTime( int index, int time ) { - assert( index >= 0 && index < splinePoints.Num() ); - splineTime[index] += time; -} - -float totalDistance(); - -static idVec3 zero; - -int getActiveSegment() { - return activeSegment; -} - -void setActiveSegment( int i ) { - //assert(i >= 0 && (splinePoints.Num() > 0 && i < splinePoints.Num())); - activeSegment = i; -} - -int numSegments() { - return splinePoints.Num(); -} - -void setColors( idVec3 &path, idVec3 &segment, idVec3 &control, idVec3 &active ) { - pathColor = path; - segmentColor = segment; - controlColor = control; - activeColor = active; -} - -const char *getName() { - return name.c_str(); -} - -void setName( const char *p ) { - name = p; -} - -bool validTime() { - if ( dirty ) { - buildSpline(); + void clearSpline() { + for ( int i = 0; i < splinePoints.Num(); i++ ) { + delete splinePoints[i]; + } + splinePoints.Clear(); } - // gcc doesn't allow static casting away from bools - // why? I've no idea... - return (bool)( splineTime.Num() > 0 && splineTime.Num() == splinePoints.Num() ); -} -void setTime( long t ) { - time = t; -} + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); -void setBaseTime( long t ) { - baseTime = t; -} + void clear() { + clearControl(); + clearSpline(); + splineTime.Clear(); + selected = NULL; + dirty = true; + activeSegment = 0; + granularity = 0.025f; + pathColor.set( 1.0f, 0.5f, 0.0f ); + controlColor.set( 0.7f, 0.0f, 1.0f ); + segmentColor.set( 0.0f, 0.0f, 1.0f ); + activeColor.set( 1.0f, 0.0f, 0.0f ); + } + + void initPosition( long startTime, long totalTime ); + const idVec3 *getPosition( long time ); + + + void draw( bool editMode ); + void addToRenderer(); + + void setSelectedPoint( idVec3 *p ); + idVec3 *getSelectedPoint() { + return selected; + } + + void addPoint( const idVec3 &v ) { + controlPoints.Append( new idVec3( v ) ); + dirty = true; + } + + void addPoint( float x, float y, float z ) { + controlPoints.Append( new idVec3( x, y, z ) ); + dirty = true; + } + + void updateSelection( const idVec3 &move ); + + void startEdit() { + editMode = true; + } + + void stopEdit() { + editMode = false; + } + + void buildSpline(); + + void setGranularity( float f ) { + granularity = f; + } + + float getGranularity() { + return granularity; + } + + int numPoints() { + return controlPoints.Num(); + } + + idVec3 *getPoint( int index ) { + assert( index >= 0 && index < controlPoints.Num() ); + return controlPoints[index]; + } + + idVec3 *getSegmentPoint( int index ) { + assert( index >= 0 && index < splinePoints.Num() ); + return splinePoints[index]; + } + + + void setSegmentTime( int index, int time ) { + assert( index >= 0 && index < splinePoints.Num() ); + splineTime[index] = time; + } + + int getSegmentTime( int index ) { + assert( index >= 0 && index < splinePoints.Num() ); + return (int)splineTime[index]; + } + void addSegmentTime( int index, int time ) { + assert( index >= 0 && index < splinePoints.Num() ); + splineTime[index] += time; + } + + float totalDistance(); + + static idVec3 zero; + + int getActiveSegment() { + return activeSegment; + } + + void setActiveSegment( int i ) { + //assert(i >= 0 && (splinePoints.Num() > 0 && i < splinePoints.Num())); + activeSegment = i; + } + + int numSegments() { + return splinePoints.Num(); + } + + void setColors( idVec3 &path, idVec3 &segment, idVec3 &control, idVec3 &active ) { + pathColor = path; + segmentColor = segment; + controlColor = control; + activeColor = active; + } + + const char *getName() { + return name.c_str(); + } + + void setName( const char *p ) { + name = p; + } + + bool validTime() { + if ( dirty ) { + buildSpline(); + } + // gcc doesn't allow static casting away from bools + // why? I've no idea... + return (bool)( splineTime.Num() > 0 && splineTime.Num() == splinePoints.Num() ); + } + + void setTime( long t ) { + time = t; + } + + void setBaseTime( long t ) { + baseTime = t; + } protected: -idStr name; -float calcSpline( int step, float tension ); -idList controlPoints; -idList splinePoints; -idList splineTime; -idVec3 *selected; -idVec3 pathColor, segmentColor, controlColor, activeColor; -float granularity; -bool editMode; -bool dirty; -int activeSegment; -long baseTime; -long time; -friend class idCamera; + idStr name; + float calcSpline( int step, float tension ); + idList controlPoints; + idList splinePoints; + idList splineTime; + idVec3 *selected; + idVec3 pathColor, segmentColor, controlColor, activeColor; + float granularity; + bool editMode; + bool dirty; + int activeSegment; + long baseTime; + long time; + friend class idCamera; }; // time in milliseconds @@ -364,412 +366,412 @@ struct idVelocity { class idCameraPosition : public idPointListInterface { public: -virtual void clearVelocities() { - for ( int i = 0; i < velocities.Num(); i++ ) { - delete velocities[i]; - velocities[i] = NULL; + virtual void clearVelocities() { + for ( int i = 0; i < velocities.Num(); i++ ) { + delete velocities[i]; + velocities[i] = NULL; + } + velocities.Clear(); } - velocities.Clear(); -} -virtual void clear() { - editMode = false; - clearVelocities(); -} + virtual void clear() { + editMode = false; + clearVelocities(); + } -idCameraPosition( const char *p ) { - name = p; -} + idCameraPosition( const char *p ) { + name = p; + } -idCameraPosition() { - time = 0; - name = "position"; -} + idCameraPosition() { + time = 0; + name = "position"; + } -idCameraPosition( long t ) { - time = t; -} + idCameraPosition( long t ) { + time = t; + } -virtual ~idCameraPosition() { - clear(); -} + virtual ~idCameraPosition() { + clear(); + } // this can be done with RTTI syntax but i like the derived classes setting a type // makes serialization a bit easier to see // -enum positionType { - FIXED = 0x00, - INTERPOLATED, - SPLINE, - POSITION_COUNT -}; + enum positionType { + FIXED = 0x00, + INTERPOLATED, + SPLINE, + POSITION_COUNT + }; -virtual void start( long t ) { - startTime = t; -} - -long getTime() { - return time; -} - -virtual void setTime( long t ) { - time = t; -} - -float getBaseVelocity() { - return baseVelocity; -} - -float getVelocity( long t ) { - long check = t - startTime; - for ( int i = 0; i < velocities.Num(); i++ ) { - if ( check >= velocities[i]->startTime && check <= velocities[i]->startTime + velocities[i]->time ) { - return velocities[i]->speed; - } + virtual void start( long t ) { + startTime = t; } - return baseVelocity; -} -void addVelocity( long start, long duration, float speed ) { - velocities.Append( new idVelocity( start, duration, speed ) ); -} + long getTime() { + return time; + } -virtual const idVec3 *getPosition( long t ) { - assert( true ); - return NULL; -} + virtual void setTime( long t ) { + time = t; + } -virtual void draw( bool editMode ) {}; + float getBaseVelocity() { + return baseVelocity; + } -virtual void parse( const char *( *text ) ) {}; -virtual void write( fileHandle_t file, const char *name ); -virtual bool parseToken( const char *key, const char *( *text ) ); + float getVelocity( long t ) { + long check = t - startTime; + for ( int i = 0; i < velocities.Num(); i++ ) { + if ( check >= velocities[i]->startTime && check <= velocities[i]->startTime + velocities[i]->time ) { + return velocities[i]->speed; + } + } + return baseVelocity; + } -const char *getName() { - return name.c_str(); -} + void addVelocity( long start, long duration, float speed ) { + velocities.Append( new idVelocity( start, duration, speed ) ); + } -void setName( const char *p ) { - name = p; -} + virtual const idVec3 *getPosition( long t ) { + assert( true ); + return NULL; + } -virtual void startEdit() { - editMode = true; -} + virtual void draw( bool editMode ) {}; -virtual void stopEdit() { - editMode = false; -} + virtual void parse( const char *( *text ) ) {}; + virtual void write( fileHandle_t file, const char *name ); + virtual bool parseToken( const char *key, const char *( *text ) ); -virtual void draw() {}; + const char *getName() { + return name.c_str(); + } -const char *typeStr() { - return positionStr[static_cast( type )]; -} + void setName( const char *p ) { + name = p; + } -void calcVelocity( float distance ) { - float secs = (float)time / 1000; - baseVelocity = distance / secs; -} + virtual void startEdit() { + editMode = true; + } + + virtual void stopEdit() { + editMode = false; + } + + virtual void draw() {}; + + const char *typeStr() { + return positionStr[static_cast( type )]; + } + + void calcVelocity( float distance ) { + float secs = (float)time / 1000; + baseVelocity = distance / secs; + } protected: -static const char* positionStr[POSITION_COUNT]; -long startTime; -long time; -idCameraPosition::positionType type; -idStr name; -bool editMode; -idList velocities; -float baseVelocity; + static const char* positionStr[POSITION_COUNT]; + long startTime; + long time; + idCameraPosition::positionType type; + idStr name; + bool editMode; + idList velocities; + float baseVelocity; }; class idFixedPosition : public idCameraPosition { public: -void init() { - pos.Zero(); - type = idCameraPosition::FIXED; -} - -idFixedPosition() : idCameraPosition() { - init(); -} - -idFixedPosition( idVec3 p ) : idCameraPosition() { - init(); - pos = p; -} - -virtual void addPoint( const idVec3 &v ) { - pos = v; -} - -virtual void addPoint( const float x, const float y, const float z ) { - pos.set( x, y, z ); -} - - -~idFixedPosition() { -} - -virtual const idVec3 *getPosition( long t ) { - return &pos; -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -virtual int numPoints() { - return 1; -} - -virtual idVec3 *getPoint( int index ) { - if ( index != 0 ) { - assert( true ); + void init() { + pos.Zero(); + type = idCameraPosition::FIXED; } - ; - return &pos; -} -virtual void draw( bool editMode ) { - glLabeledPoint( blue, pos, ( editMode ) ? 5 : 3, "Fixed point" ); -} + idFixedPosition() : idCameraPosition() { + init(); + } + + idFixedPosition( idVec3 p ) : idCameraPosition() { + init(); + pos = p; + } + + virtual void addPoint( const idVec3 &v ) { + pos = v; + } + + virtual void addPoint( const float x, const float y, const float z ) { + pos.set( x, y, z ); + } + + + ~idFixedPosition() { + } + + virtual const idVec3 *getPosition( long t ) { + return &pos; + } + + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); + + virtual int numPoints() { + return 1; + } + + virtual idVec3 *getPoint( int index ) { + if ( index != 0 ) { + assert( true ); + } + ; + return &pos; + } + + virtual void draw( bool editMode ) { + glLabeledPoint( blue, pos, ( editMode ) ? 5 : 3, "Fixed point" ); + } protected: -idVec3 pos; + idVec3 pos; }; class idInterpolatedPosition : public idCameraPosition { public: -void init() { - type = idCameraPosition::INTERPOLATED; - first = true; - startPos.Zero(); - endPos.Zero(); -} - -idInterpolatedPosition() : idCameraPosition() { - init(); -} - -idInterpolatedPosition( idVec3 start, idVec3 end, long time ) : idCameraPosition( time ) { - init(); - startPos = start; - endPos = end; -} - -~idInterpolatedPosition() { -} - -virtual const idVec3 *getPosition( long t ); - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -virtual int numPoints() { - return 2; -} - -virtual idVec3 *getPoint( int index ) { - assert( index >= 0 && index < 2 ); - if ( index == 0 ) { - return &startPos; - } - return &endPos; -} - -virtual void addPoint( const float x, const float y, const float z ) { - if ( first ) { - startPos.set( x, y, z ); - first = false; - } - else { - endPos.set( x, y, z ); + void init() { + type = idCameraPosition::INTERPOLATED; first = true; + startPos.Zero(); + endPos.Zero(); } -} -virtual void addPoint( const idVec3 &v ) { - if ( first ) { - startPos = v; - first = false; + idInterpolatedPosition() : idCameraPosition() { + init(); } - else { - endPos = v; - first = true; + + idInterpolatedPosition( idVec3 start, idVec3 end, long time ) : idCameraPosition( time ) { + init(); + startPos = start; + endPos = end; } -} -virtual void draw( bool editMode ) { - glLabeledPoint( blue, startPos, ( editMode ) ? 5 : 3, "Start interpolated" ); - glLabeledPoint( blue, endPos, ( editMode ) ? 5 : 3, "End interpolated" ); - glBegin( GL_LINES ); - glVertex3fv( startPos ); - glVertex3fv( endPos ); - glEnd(); -} + ~idInterpolatedPosition() { + } -virtual void start( long t ) { - idCameraPosition::start( t ); - lastTime = startTime; - distSoFar = 0.0; - idVec3 temp = startPos; - temp -= endPos; - calcVelocity( temp.Length() ); -} + virtual const idVec3 *getPosition( long t ); + + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); + + virtual int numPoints() { + return 2; + } + + virtual idVec3 *getPoint( int index ) { + assert( index >= 0 && index < 2 ); + if ( index == 0 ) { + return &startPos; + } + return &endPos; + } + + virtual void addPoint( const float x, const float y, const float z ) { + if ( first ) { + startPos.set( x, y, z ); + first = false; + } + else { + endPos.set( x, y, z ); + first = true; + } + } + + virtual void addPoint( const idVec3 &v ) { + if ( first ) { + startPos = v; + first = false; + } + else { + endPos = v; + first = true; + } + } + + virtual void draw( bool editMode ) { + glLabeledPoint( blue, startPos, ( editMode ) ? 5 : 3, "Start interpolated" ); + glLabeledPoint( blue, endPos, ( editMode ) ? 5 : 3, "End interpolated" ); + glBegin( GL_LINES ); + glVertex3fv( startPos ); + glVertex3fv( endPos ); + glEnd(); + } + + virtual void start( long t ) { + idCameraPosition::start( t ); + lastTime = startTime; + distSoFar = 0.0; + idVec3 temp = startPos; + temp -= endPos; + calcVelocity( temp.Length() ); + } protected: -bool first; -idVec3 startPos; -idVec3 endPos; -long lastTime; -float distSoFar; + bool first; + idVec3 startPos; + idVec3 endPos; + long lastTime; + float distSoFar; }; class idSplinePosition : public idCameraPosition { public: -void init() { - type = idCameraPosition::SPLINE; -} + void init() { + type = idCameraPosition::SPLINE; + } -idSplinePosition() : idCameraPosition() { - init(); -} + idSplinePosition() : idCameraPosition() { + init(); + } -idSplinePosition( long time ) : idCameraPosition( time ) { - init(); -} + idSplinePosition( long time ) : idCameraPosition( time ) { + init(); + } -~idSplinePosition() { -} + ~idSplinePosition() { + } -virtual void start( long t ) { - idCameraPosition::start( t ); - target.initPosition( t, time ); - lastTime = startTime; - distSoFar = 0.0; - calcVelocity( target.totalDistance() ); -} + virtual void start( long t ) { + idCameraPosition::start( t ); + target.initPosition( t, time ); + lastTime = startTime; + distSoFar = 0.0; + calcVelocity( target.totalDistance() ); + } //virtual const idVec3 *getPosition(long t) { // return target.getPosition(t); //} -virtual const idVec3 *getPosition( long t ); + virtual const idVec3 *getPosition( long t ); //virtual const idVec3 *getPosition(long t) const { -void addControlPoint( idVec3 &v ) { - target.addPoint( v ); -} + void addControlPoint( idVec3 &v ) { + target.addPoint( v ); + } -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); -virtual int numPoints() { - return target.numPoints(); -} + virtual int numPoints() { + return target.numPoints(); + } -virtual idVec3 *getPoint( int index ) { - return target.getPoint( index ); -} + virtual idVec3 *getPoint( int index ) { + return target.getPoint( index ); + } -virtual void addPoint( const idVec3 &v ) { - target.addPoint( v ); -} + virtual void addPoint( const idVec3 &v ) { + target.addPoint( v ); + } -virtual void addPoint( const float x, const float y, const float z ) { - target.addPoint( x, y, z ); -} + virtual void addPoint( const float x, const float y, const float z ) { + target.addPoint( x, y, z ); + } -virtual void draw( bool editMode ) { - target.draw( editMode ); -} + virtual void draw( bool editMode ) { + target.draw( editMode ); + } -virtual void updateSelection( const idVec3 &move ) { - idCameraPosition::updateSelection( move ); - target.buildSpline(); -} + virtual void updateSelection( const idVec3 &move ) { + idCameraPosition::updateSelection( move ); + target.buildSpline(); + } protected: -idSplineList target; -long lastTime; -float distSoFar; + idSplineList target; + long lastTime; + float distSoFar; }; class idCameraFOV { public: -idCameraFOV() { - time = 0; - length = 0; - fov = 90; -} - -idCameraFOV( int v ) { - time = 0; - length = 0; - fov = v; -} - -idCameraFOV( int s, int e, long t ) { - startFOV = s; - endFOV = e; - length = t; -} - - -~idCameraFOV(){} - -void setFOV( float f ) { - fov = f; -} - -float getFOV( long t ) { - if ( length ) { - float percent = ( t - startTime ) / length; - if ( percent < 0.0 ) { - percent = 0.0; - } - else if ( percent > 1.0 ) { - percent = 1.0; - } - float temp = endFOV - startFOV; - temp *= percent; - fov = startFOV + temp; - - if ( percent == 1.0 ) { - length = 0.0; - } + idCameraFOV() { + time = 0; + length = 0; + fov = 90; } - return fov; -} -void start( long t ) { - startTime = t; -} + idCameraFOV( int v ) { + time = 0; + length = 0; + fov = v; + } -void reset( float startfov, float endfov, int start, float len ) { - startFOV = startfov; - endFOV = endfov; - startTime = start; - length = len * 1000; -} + idCameraFOV( int s, int e, long t ) { + startFOV = s; + endFOV = e; + length = t; + } -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); + + ~idCameraFOV() {} + + void setFOV( float f ) { + fov = f; + } + + float getFOV( long t ) { + if ( length ) { + float percent = ( t - startTime ) / length; + if ( percent < 0.0 ) { + percent = 0.0; + } + else if ( percent > 1.0 ) { + percent = 1.0; + } + float temp = endFOV - startFOV; + temp *= percent; + fov = startFOV + temp; + + if ( percent == 1.0 ) { + length = 0.0; + } + } + return fov; + } + + void start( long t ) { + startTime = t; + } + + void reset( float startfov, float endfov, int start, float len ) { + startFOV = startfov; + endFOV = endfov; + startTime = start; + length = len * 1000; + } + + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); protected: -float fov; -float startFOV; -float endFOV; -int startTime; -int time; -float length; + float fov; + float startFOV; + float endFOV; + int startTime; + int time; + float length; }; @@ -777,348 +779,351 @@ float length; class idCameraEvent { public: // parameters -enum eventType { - EVENT_NA = 0x00, - EVENT_WAIT, // - EVENT_TARGETWAIT, // - EVENT_SPEED, // - EVENT_TARGET, // char(name) - EVENT_SNAPTARGET, // - EVENT_FOV, // int(time), int(targetfov) - EVENT_CMD, // - EVENT_TRIGGER, // - EVENT_STOP, // - EVENT_CAMERA, // - EVENT_FADEOUT, // int(time) - EVENT_FADEIN, // int(time) - EVENT_FEATHER, // - EVENT_COUNT -}; + enum eventType { + EVENT_NA = 0x00, + EVENT_WAIT, // + EVENT_TARGETWAIT, // + EVENT_SPEED, // + EVENT_TARGET, // char(name) + EVENT_SNAPTARGET, // + EVENT_FOV, // int(time), int(targetfov) + EVENT_CMD, // + EVENT_TRIGGER, // + EVENT_STOP, // + EVENT_CAMERA, // + EVENT_FADEOUT, // int(time) + EVENT_FADEIN, // int(time) + EVENT_FEATHER, // + EVENT_COUNT + }; -static const char* eventStr[EVENT_COUNT]; + static const char* eventStr[EVENT_COUNT]; -idCameraEvent() { - paramStr = ""; - type = EVENT_NA; - time = 0; -} + idCameraEvent() { + paramStr = ""; + type = EVENT_NA; + time = 0; + } -idCameraEvent( eventType t, const char *param, long n ) { - type = t; - paramStr = param; - time = n; -} + idCameraEvent( eventType t, const char *param, long n ) { + type = t; + paramStr = param; + time = n; + } -~idCameraEvent() {}; + ~idCameraEvent() {}; -eventType getType() { - return type; -} + eventType getType() { + return type; + } -const char *typeStr() { - return eventStr[static_cast( type )]; -} + const char *typeStr() { + return eventStr[static_cast( type )]; + } -const char *getParam() { - return paramStr.c_str(); -} + const char *getParam() { + return paramStr.c_str(); + } -long getTime() { - return time; -} + long getTime() { + return time; + } -void setTime( long n ) { - time = n; -} + void setTime( long n ) { + time = n; + } -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); + void parse( const char *( *text ) ); + void write( fileHandle_t file, const char *name ); -void setTriggered( bool b ) { - triggered = b; -} + void setTriggered( bool b ) { + triggered = b; + } -bool getTriggered() { - return triggered; -} + bool getTriggered() { + return triggered; + } protected: -eventType type; -idStr paramStr; -long time; -bool triggered; + eventType type; + idStr paramStr; + long time; + bool triggered; }; class idCameraDef { public: -void clear() { - currentCameraPosition = 0; - cameraRunning = false; - lastDirection.Zero(); - baseTime = 30; - activeTarget = 0; - name = "camera01"; - fov.setFOV( 90 ); - int i; - for ( i = 0; i < targetPositions.Num(); i++ ) { - delete targetPositions[i]; + void clear() { + currentCameraPosition = 0; + cameraRunning = false; + lastDirection.Zero(); + baseTime = 30; + activeTarget = 0; + name = "camera01"; + fov.setFOV( 90 ); + int i; + for ( i = 0; i < targetPositions.Num(); i++ ) { + delete targetPositions[i]; + } + for ( i = 0; i < events.Num(); i++ ) { + delete events[i]; + } + delete cameraPosition; + cameraPosition = NULL; + events.Clear(); + targetPositions.Clear(); } - for ( i = 0; i < events.Num(); i++ ) { - delete events[i]; + + idCameraPosition *startNewCamera( idCameraPosition::positionType type ) { + clear(); + if ( type == idCameraPosition::SPLINE ) { + cameraPosition = new idSplinePosition(); + } + else if ( type == idCameraPosition::INTERPOLATED ) { + cameraPosition = new idInterpolatedPosition(); + } + else { + cameraPosition = new idFixedPosition(); + } + return cameraPosition; } - delete cameraPosition; - cameraPosition = NULL; - events.Clear(); - targetPositions.Clear(); -} -idCameraPosition *startNewCamera( idCameraPosition::positionType type ) { - clear(); - if ( type == idCameraPosition::SPLINE ) { - cameraPosition = new idSplinePosition(); + idCameraDef() { + cameraPosition = NULL; + clear(); } - else if ( type == idCameraPosition::INTERPOLATED ) { - cameraPosition = new idInterpolatedPosition(); + + ~idCameraDef() { + clear(); } - else { - cameraPosition = new idFixedPosition(); + + void addEvent( idCameraEvent::eventType t, const char *param, long time ); + + void addEvent( idCameraEvent *event ); + + void removeEvent( int index ); + + static int sortEvents( const void *p1, const void *p2 ); + + int numEvents() { + return events.Num(); } - return cameraPosition; -} -idCameraDef() { - cameraPosition = NULL; - clear(); -} + idCameraEvent *getEvent( int index ) { + assert( index >= 0 && index < events.Num() ); + return events[index]; + } -~idCameraDef() { - clear(); -} + void parse( const char *( *text ) ); + bool load( const char *filename ); + void save( const char *filename ); -void addEvent( idCameraEvent::eventType t, const char *param, long time ); - -void addEvent( idCameraEvent *event ); - -void removeEvent( int index ); - -static int sortEvents( const void *p1, const void *p2 ); - -int numEvents() { - return events.Num(); -} - -idCameraEvent *getEvent( int index ) { - assert( index >= 0 && index < events.Num() ); - return events[index]; -} - -void parse( const char *( *text ) ); -bool load( const char *filename ); -void save( const char *filename ); - -void buildCamera(); + void buildCamera(); //idSplineList *getcameraPosition() { // return &cameraPosition; //} -static idCameraPosition *newFromType( idCameraPosition::positionType t ) { - switch ( t ) { - case idCameraPosition::FIXED: return new idFixedPosition(); - case idCameraPosition::INTERPOLATED: return new idInterpolatedPosition(); - case idCameraPosition::SPLINE: return new idSplinePosition(); - default: - break; - }; - return NULL; -} - -void addTarget( const char *name, idCameraPosition::positionType type ); - -idCameraPosition *getActiveTarget() { - if ( targetPositions.Num() == 0 ) { - addTarget( NULL, idCameraPosition::FIXED ); + static idCameraPosition *newFromType( idCameraPosition::positionType t ) { + switch ( t ) { + case idCameraPosition::FIXED: + return new idFixedPosition(); + case idCameraPosition::INTERPOLATED: + return new idInterpolatedPosition(); + case idCameraPosition::SPLINE: + return new idSplinePosition(); + default: + break; + }; + return NULL; } - return targetPositions[activeTarget]; -} -idCameraPosition *getActiveTarget( int index ) { - if ( targetPositions.Num() == 0 ) { - addTarget( NULL, idCameraPosition::FIXED ); - return targetPositions[0]; + void addTarget( const char *name, idCameraPosition::positionType type ); + + idCameraPosition *getActiveTarget() { + if ( targetPositions.Num() == 0 ) { + addTarget( NULL, idCameraPosition::FIXED ); + } + return targetPositions[activeTarget]; } - return targetPositions[index]; -} -int numTargets() { - return targetPositions.Num(); -} + idCameraPosition *getActiveTarget( int index ) { + if ( targetPositions.Num() == 0 ) { + addTarget( NULL, idCameraPosition::FIXED ); + return targetPositions[0]; + } + return targetPositions[index]; + } + + int numTargets() { + return targetPositions.Num(); + } -void setActiveTargetByName( const char *name ) { - for ( int i = 0; i < targetPositions.Num(); i++ ) { - if ( Q_stricmp( name, targetPositions[i]->getName() ) == 0 ) { - setActiveTarget( i ); - return; + void setActiveTargetByName( const char *name ) { + for ( int i = 0; i < targetPositions.Num(); i++ ) { + if ( Q_stricmp( name, targetPositions[i]->getName() ) == 0 ) { + setActiveTarget( i ); + return; + } } } -} -void setActiveTarget( int index ) { - assert( index >= 0 && index < targetPositions.Num() ); - activeTarget = index; -} + void setActiveTarget( int index ) { + assert( index >= 0 && index < targetPositions.Num() ); + activeTarget = index; + } -void setRunning( bool b ) { - cameraRunning = b; -} + void setRunning( bool b ) { + cameraRunning = b; + } -void setBaseTime( float f ) { - baseTime = f; -} + void setBaseTime( float f ) { + baseTime = f; + } -float getBaseTime() { - return baseTime; -} + float getBaseTime() { + return baseTime; + } -float getTotalTime() { - return totalTime; -} + float getTotalTime() { + return totalTime; + } -void startCamera( long t ); -void stopCamera() { - cameraRunning = true; -} -void getActiveSegmentInfo( int segment, idVec3 &origin, idVec3 &direction, float *fv ); + void startCamera( long t ); + void stopCamera() { + cameraRunning = true; + } + void getActiveSegmentInfo( int segment, idVec3 &origin, idVec3 &direction, float *fv ); -bool getCameraInfo( long time, idVec3 &origin, idVec3 &direction, float *fv ); -bool getCameraInfo( long time, float *origin, float *direction, float *fv ) { - idVec3 org, dir; - org[0] = origin[0]; - org[1] = origin[1]; - org[2] = origin[2]; - dir[0] = direction[0]; - dir[1] = direction[1]; - dir[2] = direction[2]; - bool b = getCameraInfo( time, org, dir, fv ); - origin[0] = org[0]; - origin[1] = org[1]; - origin[2] = org[2]; - direction[0] = dir[0]; - direction[1] = dir[1]; - direction[2] = dir[2]; - return b; -} + bool getCameraInfo( long time, idVec3 &origin, idVec3 &direction, float *fv ); + bool getCameraInfo( long time, float *origin, float *direction, float *fv ) { + idVec3 org, dir; + org[0] = origin[0]; + org[1] = origin[1]; + org[2] = origin[2]; + dir[0] = direction[0]; + dir[1] = direction[1]; + dir[2] = direction[2]; + bool b = getCameraInfo( time, org, dir, fv ); + origin[0] = org[0]; + origin[1] = org[1]; + origin[2] = org[2]; + direction[0] = dir[0]; + direction[1] = dir[1]; + direction[2] = dir[2]; + return b; + } -void draw( bool editMode ) { - // gcc doesn't allow casting away from bools - // why? I've no idea... - if ( cameraPosition ) { - cameraPosition->draw( (bool)( ( editMode || cameraRunning ) && cameraEdit ) ); - int count = targetPositions.Num(); - for ( int i = 0; i < count; i++ ) { - targetPositions[i]->draw( (bool)( ( editMode || cameraRunning ) && i == activeTarget && !cameraEdit ) ); + void draw( bool editMode ) { + // gcc doesn't allow casting away from bools + // why? I've no idea... + if ( cameraPosition ) { + cameraPosition->draw( (bool)( ( editMode || cameraRunning ) && cameraEdit ) ); + int count = targetPositions.Num(); + for ( int i = 0; i < count; i++ ) { + targetPositions[i]->draw( (bool)( ( editMode || cameraRunning ) && i == activeTarget && !cameraEdit ) ); + } } } -} /* - int numSegments() { - if (cameraEdit) { - return cameraPosition.numSegments(); - } - return getTargetSpline()->numSegments(); - } - - int getActiveSegment() { - if (cameraEdit) { - return cameraPosition.getActiveSegment(); - } - return getTargetSpline()->getActiveSegment(); - } - - void setActiveSegment(int i) { - if (cameraEdit) { - cameraPosition.setActiveSegment(i); - } else { - getTargetSpline()->setActiveSegment(i); - } - } - */ -int numPoints() { - if ( cameraEdit ) { - return cameraPosition->numPoints(); + int numSegments() { + if (cameraEdit) { + return cameraPosition.numSegments(); + } + return getTargetSpline()->numSegments(); } - return getActiveTarget()->numPoints(); -} -const idVec3 *getPoint( int index ) { - if ( cameraEdit ) { - return cameraPosition->getPoint( index ); + int getActiveSegment() { + if (cameraEdit) { + return cameraPosition.getActiveSegment(); + } + return getTargetSpline()->getActiveSegment(); } - return getActiveTarget()->getPoint( index ); -} -void stopEdit() { - editMode = false; - if ( cameraEdit ) { - cameraPosition->stopEdit(); - } - else { - getActiveTarget()->stopEdit(); - } -} - -void startEdit( bool camera ) { - cameraEdit = camera; - if ( camera ) { - cameraPosition->startEdit(); - for ( int i = 0; i < targetPositions.Num(); i++ ) { - targetPositions[i]->stopEdit(); + void setActiveSegment(int i) { + if (cameraEdit) { + cameraPosition.setActiveSegment(i); + } else { + getTargetSpline()->setActiveSegment(i); } } - else { - getActiveTarget()->startEdit(); - cameraPosition->stopEdit(); + */ + int numPoints() { + if ( cameraEdit ) { + return cameraPosition->numPoints(); + } + return getActiveTarget()->numPoints(); } - editMode = true; -} -bool waitEvent( int index ); - -const char *getName() { - return name.c_str(); -} - -void setName( const char *p ) { - name = p; -} - -idCameraPosition *getPositionObj() { - if ( cameraPosition == NULL ) { - cameraPosition = new idFixedPosition(); + const idVec3 *getPoint( int index ) { + if ( cameraEdit ) { + return cameraPosition->getPoint( index ); + } + return getActiveTarget()->getPoint( index ); + } + + void stopEdit() { + editMode = false; + if ( cameraEdit ) { + cameraPosition->stopEdit(); + } + else { + getActiveTarget()->stopEdit(); + } + } + + void startEdit( bool camera ) { + cameraEdit = camera; + if ( camera ) { + cameraPosition->startEdit(); + for ( int i = 0; i < targetPositions.Num(); i++ ) { + targetPositions[i]->stopEdit(); + } + } + else { + getActiveTarget()->startEdit(); + cameraPosition->stopEdit(); + } + editMode = true; + } + + bool waitEvent( int index ); + + const char *getName() { + return name.c_str(); + } + + void setName( const char *p ) { + name = p; + } + + idCameraPosition *getPositionObj() { + if ( cameraPosition == NULL ) { + cameraPosition = new idFixedPosition(); + } + return cameraPosition; } - return cameraPosition; -} protected: -idStr name; -int currentCameraPosition; -idVec3 lastDirection; -bool cameraRunning; -idCameraPosition *cameraPosition; -idList targetPositions; -idList events; -idCameraFOV fov; -int activeTarget; -float totalTime; -float baseTime; -long startTime; + idStr name; + int currentCameraPosition; + idVec3 lastDirection; + bool cameraRunning; + idCameraPosition *cameraPosition; + idList targetPositions; + idList events; + idCameraFOV fov; + int activeTarget; + float totalTime; + float baseTime; + long startTime; -bool cameraEdit; -bool editMode; + bool cameraEdit; + bool editMode; }; extern bool g_splineMode; diff --git a/libs/splines/util_list.h b/libs/splines/util_list.h index dfa92fb1..06b54512 100644 --- a/libs/splines/util_list.h +++ b/libs/splines/util_list.h @@ -28,30 +28,30 @@ template< class type > class idList { private: -int m_num; -int m_size; -int m_granularity; -type *m_list; + int m_num; + int m_size; + int m_granularity; + type *m_list; public: -idList( int granularity = 16 ); -~idList(); -void Clear( void ); -int Num( void ); -void SetNum( int num ); -void SetGranularity( int granularity ); -void Condense( void ); -int Size( void ); -void Resize( int size ); -type operator[]( int index ) const; -type &operator[]( int index ); -int Append( type const & obj ); -int AddUnique( type const & obj ); -type *Find( type const & obj, int *index = NULL ); -bool RemoveIndex( int index ); -bool Remove( type const & obj ); -typedef int cmp_t ( const void *, const void * ); -void Sort( cmp_t *compare ); + idList( int granularity = 16 ); + ~idList(); + void Clear( void ); + int Num( void ); + void SetNum( int num ); + void SetGranularity( int granularity ); + void Condense( void ); + int Size( void ); + void Resize( int size ); + type operator[]( int index ) const; + type &operator[]( int index ); + int Append( type const & obj ); + int AddUnique( type const & obj ); + type *Find( type const & obj, int *index = NULL ); + bool RemoveIndex( int index ); + bool Remove( type const & obj ); + typedef int cmp_t ( const void *, const void * ); + void Sort( cmp_t *compare ); }; /* diff --git a/libs/splines/util_str.cpp b/libs/splines/util_str.cpp index 62fdaedc..af66bd9b 100644 --- a/libs/splines/util_str.cpp +++ b/libs/splines/util_str.cpp @@ -41,7 +41,7 @@ char *idStr::__tolower char *idStr::tolower #endif ( - char *s1 + char *s1 ){ char *s; @@ -62,7 +62,7 @@ char *idStr::__toupper char *idStr::toupper #endif ( - char *s1 + char *s1 ){ char *s; @@ -78,9 +78,9 @@ char *idStr::toupper int idStr::icmpn ( - const char *s1, - const char *s2, - int n + const char *s1, + const char *s2, + int n ){ int c1; int c2; @@ -122,8 +122,8 @@ int idStr::icmpn int idStr::icmp ( - const char *s1, - const char *s2 + const char *s1, + const char *s2 ){ int c1; int c2; @@ -160,9 +160,9 @@ int idStr::icmp int idStr::cmpn ( - const char *s1, - const char *s2, - int n + const char *s1, + const char *s2, + int n ){ int c1; int c2; @@ -194,8 +194,8 @@ int idStr::cmpn int idStr::cmp ( - const char *s1, - const char *s2 + const char *s1, + const char *s2 ){ int c1; int c2; @@ -229,7 +229,7 @@ int idStr::cmp */ bool idStr::isNumeric ( - const char *str + const char *str ){ int len; int i; @@ -257,8 +257,8 @@ bool idStr::isNumeric idStr operator+ ( - const idStr& a, - const float b + const idStr& a, + const float b ){ char text[ 20 ]; @@ -272,8 +272,8 @@ idStr operator+ idStr operator+ ( - const idStr& a, - const int b + const idStr& a, + const int b ){ char text[ 20 ]; @@ -287,8 +287,8 @@ idStr operator+ idStr operator+ ( - const idStr& a, - const unsigned b + const idStr& a, + const unsigned b ){ char text[ 20 ]; @@ -302,7 +302,7 @@ idStr operator+ idStr& idStr::operator+= ( - const float a + const float a ){ char text[ 20 ]; @@ -314,7 +314,7 @@ idStr& idStr::operator+= idStr& idStr::operator+= ( - const int a + const int a ){ char text[ 20 ]; @@ -326,7 +326,7 @@ idStr& idStr::operator+= idStr& idStr::operator+= ( - const unsigned a + const unsigned a ){ char text[ 20 ]; @@ -338,7 +338,7 @@ idStr& idStr::operator+= void idStr::CapLength ( - int newlen + int newlen ){ assert( m_data ); @@ -354,7 +354,7 @@ void idStr::CapLength void idStr::EnsureDataWritable ( - void + void ){ assert( m_data ); strdata *olddata; @@ -421,7 +421,7 @@ void idStr::EnsureAlloced( int amount, bool keepold ) { void idStr::BackSlashesToSlashes ( - void + void ){ int i; @@ -437,10 +437,10 @@ void idStr::BackSlashesToSlashes void idStr::snprintf ( - char *dst, - int size, - const char *fmt, - ... + char *dst, + int size, + const char *fmt, + ... ){ char buffer[0x10000]; int len; @@ -472,7 +472,7 @@ void idStr::snprintf */ void TestStringClass ( - void + void ){ char ch; // ch == ? idStr *t; // t == ? diff --git a/libs/splines/util_str.h b/libs/splines/util_str.h index 57f05b5a..dbb14c59 100644 --- a/libs/splines/util_str.h +++ b/libs/splines/util_str.h @@ -37,115 +37,117 @@ void TestStringClass(); class strdata { public: -strdata () : len( 0 ), refcount( 0 ), data( NULL ), alloced( 0 ) {} -~strdata (){ - if ( data ) { - delete [] data; - } -} - -void AddRef() { refcount++; } -bool DelRef(){ // True if killed - refcount--; - if ( refcount < 0 ) { - delete this; - return true; + strdata () : len( 0 ), refcount( 0 ), data( NULL ), alloced( 0 ) {} + ~strdata (){ + if ( data ) { + delete [] data; + } } - return false; -} + void AddRef() { + refcount++; + } + bool DelRef(){ // True if killed + refcount--; + if ( refcount < 0 ) { + delete this; + return true; + } -int len; -int refcount; -char *data; -int alloced; + return false; + } + + int len; + int refcount; + char *data; + int alloced; }; class idStr { protected: -strdata *m_data; -void EnsureAlloced( int, bool keepold = true ); -void EnsureDataWritable(); + strdata *m_data; + void EnsureAlloced( int, bool keepold = true ); + void EnsureDataWritable(); public: -~idStr(); -idStr(); -idStr( const char *text ); -idStr( const idStr& string ); -idStr( const idStr string, int start, int end ); -idStr( const char ch ); -idStr( const int num ); -idStr( const float num ); -idStr( const unsigned num ); -int length( void ) const; -int allocated( void ) const; -const char * c_str( void ) const; + ~idStr(); + idStr(); + idStr( const char *text ); + idStr( const idStr& string ); + idStr( const idStr string, int start, int end ); + idStr( const char ch ); + idStr( const int num ); + idStr( const float num ); + idStr( const unsigned num ); + int length( void ) const; + int allocated( void ) const; + const char * c_str( void ) const; -void append( const char *text ); -void append( const idStr& text ); -char operator[]( int index ) const; -char& operator[]( int index ); + void append( const char *text ); + void append( const idStr& text ); + char operator[]( int index ) const; + char& operator[]( int index ); -void operator=( const idStr& text ); -void operator=( const char *text ); + void operator=( const idStr& text ); + void operator=( const char *text ); -friend idStr operator+( const idStr& a, const idStr& b ); -friend idStr operator+( const idStr& a, const char *b ); -friend idStr operator+( const char *a, const idStr& b ); + friend idStr operator+( const idStr& a, const idStr& b ); + friend idStr operator+( const idStr& a, const char *b ); + friend idStr operator+( const char *a, const idStr& b ); -friend idStr operator+( const idStr& a, const float b ); -friend idStr operator+( const idStr& a, const int b ); -friend idStr operator+( const idStr& a, const unsigned b ); -friend idStr operator+( const idStr& a, const bool b ); -friend idStr operator+( const idStr& a, const char b ); + friend idStr operator+( const idStr& a, const float b ); + friend idStr operator+( const idStr& a, const int b ); + friend idStr operator+( const idStr& a, const unsigned b ); + friend idStr operator+( const idStr& a, const bool b ); + friend idStr operator+( const idStr& a, const char b ); -idStr& operator+=( const idStr& a ); -idStr& operator+=( const char *a ); -idStr& operator+=( const float a ); -idStr& operator+=( const char a ); -idStr& operator+=( const int a ); -idStr& operator+=( const unsigned a ); -idStr& operator+=( const bool a ); + idStr& operator+=( const idStr& a ); + idStr& operator+=( const char *a ); + idStr& operator+=( const float a ); + idStr& operator+=( const char a ); + idStr& operator+=( const int a ); + idStr& operator+=( const unsigned a ); + idStr& operator+=( const bool a ); -friend bool operator==( const idStr& a, const idStr& b ); -friend bool operator==( const idStr& a, const char *b ); -friend bool operator==( const char *a, const idStr& b ); + friend bool operator==( const idStr& a, const idStr& b ); + friend bool operator==( const idStr& a, const char *b ); + friend bool operator==( const char *a, const idStr& b ); -friend bool operator!=( const idStr& a, const idStr& b ); -friend bool operator!=( const idStr& a, const char *b ); -friend bool operator!=( const char *a, const idStr& b ); + friend bool operator!=( const idStr& a, const idStr& b ); + friend bool operator!=( const idStr& a, const char *b ); + friend bool operator!=( const char *a, const idStr& b ); -operator const char *() const; -operator const char *(); + operator const char *() const; + operator const char *(); -int icmpn( const char *text, int n ) const; -int icmpn( const idStr& text, int n ) const; -int icmp( const char *text ) const; -int icmp( const idStr& text ) const; -int cmpn( const char *text, int n ) const; -int cmpn( const idStr& text, int n ) const; -int cmp( const char *text ) const; -int cmp( const idStr& text ) const; + int icmpn( const char *text, int n ) const; + int icmpn( const idStr& text, int n ) const; + int icmp( const char *text ) const; + int icmp( const idStr& text ) const; + int cmpn( const char *text, int n ) const; + int cmpn( const idStr& text, int n ) const; + int cmp( const char *text ) const; + int cmp( const idStr& text ) const; -void tolower( void ); -void toupper( void ); + void tolower( void ); + void toupper( void ); -static char *tolower( char *s1 ); -static char *toupper( char *s1 ); + static char *tolower( char *s1 ); + static char *toupper( char *s1 ); -static int icmpn( const char *s1, const char *s2, int n ); -static int icmp( const char *s1, const char *s2 ); -static int cmpn( const char *s1, const char *s2, int n ); -static int cmp( const char *s1, const char *s2 ); + static int icmpn( const char *s1, const char *s2, int n ); + static int icmp( const char *s1, const char *s2 ); + static int cmpn( const char *s1, const char *s2, int n ); + static int cmp( const char *s1, const char *s2 ); -static void snprintf( char *dst, int size, const char *fmt, ... ); + static void snprintf( char *dst, int size, const char *fmt, ... ); -static bool isNumeric( const char *str ); -bool isNumeric( void ) const; + static bool isNumeric( const char *str ); + bool isNumeric( void ) const; -void CapLength( int ); + void CapLength( int ); -void BackSlashesToSlashes(); + void BackSlashesToSlashes(); }; @@ -163,7 +165,7 @@ inline idStr::idStr() : m_data( NULL ){ inline idStr::idStr ( - const char *text + const char *text ) : m_data( NULL ){ int len; @@ -185,7 +187,7 @@ inline idStr::idStr inline idStr::idStr ( - const idStr& text + const idStr& text ) : m_data( NULL ){ m_data = text.m_data; m_data->AddRef(); @@ -193,9 +195,9 @@ inline idStr::idStr inline idStr::idStr ( - const idStr text, - int start, - int end + const idStr text, + int start, + int end ) : m_data( NULL ){ int i; int len; @@ -226,7 +228,7 @@ inline idStr::idStr inline idStr::idStr ( - const char ch + const char ch ) : m_data( NULL ){ EnsureAlloced( 2 ); @@ -237,7 +239,7 @@ inline idStr::idStr inline idStr::idStr ( - const float num + const float num ) : m_data( NULL ){ char text[ 32 ]; int len; @@ -251,7 +253,7 @@ inline idStr::idStr inline idStr::idStr ( - const int num + const int num ) : m_data( NULL ){ char text[ 32 ]; int len; @@ -265,7 +267,7 @@ inline idStr::idStr inline idStr::idStr ( - const unsigned num + const unsigned num ) : m_data( NULL ){ char text[ 32 ]; int len; @@ -293,7 +295,7 @@ inline const char *idStr::c_str( void ) const { inline void idStr::append ( - const char *text + const char *text ){ int len; @@ -310,7 +312,7 @@ inline void idStr::append inline void idStr::append ( - const idStr& text + const idStr& text ){ int len; @@ -342,7 +344,7 @@ inline char idStr::operator[]( int index ) const { inline char& idStr::operator[] ( - int index + int index ){ // Used for result for invalid indices static char dummy = 0; @@ -370,7 +372,7 @@ inline char& idStr::operator[] inline void idStr::operator= ( - const idStr& text + const idStr& text ){ // adding the reference before deleting our current reference prevents // us from deleting our string if we are copying from ourself @@ -381,7 +383,7 @@ inline void idStr::operator= inline void idStr::operator= ( - const char *text + const char *text ){ int len; @@ -441,8 +443,8 @@ inline void idStr::operator= inline idStr operator+ ( - const idStr& a, - const idStr& b + const idStr& a, + const idStr& b ){ idStr result( a ); @@ -453,8 +455,8 @@ inline idStr operator+ inline idStr operator+ ( - const idStr& a, - const char *b + const idStr& a, + const char *b ){ idStr result( a ); @@ -465,8 +467,8 @@ inline idStr operator+ inline idStr operator+ ( - const char *a, - const idStr& b + const char *a, + const idStr& b ){ idStr result( a ); @@ -477,8 +479,8 @@ inline idStr operator+ inline idStr operator+ ( - const idStr& a, - const bool b + const idStr& a, + const bool b ){ idStr result( a ); @@ -489,8 +491,8 @@ inline idStr operator+ inline idStr operator+ ( - const idStr& a, - const char b + const idStr& a, + const char b ){ char text[ 2 ]; @@ -502,7 +504,7 @@ inline idStr operator+ inline idStr& idStr::operator+= ( - const idStr& a + const idStr& a ){ append( a ); return *this; @@ -510,7 +512,7 @@ inline idStr& idStr::operator+= inline idStr& idStr::operator+= ( - const char *a + const char *a ){ append( a ); return *this; @@ -518,7 +520,7 @@ inline idStr& idStr::operator+= inline idStr& idStr::operator+= ( - const char a + const char a ){ char text[ 2 ]; @@ -531,7 +533,7 @@ inline idStr& idStr::operator+= inline idStr& idStr::operator+= ( - const bool a + const bool a ){ append( a ? "true" : "false" ); return *this; @@ -539,16 +541,16 @@ inline idStr& idStr::operator+= inline bool operator== ( - const idStr& a, - const idStr& b + const idStr& a, + const idStr& b ){ return ( !strcmp( a.c_str(), b.c_str() ) ); } inline bool operator== ( - const idStr& a, - const char *b + const idStr& a, + const char *b ){ assert( b ); if ( !b ) { @@ -559,8 +561,8 @@ inline bool operator== inline bool operator== ( - const char *a, - const idStr& b + const char *a, + const idStr& b ){ assert( a ); if ( !a ) { @@ -571,32 +573,32 @@ inline bool operator== inline bool operator!= ( - const idStr& a, - const idStr& b + const idStr& a, + const idStr& b ){ return !( a == b ); } inline bool operator!= ( - const idStr& a, - const char *b + const idStr& a, + const char *b ){ return !( a == b ); } inline bool operator!= ( - const char *a, - const idStr& b + const char *a, + const idStr& b ){ return !( a == b ); } inline int idStr::icmpn ( - const char *text, - int n + const char *text, + int n ) const { assert( m_data ); assert( text ); @@ -606,8 +608,8 @@ inline int idStr::icmpn inline int idStr::icmpn ( - const idStr& text, - int n + const idStr& text, + int n ) const { assert( m_data ); assert( text.m_data ); @@ -617,7 +619,7 @@ inline int idStr::icmpn inline int idStr::icmp ( - const char *text + const char *text ) const { assert( m_data ); assert( text ); @@ -627,7 +629,7 @@ inline int idStr::icmp inline int idStr::icmp ( - const idStr& text + const idStr& text ) const { assert( c_str() ); assert( text.c_str() ); @@ -637,7 +639,7 @@ inline int idStr::icmp inline int idStr::cmp ( - const char *text + const char *text ) const { assert( m_data ); assert( text ); @@ -647,7 +649,7 @@ inline int idStr::cmp inline int idStr::cmp ( - const idStr& text + const idStr& text ) const { assert( c_str() ); assert( text.c_str() ); @@ -657,8 +659,8 @@ inline int idStr::cmp inline int idStr::cmpn ( - const char *text, - int n + const char *text, + int n ) const { assert( c_str() ); assert( text ); @@ -668,8 +670,8 @@ inline int idStr::cmpn inline int idStr::cmpn ( - const idStr& text, - int n + const idStr& text, + int n ) const { assert( c_str() ); assert( text.c_str() ); @@ -679,7 +681,7 @@ inline int idStr::cmpn inline void idStr::tolower ( - void + void ){ assert( m_data ); @@ -690,7 +692,7 @@ inline void idStr::tolower inline void idStr::toupper ( - void + void ){ assert( m_data ); @@ -701,7 +703,7 @@ inline void idStr::toupper inline bool idStr::isNumeric ( - void + void ) const { assert( m_data ); return idStr::isNumeric( m_data->data ); @@ -713,7 +715,7 @@ inline idStr::operator const char *() { inline idStr::operator const char * ( - void + void ) const { return c_str(); } diff --git a/libs/str.h b/libs/str.h index 6996e64b..f315e60e 100644 --- a/libs/str.h +++ b/libs/str.h @@ -102,334 +102,368 @@ static char *g_pStrWork = 0; class Str { protected: -bool m_bIgnoreCase; -char *m_pStr; + bool m_bIgnoreCase; + char *m_pStr; public: -Str(){ - m_bIgnoreCase = true; - m_pStr = new char[1]; - m_pStr[0] = '\0'; -} - -Str( char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( p ); -} - -Str( const char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( p ); -} - -Str( const unsigned char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( reinterpret_cast( p ) ); -} - -Str( const char c ){ - m_bIgnoreCase = true; - m_pStr = new char[2]; - m_pStr[0] = c; - m_pStr[1] = '\0'; -} - -const char* GetBuffer() const { - return m_pStr; -} - -char* GetBuffer(){ - return m_pStr; -} - -Str( const Str &s ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( s.GetBuffer() ); -} - -void Deallocate(){ - delete []m_pStr; - m_pStr = 0; -} - -void Allocate( std::size_t n ){ - Deallocate(); - m_pStr = new char[n]; -} - -void MakeEmpty(){ - Deallocate(); - m_pStr = __StrDup( "" ); -} - -~Str(){ - Deallocate(); - // NOTE TTimo: someone explain this g_pStrWork to me? - if ( g_pStrWork ) { - delete []g_pStrWork; + Str(){ + m_bIgnoreCase = true; + m_pStr = new char[1]; + m_pStr[0] = '\0'; } - g_pStrWork = 0; -} -void MakeLower(){ - if ( m_pStr ) { - strlwr( m_pStr ); + Str( char *p ){ + m_bIgnoreCase = true; + m_pStr = __StrDup( p ); } -} -void MakeUpper(){ - if ( m_pStr ) { - strupr( m_pStr ); + Str( const char *p ){ + m_bIgnoreCase = true; + m_pStr = __StrDup( p ); } -} -void TrimRight(){ - char* lpsz = m_pStr; - char* lpszLast = 0; - while ( *lpsz != '\0' ) - { - if ( isspace( *lpsz ) ) { - if ( lpszLast == 0 ) { - lpszLast = lpsz; + Str( const unsigned char *p ){ + m_bIgnoreCase = true; + m_pStr = __StrDup( reinterpret_cast( p ) ); + } + + Str( const char c ){ + m_bIgnoreCase = true; + m_pStr = new char[2]; + m_pStr[0] = c; + m_pStr[1] = '\0'; + } + + const char* GetBuffer() const { + return m_pStr; + } + + char* GetBuffer(){ + return m_pStr; + } + + Str( const Str &s ){ + m_bIgnoreCase = true; + m_pStr = __StrDup( s.GetBuffer() ); + } + + void Deallocate(){ + delete []m_pStr; + m_pStr = 0; + } + + void Allocate( std::size_t n ){ + Deallocate(); + m_pStr = new char[n]; + } + + void MakeEmpty(){ + Deallocate(); + m_pStr = __StrDup( "" ); + } + + ~Str(){ + Deallocate(); + // NOTE TTimo: someone explain this g_pStrWork to me? + if ( g_pStrWork ) { + delete []g_pStrWork; + } + g_pStrWork = 0; + } + + void MakeLower(){ + if ( m_pStr ) { + strlwr( m_pStr ); + } + } + + void MakeUpper(){ + if ( m_pStr ) { + strupr( m_pStr ); + } + } + + void TrimRight(){ + char* lpsz = m_pStr; + char* lpszLast = 0; + while ( *lpsz != '\0' ) + { + if ( isspace( *lpsz ) ) { + if ( lpszLast == 0 ) { + lpszLast = lpsz; + } } + else{ + lpszLast = 0; + } + lpsz++; } - else{ - lpszLast = 0; + + if ( lpszLast != 0 ) { + // truncate at trailing space start + *lpszLast = '\0'; } - lpsz++; } - if ( lpszLast != 0 ) { - // truncate at trailing space start - *lpszLast = '\0'; + void TrimLeft(){ + // find first non-space character + char* lpsz = m_pStr; + while ( isspace( *lpsz ) ) + lpsz++; + + // fix up data and length + std::size_t nDataLength = GetLength() - ( lpsz - m_pStr ); + memmove( m_pStr, lpsz, ( nDataLength + 1 ) ); } -} -void TrimLeft(){ - // find first non-space character - char* lpsz = m_pStr; - while ( isspace( *lpsz ) ) - lpsz++; - - // fix up data and length - std::size_t nDataLength = GetLength() - ( lpsz - m_pStr ); - memmove( m_pStr, lpsz, ( nDataLength + 1 ) ); -} - -char* Find( const char *p ){ - return strstr( m_pStr, p ); -} + char* Find( const char *p ){ + return strstr( m_pStr, p ); + } // search starting at a given offset -char* Find( const char *p, std::size_t offset ){ - return strstr( m_pStr + offset, p ); -} - -char* Find( const char ch ){ - return strchr( m_pStr, ch ); -} - -char* ReverseFind( const char ch ){ - return strrchr( m_pStr, ch ); -} - -int Compare( const char* str ) const { - return strcmp( m_pStr, str ); -} - -int CompareNoCase( const char* str ) const { - return strcasecmp( m_pStr, str ); -} - -std::size_t GetLength(){ - return ( m_pStr ) ? strlen( m_pStr ) : 0; -} - -const char* Left( std::size_t n ){ - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - strncpy( g_pStrWork, m_pStr, n ); - g_pStrWork[n] = '\0'; - } - else - { - //g_pStrWork = ""; - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -const char* Right( std::size_t n ){ - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - std::size_t nStart = GetLength() - n; - strncpy( g_pStrWork, &m_pStr[nStart], n ); - g_pStrWork[n] = '\0'; - } - else - { - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -const char* Mid( std::size_t nFirst ) const { - return Mid( nFirst, strlen( m_pStr ) - nFirst ); -} - -const char* Mid( std::size_t first, std::size_t n ) const { - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - strncpy( g_pStrWork, m_pStr + first, n ); - g_pStrWork[n] = '\0'; - } - else - { - //g_pStrWork = ""; - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -#if 0 // defined(__G_LIB_H__) -void Format( const char* fmt, ... ){ - va_list args; - char *buffer; - - va_start( args, fmt ); - buffer = g_strdup_vprintf( fmt, args ); - va_end( args ); - - delete[] m_pStr; - m_pStr = __StrDup( buffer ); - g_free( buffer ); -} -#else -void Format( const char* fmt, ... ){ - char buffer[1024]; - - { - va_list args; - va_start( args, fmt ); - vsnprintf( buffer, 1023, fmt, args ); - va_end( args ); + char* Find( const char *p, std::size_t offset ){ + return strstr( m_pStr + offset, p ); } - delete[] m_pStr; - m_pStr = __StrDup( buffer ); -} -#endif - -void SetAt( std::size_t n, char ch ){ - if ( n < GetLength() ) { - m_pStr[n] = ch; - } -} - -// NOTE: unlike CString, this looses the pointer -void ReleaseBuffer( std::size_t n ){ - char* tmp = m_pStr; - tmp[n] = '\0'; - m_pStr = __StrDup( tmp ); - delete []tmp; -} -void ReleaseBuffer(){ - ReleaseBuffer( GetLength() ); -} - -char* GetBufferSetLength( std::size_t n ){ - char *p = new char[n + 1]; - strncpy( p, m_pStr, n ); - p[n] = '\0'; - delete []m_pStr; - m_pStr = p; - return m_pStr; -} - -// char& operator *() { return *m_pStr; } -// char& operator *() const { return *const_cast(this)->m_pStr; } -operator void*() { - return m_pStr; -} -operator char*() { - return m_pStr; -} -operator const char*() const { return reinterpret_cast( m_pStr ); } -operator unsigned char*() { - return reinterpret_cast( m_pStr ); -} -operator const unsigned char*() const { return reinterpret_cast( m_pStr ); } -Str& operator =( const Str& rhs ){ - if ( &rhs != this ) { - delete[] m_pStr; - m_pStr = __StrDup( rhs.m_pStr ); - } - return *this; -} - -Str& operator =( const char* pStr ){ - if ( m_pStr != pStr ) { - delete[] m_pStr; - m_pStr = __StrDup( pStr ); - } - return *this; -} - -Str& operator +=( const char ch ){ - std::size_t len = GetLength(); - char *p = new char[len + 1 + 1]; - - if ( m_pStr ) { - strcpy( p, m_pStr ); - delete[] m_pStr; + char* Find( const char ch ){ + return strchr( m_pStr, ch ); } - m_pStr = p; - m_pStr[len] = ch; - m_pStr[len + 1] = '\0'; + char* ReverseFind( const char ch ){ + return strrchr( m_pStr, ch ); + } - return *this; -} + int Compare( const char* str ) const { + return strcmp( m_pStr, str ); + } -Str& operator +=( const char *pStr ){ - if ( pStr ) { - if ( m_pStr ) { - char *p = new char[strlen( m_pStr ) + strlen( pStr ) + 1]; - strcpy( p, m_pStr ); - strcat( p, pStr ); - delete[] m_pStr; - m_pStr = p; + int CompareNoCase( const char* str ) const { + return strcasecmp( m_pStr, str ); + } + + std::size_t GetLength(){ + return ( m_pStr ) ? strlen( m_pStr ) : 0; + } + + const char* Left( std::size_t n ){ + delete []g_pStrWork; + if ( n > 0 ) { + g_pStrWork = new char[n + 1]; + strncpy( g_pStrWork, m_pStr, n ); + g_pStrWork[n] = '\0'; } else { - m_pStr = __StrDup( pStr ); + //g_pStrWork = ""; + g_pStrWork = new char[1]; + g_pStrWork[0] = '\0'; + } + return g_pStrWork; + } + + const char* Right( std::size_t n ){ + delete []g_pStrWork; + if ( n > 0 ) { + g_pStrWork = new char[n + 1]; + std::size_t nStart = GetLength() - n; + strncpy( g_pStrWork, &m_pStr[nStart], n ); + g_pStrWork[n] = '\0'; + } + else + { + g_pStrWork = new char[1]; + g_pStrWork[0] = '\0'; + } + return g_pStrWork; + } + + const char* Mid( std::size_t nFirst ) const { + return Mid( nFirst, strlen( m_pStr ) - nFirst ); + } + + const char* Mid( std::size_t first, std::size_t n ) const { + delete []g_pStrWork; + if ( n > 0 ) { + g_pStrWork = new char[n + 1]; + strncpy( g_pStrWork, m_pStr + first, n ); + g_pStrWork[n] = '\0'; + } + else + { + //g_pStrWork = ""; + g_pStrWork = new char[1]; + g_pStrWork[0] = '\0'; + } + return g_pStrWork; + } + +#if 0 // defined(__G_LIB_H__) + void Format( const char* fmt, ... ){ + va_list args; + char *buffer; + + va_start( args, fmt ); + buffer = g_strdup_vprintf( fmt, args ); + va_end( args ); + + delete[] m_pStr; + m_pStr = __StrDup( buffer ); + g_free( buffer ); + } +#else + void Format( const char* fmt, ... ){ + char buffer[1024]; + + { + va_list args; + va_start( args, fmt ); + vsnprintf( buffer, 1023, fmt, args ); + va_end( args ); + } + + delete[] m_pStr; + m_pStr = __StrDup( buffer ); + } +#endif + + void SetAt( std::size_t n, char ch ){ + if ( n < GetLength() ) { + m_pStr[n] = ch; } } - return *this; -} + +// NOTE: unlike CString, this looses the pointer + void ReleaseBuffer( std::size_t n ){ + char* tmp = m_pStr; + tmp[n] = '\0'; + m_pStr = __StrDup( tmp ); + delete []tmp; + } + void ReleaseBuffer(){ + ReleaseBuffer( GetLength() ); + } + + char* GetBufferSetLength( std::size_t n ){ + char *p = new char[n + 1]; + strncpy( p, m_pStr, n ); + p[n] = '\0'; + delete []m_pStr; + m_pStr = p; + return m_pStr; + } + +// char& operator *() { return *m_pStr; } +// char& operator *() const { return *const_cast(this)->m_pStr; } + operator void*() { + return m_pStr; + } + operator char*() { + return m_pStr; + } + operator const char*() const { + return reinterpret_cast( m_pStr ); + } + operator unsigned char*() { + return reinterpret_cast( m_pStr ); + } + operator const unsigned char*() const { + return reinterpret_cast( m_pStr ); + } + Str& operator =( const Str& rhs ){ + if ( &rhs != this ) { + delete[] m_pStr; + m_pStr = __StrDup( rhs.m_pStr ); + } + return *this; + } + + Str& operator =( const char* pStr ){ + if ( m_pStr != pStr ) { + delete[] m_pStr; + m_pStr = __StrDup( pStr ); + } + return *this; + } + + Str& operator +=( const char ch ){ + std::size_t len = GetLength(); + char *p = new char[len + 1 + 1]; + + if ( m_pStr ) { + strcpy( p, m_pStr ); + delete[] m_pStr; + } + + m_pStr = p; + m_pStr[len] = ch; + m_pStr[len + 1] = '\0'; + + return *this; + } + + Str& operator +=( const char *pStr ){ + if ( pStr ) { + if ( m_pStr ) { + char *p = new char[strlen( m_pStr ) + strlen( pStr ) + 1]; + strcpy( p, m_pStr ); + strcat( p, pStr ); + delete[] m_pStr; + m_pStr = p; + } + else + { + m_pStr = __StrDup( pStr ); + } + } + return *this; + } -bool operator ==( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) == 0 : strcmp( m_pStr, rhs.m_pStr ) == 0; } -bool operator ==( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; } -bool operator ==( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; } -bool operator !=( Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) != 0 : strcmp( m_pStr, rhs.m_pStr ) != 0; } -bool operator !=( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; } -bool operator !=( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; } -bool operator <( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) < 0 : strcmp( m_pStr, rhs.m_pStr ) < 0; } -bool operator <( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; } -bool operator <( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; } -bool operator >( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) > 0 : strcmp( m_pStr, rhs.m_pStr ) > 0; } -bool operator >( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; } -bool operator >( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; } -char& operator []( std::size_t nIndex ) { return m_pStr[nIndex]; } -const char& operator []( std::size_t nIndex ) const { return m_pStr[nIndex]; } -char GetAt( std::size_t nIndex ) { return m_pStr[nIndex]; } + bool operator ==( const Str& rhs ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) == 0 : strcmp( m_pStr, rhs.m_pStr ) == 0; + } + bool operator ==( char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; + } + bool operator ==( const char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; + } + bool operator !=( Str& rhs ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) != 0 : strcmp( m_pStr, rhs.m_pStr ) != 0; + } + bool operator !=( char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; + } + bool operator !=( const char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; + } + bool operator <( const Str& rhs ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) < 0 : strcmp( m_pStr, rhs.m_pStr ) < 0; + } + bool operator <( char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; + } + bool operator <( const char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; + } + bool operator >( const Str& rhs ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) > 0 : strcmp( m_pStr, rhs.m_pStr ) > 0; + } + bool operator >( char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; + } + bool operator >( const char* pStr ) const { + return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; + } + char& operator []( std::size_t nIndex ) { + return m_pStr[nIndex]; + } + const char& operator []( std::size_t nIndex ) const { + return m_pStr[nIndex]; + } + char GetAt( std::size_t nIndex ) { + return m_pStr[nIndex]; + } }; @@ -442,7 +476,7 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const inline void AddSlash( Str& strPath ){ if ( strPath.GetLength() > 0 ) { if ( ( strPath.GetAt( strPath.GetLength() - 1 ) != '/' ) && - ( strPath.GetAt( strPath.GetLength() - 1 ) != '\\' ) ) { + ( strPath.GetAt( strPath.GetLength() - 1 ) != '\\' ) ) { strPath += '/'; } } diff --git a/libs/stream/filestream.h b/libs/stream/filestream.h index 826f6b52..8b762e8c 100644 --- a/libs/stream/filestream.h +++ b/libs/stream/filestream.h @@ -49,38 +49,38 @@ inline int whence_for_seekdir( SeekableStream::seekdir direction ){ /// - Implements SeekableInputStream. class FileInputStream : public SeekableInputStream { -std::FILE* m_file; + std::FILE* m_file; public: -FileInputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "rb" ); -} -~FileInputStream(){ - if ( !failed() ) { - fclose( m_file ); + FileInputStream( const char* name ){ + m_file = name[0] == '\0' ? 0 : fopen( name, "rb" ); + } + ~FileInputStream(){ + if ( !failed() ) { + fclose( m_file ); + } } -} -bool failed() const { - return m_file == 0; -} + bool failed() const { + return m_file == 0; + } -size_type read( byte_type* buffer, size_type length ){ - return fread( buffer, 1, length, m_file ); -} + size_type read( byte_type* buffer, size_type length ){ + return fread( buffer, 1, length, m_file ); + } -size_type seek( size_type position ){ - return fseek( m_file, static_cast( position ), SEEK_SET ); -} -size_type seek( offset_type offset, seekdir direction ){ - return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); -} -size_type tell() const { - return ftell( m_file ); -} + size_type seek( size_type position ){ + return fseek( m_file, static_cast( position ), SEEK_SET ); + } + size_type seek( offset_type offset, seekdir direction ){ + return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); + } + size_type tell() const { + return ftell( m_file ); + } -std::FILE* file(){ - return m_file; -} + std::FILE* file(){ + return m_file; + } }; /// \brief A wrapper around a FileInputStream limiting access. @@ -89,21 +89,21 @@ std::FILE* file(){ /// - Provides input starting at an offset in the file for a limited range. class SubFileInputStream : public InputStream { -FileInputStream& m_istream; -size_type m_remaining; + FileInputStream& m_istream; + size_type m_remaining; public: -typedef FileInputStream::position_type position_type; + typedef FileInputStream::position_type position_type; -SubFileInputStream( FileInputStream& istream, position_type offset, size_type size ) - : m_istream( istream ), m_remaining( size ){ - m_istream.seek( offset ); -} + SubFileInputStream( FileInputStream& istream, position_type offset, size_type size ) + : m_istream( istream ), m_remaining( size ){ + m_istream.seek( offset ); + } -size_type read( byte_type* buffer, size_type length ){ - size_type result = m_istream.read( buffer, std::min( length, m_remaining ) ); - m_remaining -= result; - return result; -} + size_type read( byte_type* buffer, size_type length ){ + size_type result = m_istream.read( buffer, std::min( length, m_remaining ) ); + m_remaining -= result; + return result; + } }; @@ -113,34 +113,34 @@ size_type read( byte_type* buffer, size_type length ){ /// - Implements SeekableInputStream. class FileOutputStream : public SeekableOutputStream { -std::FILE* m_file; + std::FILE* m_file; public: -FileOutputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "wb" ); -} -~FileOutputStream(){ - if ( !failed() ) { - fclose( m_file ); + FileOutputStream( const char* name ){ + m_file = name[0] == '\0' ? 0 : fopen( name, "wb" ); + } + ~FileOutputStream(){ + if ( !failed() ) { + fclose( m_file ); + } } -} -bool failed() const { - return m_file == 0; -} + bool failed() const { + return m_file == 0; + } -size_type write( const byte_type* buffer, size_type length ){ - return fwrite( buffer, 1, length, m_file ); -} + size_type write( const byte_type* buffer, size_type length ){ + return fwrite( buffer, 1, length, m_file ); + } -size_type seek( size_type position ){ - return fseek( m_file, static_cast( position ), SEEK_SET ); -} -size_type seek( offset_type offset, seekdir direction ){ - return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); -} -size_type tell() const { - return ftell( m_file ); -} + size_type seek( size_type position ){ + return fseek( m_file, static_cast( position ), SEEK_SET ); + } + size_type seek( offset_type offset, seekdir direction ){ + return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); + } + size_type tell() const { + return ftell( m_file ); + } }; inline bool file_copy( const char* source, const char* target ){ diff --git a/libs/stream/memstream.h b/libs/stream/memstream.h index 75bd23ad..90c197f4 100644 --- a/libs/stream/memstream.h +++ b/libs/stream/memstream.h @@ -28,22 +28,22 @@ class BufferOutputStream : public TextOutputStream { -std::vector m_buffer; + std::vector m_buffer; public: -std::size_t write( const char* buffer, std::size_t length ){ - m_buffer.insert( m_buffer.end(), buffer, buffer + length ); - return length; -} -const char* data() const { - return &( *m_buffer.begin() ); -} -std::size_t size() const { - return m_buffer.size(); -} -void clear(){ - std::vector empty; - std::swap( empty, m_buffer ); -} + std::size_t write( const char* buffer, std::size_t length ){ + m_buffer.insert( m_buffer.end(), buffer, buffer + length ); + return length; + } + const char* data() const { + return &( *m_buffer.begin() ); + } + std::size_t size() const { + return m_buffer.size(); + } + void clear(){ + std::vector empty; + std::swap( empty, m_buffer ); + } }; template @@ -54,21 +54,21 @@ inline BufferOutputStream& operator<<( BufferOutputStream& ostream, const T& t ) class BufferInputStream : public TextInputStream { -const char* m_read; -const char* m_end; + const char* m_read; + const char* m_end; public: -BufferInputStream( const char* buffer, std::size_t length ) - : m_read( buffer ), m_end( buffer + length ){ -} -std::size_t read( char* buffer, std::size_t length ){ - std::size_t count = std::min( std::size_t( m_end - m_read ), length ); - const char* end = m_read + count; - while ( m_read != end ) - { - *buffer++ = *m_read++; + BufferInputStream( const char* buffer, std::size_t length ) + : m_read( buffer ), m_end( buffer + length ){ + } + std::size_t read( char* buffer, std::size_t length ){ + std::size_t count = std::min( std::size_t( m_end - m_read ), length ); + const char* end = m_read + count; + while ( m_read != end ) + { + *buffer++ = *m_read++; + } + return count; } - return count; -} }; #endif diff --git a/libs/stream/stringstream.h b/libs/stream/stringstream.h index a2897716..0b8892eb 100644 --- a/libs/stream/stringstream.h +++ b/libs/stream/stringstream.h @@ -32,122 +32,122 @@ /// Provides a limited STL-style interface to push and pop characters at the end of the string. class StringBuffer { -std::vector m_string; + std::vector m_string; public: -StringBuffer(){ - m_string.push_back( '\0' ); -} -explicit StringBuffer( std::size_t capacity ){ - m_string.reserve( capacity ); - m_string.push_back( '\0' ); -} -explicit StringBuffer( const char* string ) : m_string( string, string + string_length( string ) + 1 ){ -} + StringBuffer(){ + m_string.push_back( '\0' ); + } + explicit StringBuffer( std::size_t capacity ){ + m_string.reserve( capacity ); + m_string.push_back( '\0' ); + } + explicit StringBuffer( const char* string ) : m_string( string, string + string_length( string ) + 1 ){ + } -typedef std::vector::iterator iterator; -typedef std::vector::const_iterator const_iterator; + typedef std::vector::iterator iterator; + typedef std::vector::const_iterator const_iterator; -iterator begin(){ - return m_string.begin(); -} -const_iterator begin() const { - return m_string.begin(); -} -iterator end(){ - return m_string.end() - 1; -} -const_iterator end() const { - return m_string.end() - 1; -} + iterator begin(){ + return m_string.begin(); + } + const_iterator begin() const { + return m_string.begin(); + } + iterator end(){ + return m_string.end() - 1; + } + const_iterator end() const { + return m_string.end() - 1; + } -void push_back( char c ){ - m_string.insert( end(), c ); -} -void pop_back(){ - m_string.erase( end() - 1 ); -} -void push_range( const char* first, const char* last ){ - m_string.insert( end(), first, last ); -} -void push_string( const char* string ){ - push_range( string, string + string_length( string ) ); -} -char* c_str(){ - return &( *m_string.begin() ); -} -const char* c_str() const { - return &( *m_string.begin() ); -} + void push_back( char c ){ + m_string.insert( end(), c ); + } + void pop_back(){ + m_string.erase( end() - 1 ); + } + void push_range( const char* first, const char* last ){ + m_string.insert( end(), first, last ); + } + void push_string( const char* string ){ + push_range( string, string + string_length( string ) ); + } + char* c_str(){ + return &( *m_string.begin() ); + } + const char* c_str() const { + return &( *m_string.begin() ); + } -char& back(){ - return *( end() - 1 ); -} -const char& back() const { - return *( end() - 1 ); -} -bool empty() const { - return m_string.size() == 1; -} -void clear(){ - m_string.clear(); - m_string.push_back( '\0' ); -} + char& back(){ + return *( end() - 1 ); + } + const char& back() const { + return *( end() - 1 ); + } + bool empty() const { + return m_string.size() == 1; + } + void clear(){ + m_string.clear(); + m_string.push_back( '\0' ); + } }; /// \brief A TextOutputStream which writes to a StringBuffer. /// Similar to std::stringstream. class StringOutputStream : public TextOutputStream { -StringBuffer m_string; + StringBuffer m_string; public: -typedef StringBuffer::iterator iterator; -typedef StringBuffer::const_iterator const_iterator; + typedef StringBuffer::iterator iterator; + typedef StringBuffer::const_iterator const_iterator; -StringOutputStream(){ -} -StringOutputStream( std::size_t capacity ) : m_string( capacity ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - m_string.push_range( buffer, buffer + length ); - return length; -} + StringOutputStream(){ + } + StringOutputStream( std::size_t capacity ) : m_string( capacity ){ + } + std::size_t write( const char* buffer, std::size_t length ){ + m_string.push_range( buffer, buffer + length ); + return length; + } -template -StringOutputStream& operator()( Args&& ... args ){ - clear(); - ( *this << ... << std::forward( args ) ); - return *this; -} + template + StringOutputStream& operator()( Args&& ... args ){ + clear(); + ( *this << ... << std::forward( args ) ); + return *this; + } -operator const char*() const { - return c_str(); -} + operator const char*() const { + return c_str(); + } -iterator begin(){ - return m_string.begin(); -} -const_iterator begin() const { - return m_string.begin(); -} -iterator end(){ - return m_string.end(); -} -const_iterator end() const { - return m_string.end(); -} + iterator begin(){ + return m_string.begin(); + } + const_iterator begin() const { + return m_string.begin(); + } + iterator end(){ + return m_string.end(); + } + const_iterator end() const { + return m_string.end(); + } -bool empty() const { - return m_string.empty(); -} -char* c_str(){ - return m_string.c_str(); -} -const char* c_str() const { - return m_string.c_str(); -} -void clear(){ - m_string.clear(); -} + bool empty() const { + return m_string.empty(); + } + char* c_str(){ + return m_string.c_str(); + } + const char* c_str() const { + return m_string.c_str(); + } + void clear(){ + m_string.clear(); + } }; template diff --git a/libs/stream/textfilestream.h b/libs/stream/textfilestream.h index 41dc9384..488f7e7e 100644 --- a/libs/stream/textfilestream.h +++ b/libs/stream/textfilestream.h @@ -28,47 +28,47 @@ /// \brief A wrapper around a file input stream opened for reading in text mode. Similar to std::ifstream. class TextFileInputStream : public TextInputStream { -FILE* m_file; + FILE* m_file; public: -TextFileInputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "rt" ); -} -~TextFileInputStream(){ - if ( !failed() ) { - fclose( m_file ); + TextFileInputStream( const char* name ){ + m_file = name[0] == '\0' ? 0 : fopen( name, "rt" ); + } + ~TextFileInputStream(){ + if ( !failed() ) { + fclose( m_file ); + } } -} -bool failed() const { - return m_file == 0; -} + bool failed() const { + return m_file == 0; + } -std::size_t read( char* buffer, std::size_t length ){ - return fread( buffer, 1, length, m_file ); -} + std::size_t read( char* buffer, std::size_t length ){ + return fread( buffer, 1, length, m_file ); + } }; /// \brief A wrapper around a file input stream opened for writing in text mode. Similar to std::ofstream. class TextFileOutputStream : public TextOutputStream { -FILE* m_file; + FILE* m_file; public: -TextFileOutputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "wt" ); -} -~TextFileOutputStream(){ - if ( !failed() ) { - fclose( m_file ); + TextFileOutputStream( const char* name ){ + m_file = name[0] == '\0' ? 0 : fopen( name, "wt" ); + } + ~TextFileOutputStream(){ + if ( !failed() ) { + fclose( m_file ); + } } -} -bool failed() const { - return m_file == 0; -} + bool failed() const { + return m_file == 0; + } -std::size_t write( const char* buffer, std::size_t length ){ - return fwrite( buffer, 1, length, m_file ); -} + std::size_t write( const char* buffer, std::size_t length ){ + return fwrite( buffer, 1, length, m_file ); + } }; template diff --git a/libs/stream/textstream.h b/libs/stream/textstream.h index fb285a10..41bdee51 100644 --- a/libs/stream/textstream.h +++ b/libs/stream/textstream.h @@ -46,7 +46,7 @@ inline char* write_unsigned_nonzero_decimal_backward( char* ptr, unsigned int de return ptr; } - #if defined ( _WIN64 ) || defined ( __LP64__ ) +#if defined ( _WIN64 ) || defined ( __LP64__ ) inline char* write_size_t_nonzero_decimal_backward( char* ptr, size_t decimal ){ for (; decimal != 0; decimal /= 10 ) { @@ -54,7 +54,7 @@ inline char* write_size_t_nonzero_decimal_backward( char* ptr, size_t decimal ){ } return ptr; } - #endif +#endif inline char* write_signed_nonzero_decimal_backward( char* ptr, int decimal, bool show_positive ){ const bool negative = decimal < 0 ; @@ -76,7 +76,7 @@ inline char* write_unsigned_nonzero_decimal_backward( char* ptr, unsigned int de return ptr; } - #if defined ( _WIN64 ) || defined ( __LP64__ ) +#if defined ( _WIN64 ) || defined ( __LP64__ ) inline char* write_size_t_nonzero_decimal_backward( char* ptr, size_t decimal, bool show_positive ){ ptr = write_size_t_nonzero_decimal_backward( ptr, decimal ); if ( show_positive ) { @@ -84,7 +84,7 @@ inline char* write_size_t_nonzero_decimal_backward( char* ptr, size_t decimal, b } return ptr; } - #endif +#endif inline char* write_signed_decimal_backward( char* ptr, int decimal, bool show_positive ){ if ( decimal == 0 ) { @@ -108,7 +108,7 @@ inline char* write_unsigned_decimal_backward( char* ptr, unsigned int decimal, b return ptr; } - #if defined ( _WIN64 ) || defined ( __LP64__ ) +#if defined ( _WIN64 ) || defined ( __LP64__ ) inline char* write_size_t_decimal_backward( char* ptr, size_t decimal, bool show_positive ){ if ( decimal == 0 ) { *--ptr = '0'; @@ -119,7 +119,7 @@ inline char* write_size_t_decimal_backward( char* ptr, size_t decimal, bool show } return ptr; } - #endif +#endif } @@ -214,9 +214,9 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class HexChar { public: -char m_value; -HexChar( char value ) : m_value( value ){ -} + char m_value; + HexChar( char value ) : m_value( value ){ + } }; /// \brief Writes a single character \p c to \p ostream in hexadecimal form. @@ -231,12 +231,12 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class FloatFormat { public: -double m_f; -int m_width; -int m_precision; -FloatFormat( double f, int width, int precision ) - : m_f( f ), m_width( width ), m_precision( precision ){ -} + double m_f; + int m_width; + int m_precision; + FloatFormat( double f, int width, int precision ) + : m_f( f ), m_width( width ), m_precision( precision ){ + } }; /// \brief Writes a floating point value to \p ostream with a specific width and precision. @@ -252,9 +252,9 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class Decimal { public: -double m_f; -Decimal( double f ) : m_f( f ){ -} + double m_f; + Decimal( double f ) : m_f( f ){ + } }; /// \brief Writes a floating point value to \p ostream in decimal form with trailing zeros removed. @@ -290,10 +290,10 @@ template class Quoted { public: -const Type& m_type; -Quoted( const Type& type ) - : m_type( type ){ -} + const Type& m_type; + Quoted( const Type& type ) + : m_type( type ){ + } }; template @@ -311,9 +311,9 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class LowerCase { public: -const char* m_string; -LowerCase( const char* string ) : m_string( string ){ -} + const char* m_string; + LowerCase( const char* string ) : m_string( string ){ + } }; /// \brief Writes a string to \p ostream converted to lower-case. @@ -331,140 +331,140 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const template class SingleCharacterInputStream { -TextInputStreamType& m_inputStream; -char m_buffer[SIZE]; -char* m_cur; -char* m_end; + TextInputStreamType& m_inputStream; + char m_buffer[SIZE]; + char* m_cur; + char* m_end; -bool fillBuffer(){ - m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); - m_cur = m_buffer; - return m_cur != m_end; -} + bool fillBuffer(){ + m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); + m_cur = m_buffer; + return m_cur != m_end; + } public: -SingleCharacterInputStream( TextInputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer ), m_end( m_buffer ){ -} -bool readChar( char& c ){ - if ( m_cur == m_end && !fillBuffer() ) { - return false; + SingleCharacterInputStream( TextInputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer ), m_end( m_buffer ){ } + bool readChar( char& c ){ + if ( m_cur == m_end && !fillBuffer() ) { + return false; + } - c = *m_cur++; - return true; -} + c = *m_cur++; + return true; + } }; /// doublefuffered to be able to read forward for map format (valve220) detection template class SingleCharacterInputStreamDoubleBuffered { -TextInputStreamType& m_inputStream; -char m_bu[SIZE]; -char* m_buffer; -char* m_cur; -char* m_end; + TextInputStreamType& m_inputStream; + char m_bu[SIZE]; + char* m_buffer; + char* m_cur; + char* m_end; -char m_bu2[SIZE]; -char* m_buffer2; -char* m_end2; + char m_bu2[SIZE]; + char* m_buffer2; + char* m_end2; -bool fillBuffer(){ - std::swap( m_buffer, m_buffer2 ); - m_cur = m_buffer; - m_end = m_end2; - m_end2 = m_buffer2 + m_inputStream.read( m_buffer2, SIZE ); - return m_cur != m_end; -} + bool fillBuffer(){ + std::swap( m_buffer, m_buffer2 ); + m_cur = m_buffer; + m_end = m_end2; + m_end2 = m_buffer2 + m_inputStream.read( m_buffer2, SIZE ); + return m_cur != m_end; + } public: -SingleCharacterInputStreamDoubleBuffered( TextInputStreamType& inputStream ) : m_inputStream( inputStream ), m_buffer( m_bu ), m_cur( m_buffer ), m_end( m_buffer ), m_buffer2( m_bu2 ){ - m_end2 = m_buffer2 + m_inputStream.read( m_buffer2, SIZE ); -} -bool readChar( char& c ){ - if ( m_cur == m_end && !fillBuffer() ) { - return false; + SingleCharacterInputStreamDoubleBuffered( TextInputStreamType& inputStream ) : m_inputStream( inputStream ), m_buffer( m_bu ), m_cur( m_buffer ), m_end( m_buffer ), m_buffer2( m_bu2 ){ + m_end2 = m_buffer2 + m_inputStream.read( m_buffer2, SIZE ); } + bool readChar( char& c ){ + if ( m_cur == m_end && !fillBuffer() ) { + return false; + } - c = *m_cur++; - return true; -} -bool bufferContains( const char* str ) const{ - return ( std::search( m_cur, m_end, str, str + strlen( str ) ) != m_end ) || - ( std::search( m_buffer2, m_end2, str, str + strlen( str ) ) != m_end2 ); -} + c = *m_cur++; + return true; + } + bool bufferContains( const char* str ) const{ + return ( std::search( m_cur, m_end, str, str + strlen( str ) ) != m_end ) || + ( std::search( m_buffer2, m_end2, str, str + strlen( str ) ) != m_end2 ); + } }; /// \brief A wrapper for a TextOutputStream, optimised for writing a single character at a time. class SingleCharacterOutputStream : public TextOutputStream { -enum unnamed0 { m_bufsize = 1024 }; -TextOutputStream& m_ostream; -char m_buffer[m_bufsize]; -char* m_pos; -const char* m_end; + enum unnamed0 { m_bufsize = 1024 }; + TextOutputStream& m_ostream; + char m_buffer[m_bufsize]; + char* m_pos; + const char* m_end; -const char* end() const { - return m_end; -} -void reset(){ - m_pos = m_buffer; -} -void flush(){ - m_ostream.write( m_buffer, m_pos - m_buffer ); - reset(); -} + const char* end() const { + return m_end; + } + void reset(){ + m_pos = m_buffer; + } + void flush(){ + m_ostream.write( m_buffer, m_pos - m_buffer ); + reset(); + } public: -SingleCharacterOutputStream( TextOutputStream& ostream ) : m_ostream( ostream ), m_pos( m_buffer ), m_end( m_buffer + m_bufsize ){ -} -~SingleCharacterOutputStream(){ - flush(); -} -void write( const char c ){ - if ( m_pos == end() ) { + SingleCharacterOutputStream( TextOutputStream& ostream ) : m_ostream( ostream ), m_pos( m_buffer ), m_end( m_buffer + m_bufsize ){ + } + ~SingleCharacterOutputStream(){ flush(); } - *m_pos++ = c; -} -std::size_t write( const char* buffer, std::size_t length ){ - const char*const end = buffer + length; - for ( const char* p = buffer; p != end; ++p ) - { - write( *p ); + void write( const char c ){ + if ( m_pos == end() ) { + flush(); + } + *m_pos++ = c; + } + std::size_t write( const char* buffer, std::size_t length ){ + const char*const end = buffer + length; + for ( const char* p = buffer; p != end; ++p ) + { + write( *p ); + } + return length; } - return length; -} }; /// \brief A wrapper for a TextOutputStream, optimised for writing a few characters at a time. template class BufferedTextOutputStream : public TextOutputStream { -TextOutputStreamType outputStream; -char m_buffer[SIZE]; -char* m_cur; + TextOutputStreamType outputStream; + char m_buffer[SIZE]; + char* m_cur; public: -BufferedTextOutputStream( TextOutputStreamType& outputStream ) : outputStream( outputStream ), m_cur( m_buffer ){ -} -~BufferedTextOutputStream(){ - outputStream.write( m_buffer, m_cur - m_buffer ); -} -std::size_t write( const char* buffer, std::size_t length ){ - std::size_t remaining = length; - for (;; ) - { - std::size_t n = std::min( remaining, std::size_t( ( m_buffer + SIZE ) - m_cur ) ); - m_cur = std::copy( buffer, buffer + n, m_cur ); - remaining -= n; - if ( remaining == 0 ) { - return 0; - } - outputStream.write( m_buffer, SIZE ); - m_cur = m_buffer; + BufferedTextOutputStream( TextOutputStreamType& outputStream ) : outputStream( outputStream ), m_cur( m_buffer ){ + } + ~BufferedTextOutputStream(){ + outputStream.write( m_buffer, m_cur - m_buffer ); + } + std::size_t write( const char* buffer, std::size_t length ){ + std::size_t remaining = length; + for (;; ) + { + std::size_t n = std::min( remaining, std::size_t( ( m_buffer + SIZE ) - m_cur ) ); + m_cur = std::copy( buffer, buffer + n, m_cur ); + remaining -= n; + if ( remaining == 0 ) { + return 0; + } + outputStream.write( m_buffer, SIZE ); + m_cur = m_buffer; + } } -} }; #endif diff --git a/libs/string/pooledstring.h b/libs/string/pooledstring.h index a388acff..c98db9dd 100644 --- a/libs/string/pooledstring.h +++ b/libs/string/pooledstring.h @@ -39,54 +39,54 @@ inline void StringPool_analyse( StringPool& pool ){ template class PooledString { -StringPool::iterator m_i; -static StringPool::iterator increment( StringPool::iterator i ){ - ++( *i ).value; - return i; -} -static StringPool::iterator insert( const char* string ){ - StringPool::iterator i = PoolContext::instance().find( const_cast( string ) ); - if ( i == PoolContext::instance().end() ) { - return PoolContext::instance().insert( string_clone( string ), 1 ); + StringPool::iterator m_i; + static StringPool::iterator increment( StringPool::iterator i ){ + ++( *i ).value; + return i; } - return increment( i ); -} -static void erase( StringPool::iterator i ){ - if ( --( *i ).value == 0 ) { - char* string = ( *i ).key; - PoolContext::instance().erase( i ); - string_release( string, string_length( string ) ); + static StringPool::iterator insert( const char* string ){ + StringPool::iterator i = PoolContext::instance().find( const_cast( string ) ); + if ( i == PoolContext::instance().end() ) { + return PoolContext::instance().insert( string_clone( string ), 1 ); + } + return increment( i ); + } + static void erase( StringPool::iterator i ){ + if ( --( *i ).value == 0 ) { + char* string = ( *i ).key; + PoolContext::instance().erase( i ); + string_release( string, string_length( string ) ); + } } -} public: -PooledString() : m_i( insert( "" ) ){ -} -PooledString( const PooledString& other ) : m_i( increment( other.m_i ) ){ -} -PooledString( const char* string ) : m_i( insert( string ) ){ -} -~PooledString(){ - erase( m_i ); -} -PooledString& operator=( const PooledString& other ){ - PooledString tmp( other ); - tmp.swap( *this ); - return *this; -} -PooledString& operator=( const char* string ){ - PooledString tmp( string ); - tmp.swap( *this ); - return *this; -} -void swap( PooledString& other ){ - std::swap( m_i, other.m_i ); -} -bool operator==( const PooledString& other ) const { - return m_i == other.m_i; -} -const char* c_str() const { - return ( *m_i ).key; -} + PooledString() : m_i( insert( "" ) ){ + } + PooledString( const PooledString& other ) : m_i( increment( other.m_i ) ){ + } + PooledString( const char* string ) : m_i( insert( string ) ){ + } + ~PooledString(){ + erase( m_i ); + } + PooledString& operator=( const PooledString& other ){ + PooledString tmp( other ); + tmp.swap( *this ); + return *this; + } + PooledString& operator=( const char* string ){ + PooledString tmp( string ); + tmp.swap( *this ); + return *this; + } + void swap( PooledString& other ){ + std::swap( m_i, other.m_i ); + } + bool operator==( const PooledString& other ) const { + return m_i == other.m_i; + } + const char* c_str() const { + return ( *m_i ).key; + } }; diff --git a/libs/string/string.h b/libs/string/string.h index 6bd36210..c84d617c 100644 --- a/libs/string/string.h +++ b/libs/string/string.h @@ -277,50 +277,50 @@ inline const char* string_in_string_nocase( const char* haystack, const char* ne /// \brief A re-entrant string tokeniser similar to strchr. class StringTokeniser { -bool istoken( char c ) const { - if ( strchr( m_delimiters, c ) != 0 ) { - return false; - } - return true; -} -const char* advance(){ - const char* token = m_pos; - bool intoken = true; - while ( !string_empty( m_pos ) ) - { - if ( !istoken( *m_pos ) ) { - *m_pos = '\0'; - intoken = false; + bool istoken( char c ) const { + if ( strchr( m_delimiters, c ) != 0 ) { + return false; } - else if ( !intoken ) { - return token; - } - ++m_pos; + return true; } - return token; -} -std::size_t m_length; -char* m_string; -char* m_pos; -const char* m_delimiters; + const char* advance(){ + const char* token = m_pos; + bool intoken = true; + while ( !string_empty( m_pos ) ) + { + if ( !istoken( *m_pos ) ) { + *m_pos = '\0'; + intoken = false; + } + else if ( !intoken ) { + return token; + } + ++m_pos; + } + return token; + } + std::size_t m_length; + char* m_string; + char* m_pos; + const char* m_delimiters; public: -StringTokeniser( const char* string, const char* delimiters = " \n\r\t\v" ) : - m_length( string_length( string ) ), - m_string( string_copy( string_new( m_length ), string ) ), - m_pos( m_string ), - m_delimiters( delimiters ){ - while ( !string_empty( m_pos ) && !istoken( *m_pos ) ) - { - ++m_pos; + StringTokeniser( const char* string, const char* delimiters = " \n\r\t\v" ) : + m_length( string_length( string ) ), + m_string( string_copy( string_new( m_length ), string ) ), + m_pos( m_string ), + m_delimiters( delimiters ){ + while ( !string_empty( m_pos ) && !istoken( *m_pos ) ) + { + ++m_pos; + } + } + ~StringTokeniser(){ + string_release( m_string, m_length ); } -} -~StringTokeniser(){ - string_release( m_string, m_length ); -} /// \brief Returns the next token or "" if there are no more tokens available. -const char* getToken(){ - return advance(); -} + const char* getToken(){ + return advance(); + } }; /// \brief A non-mutable c-style string. @@ -335,42 +335,42 @@ class String : public Buffer { public: -String() - : Buffer(){ -} -String( const char* string ) - : Buffer( string ){ -} -String( StringRange range ) - : Buffer( range ){ -} -String( const String& other ) - : Buffer( other ){ -} + String() + : Buffer(){ + } + String( const char* string ) + : Buffer( string ){ + } + String( StringRange range ) + : Buffer( range ){ + } + String( const String& other ) + : Buffer( other ){ + } -String& operator=( const String& other ){ - String temp( other ); - temp.swap( *this ); - return *this; -} -String& operator=( const char* string ){ - String temp( string ); - temp.swap( *this ); - return *this; -} -String& operator=( StringRange range ){ - String temp( range ); - temp.swap( *this ); - return *this; -} + String& operator=( const String& other ){ + String temp( other ); + temp.swap( *this ); + return *this; + } + String& operator=( const char* string ){ + String temp( string ); + temp.swap( *this ); + return *this; + } + String& operator=( StringRange range ){ + String temp( range ); + temp.swap( *this ); + return *this; + } -void swap( String& other ){ - Buffer::swap( other ); -} + void swap( String& other ){ + Buffer::swap( other ); + } -bool empty() const { - return string_empty( Buffer::c_str() ); -} + bool empty() const { + return string_empty( Buffer::c_str() ); + } }; template @@ -418,44 +418,44 @@ inline void swap( String& self, String& other ){ template class CopiedBuffer : private Allocator { -char* m_string; + char* m_string; -char* copy_range( StringRange range ){ - return string_clone_range( range, static_cast( *this ) ); -} -char* copy( const char* other ){ - return string_clone( other, static_cast( *this ) ); -} -void destroy( char* string ){ - string_release( string, string_length( string ), static_cast( *this ) ); -} + char* copy_range( StringRange range ){ + return string_clone_range( range, static_cast( *this ) ); + } + char* copy( const char* other ){ + return string_clone( other, static_cast( *this ) ); + } + void destroy( char* string ){ + string_release( string, string_length( string ), static_cast( *this ) ); + } protected: -~CopiedBuffer(){ - destroy( m_string ); -} + ~CopiedBuffer(){ + destroy( m_string ); + } public: -CopiedBuffer() - : m_string( copy( "" ) ){ -} -explicit CopiedBuffer( const Allocator& allocator ) - : Allocator( allocator ), m_string( copy( "" ) ){ -} -CopiedBuffer( const CopiedBuffer& other ) - : Allocator( other ), m_string( copy( other.m_string ) ){ -} -CopiedBuffer( const char* string, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_string( copy( string ) ){ -} -CopiedBuffer( StringRange range, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_string( copy_range( range ) ){ -} -const char* c_str() const { - return m_string; -} -void swap( CopiedBuffer& other ){ - string_swap( m_string, other.m_string ); -} + CopiedBuffer() + : m_string( copy( "" ) ){ + } + explicit CopiedBuffer( const Allocator& allocator ) + : Allocator( allocator ), m_string( copy( "" ) ){ + } + CopiedBuffer( const CopiedBuffer& other ) + : Allocator( other ), m_string( copy( other.m_string ) ){ + } + CopiedBuffer( const char* string, const Allocator& allocator = Allocator() ) + : Allocator( allocator ), m_string( copy( string ) ){ + } + CopiedBuffer( StringRange range, const Allocator& allocator = Allocator() ) + : Allocator( allocator ), m_string( copy_range( range ) ){ + } + const char* c_str() const { + return m_string; + } + void swap( CopiedBuffer& other ){ + string_swap( m_string, other.m_string ); + } }; /// \brief A non-mutable string which uses copy-by-value for assignment. @@ -466,65 +466,65 @@ typedef String< CopiedBuffer< DefaultAllocator > > CopiedString; template class SmartBuffer : private Allocator { -char* m_buffer; + char* m_buffer; -char* copy_range( StringRange range ){ - char* buffer = Allocator::allocate( sizeof( std::size_t ) + ( range.last - range.first ) + 1 ); - strncpy( buffer + sizeof( std::size_t ), range.first, range.last - range.first ); - buffer[sizeof( std::size_t ) + ( range.last - range.first )] = '\0'; - *reinterpret_cast( buffer ) = 0; - return buffer; -} -char* copy( const char* string ){ - char* buffer = Allocator::allocate( sizeof( std::size_t ) + string_length( string ) + 1 ); - strcpy( buffer + sizeof( std::size_t ), string ); - *reinterpret_cast( buffer ) = 0; - return buffer; -} -void destroy( char* buffer ){ - Allocator::deallocate( buffer, sizeof( std::size_t ) + string_length( c_str() ) + 1 ); -} - -void incref( char* buffer ){ - ++( *reinterpret_cast( buffer ) ); -} -void decref( char* buffer ){ - if ( --( *reinterpret_cast( buffer ) ) == 0 ) { - destroy( buffer ); + char* copy_range( StringRange range ){ + char* buffer = Allocator::allocate( sizeof( std::size_t ) + ( range.last - range.first ) + 1 ); + strncpy( buffer + sizeof( std::size_t ), range.first, range.last - range.first ); + buffer[sizeof( std::size_t ) + ( range.last - range.first )] = '\0'; + *reinterpret_cast( buffer ) = 0; + return buffer; + } + char* copy( const char* string ){ + char* buffer = Allocator::allocate( sizeof( std::size_t ) + string_length( string ) + 1 ); + strcpy( buffer + sizeof( std::size_t ), string ); + *reinterpret_cast( buffer ) = 0; + return buffer; + } + void destroy( char* buffer ){ + Allocator::deallocate( buffer, sizeof( std::size_t ) + string_length( c_str() ) + 1 ); + } + + void incref( char* buffer ){ + ++( *reinterpret_cast( buffer ) ); + } + void decref( char* buffer ){ + if ( --( *reinterpret_cast( buffer ) ) == 0 ) { + destroy( buffer ); + } } -} protected: -~SmartBuffer(){ - decref( m_buffer ); -} + ~SmartBuffer(){ + decref( m_buffer ); + } public: -SmartBuffer() - : m_buffer( copy( "" ) ){ - incref( m_buffer ); -} -explicit SmartBuffer( const Allocator& allocator ) - : Allocator( allocator ), m_buffer( copy( "" ) ){ - incref( m_buffer ); -} -SmartBuffer( const SmartBuffer& other ) - : Allocator( other ), m_buffer( other.m_buffer ){ - incref( m_buffer ); -} -SmartBuffer( const char* string, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_buffer( copy( string ) ){ - incref( m_buffer ); -} -SmartBuffer( StringRange range, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_buffer( copy_range( range ) ){ - incref( m_buffer ); -} -const char* c_str() const { - return m_buffer + sizeof( std::size_t ); -} -void swap( SmartBuffer& other ){ - string_swap( m_buffer, other.m_buffer ); -} + SmartBuffer() + : m_buffer( copy( "" ) ){ + incref( m_buffer ); + } + explicit SmartBuffer( const Allocator& allocator ) + : Allocator( allocator ), m_buffer( copy( "" ) ){ + incref( m_buffer ); + } + SmartBuffer( const SmartBuffer& other ) + : Allocator( other ), m_buffer( other.m_buffer ){ + incref( m_buffer ); + } + SmartBuffer( const char* string, const Allocator& allocator = Allocator() ) + : Allocator( allocator ), m_buffer( copy( string ) ){ + incref( m_buffer ); + } + SmartBuffer( StringRange range, const Allocator& allocator = Allocator() ) + : Allocator( allocator ), m_buffer( copy_range( range ) ){ + incref( m_buffer ); + } + const char* c_str() const { + return m_buffer + sizeof( std::size_t ); + } + void swap( SmartBuffer& other ){ + string_swap( m_buffer, other.m_buffer ); + } }; /// \brief A non-mutable string which uses copy-by-reference for assignment of SmartString. @@ -533,9 +533,9 @@ typedef String< SmartBuffer< DefaultAllocator > > SmartString; class StringEqualNoCase { public: -bool operator()( const CopiedString& key, const CopiedString& other ) const { - return string_equal_nocase( key.c_str(), other.c_str() ); -} + bool operator()( const CopiedString& key, const CopiedString& other ) const { + return string_equal_nocase( key.c_str(), other.c_str() ); + } }; struct StringLessNoCase diff --git a/libs/stringio.h b/libs/stringio.h index 72bfc1ee..6b87b701 100644 --- a/libs/stringio.h +++ b/libs/stringio.h @@ -372,23 +372,23 @@ template class ImportConvert1 { public: -static void thunk( void* environment, FirstArgument firstArgument ){ - Caller::thunk( environment, FirstConversion( firstArgument ) ); -} + static void thunk( void* environment, FirstArgument firstArgument ){ + Caller::thunk( environment, FirstConversion( firstArgument ) ); + } }; class CopiedStringFromString { -CopiedString m_value; + CopiedString m_value; public: -CopiedStringFromString( const char* string ){ - CopiedString_importString( m_value, string ); -} -operator CopiedString() const -{ - return m_value; -} + CopiedStringFromString( const char* string ){ + CopiedString_importString( m_value, string ); + } + operator CopiedString() const + { + return m_value; + } }; inline void CopiedString_toString( const StringImportCallback& self, CopiedString value ){ @@ -410,15 +410,15 @@ inline StringExportCallback makeCopiedStringStringExportCallback( const Caller& class BoolFromString { -bool m_value; + bool m_value; public: -BoolFromString( const char* string ){ - Bool_importString( m_value, string ); -} -operator bool() const -{ - return m_value; -} + BoolFromString( const char* string ){ + Bool_importString( m_value, string ); + } + operator bool() const + { + return m_value; + } }; inline void Bool_toString( const StringImportCallback& self, bool value ){ @@ -440,15 +440,15 @@ inline StringExportCallback makeBoolStringExportCallback( const Caller& caller ) class IntFromString { -int m_value; + int m_value; public: -IntFromString( const char* string ){ - Int_importString( m_value, string ); -} -operator int() const -{ - return m_value; -} + IntFromString( const char* string ){ + Int_importString( m_value, string ); + } + operator int() const + { + return m_value; + } }; inline void Int_toString( const StringImportCallback& self, int value ){ @@ -471,15 +471,15 @@ inline StringExportCallback makeIntStringExportCallback( const Caller& caller ){ class SizeFromString { -std::size_t m_value; + std::size_t m_value; public: -SizeFromString( const char* string ){ - Size_importString( m_value, string ); -} -operator std::size_t() const -{ - return m_value; -} + SizeFromString( const char* string ){ + Size_importString( m_value, string ); + } + operator std::size_t() const + { + return m_value; + } }; inline void Size_toString( const StringImportCallback& self, std::size_t value ){ diff --git a/libs/transformlib.h b/libs/transformlib.h index 362e93a2..9dbc2ac0 100644 --- a/libs/transformlib.h +++ b/libs/transformlib.h @@ -31,9 +31,9 @@ class TransformNode { public: -STRING_CONSTANT( Name, "TransformNode" ); + STRING_CONSTANT( Name, "TransformNode" ); /// \brief Returns the transform which maps the node's local-space into the local-space of its parent node. -virtual const Matrix4& localToParent() const = 0; + virtual const Matrix4& localToParent() const = 0; }; /// \brief A transform node which has no effect. @@ -41,26 +41,26 @@ class IdentityTransform : public TransformNode { public: /// \brief Returns the identity matrix. -const Matrix4& localToParent() const { - return g_matrix4_identity; -} + const Matrix4& localToParent() const { + return g_matrix4_identity; + } }; /// \brief A transform node which stores a generic transformation matrix. class MatrixTransform : public TransformNode { -Matrix4 m_localToParent; + Matrix4 m_localToParent; public: -MatrixTransform() : m_localToParent( g_matrix4_identity ){ -} + MatrixTransform() : m_localToParent( g_matrix4_identity ){ + } -Matrix4& localToParent(){ - return m_localToParent; -} + Matrix4& localToParent(){ + return m_localToParent; + } /// \brief Returns the stored local->parent transform. -const Matrix4& localToParent() const { - return m_localToParent; -} + const Matrix4& localToParent() const { + return m_localToParent; + } }; @@ -119,14 +119,14 @@ const TransformModifierType TRANSFORM_COMPONENT = true; class Transformable { public: -STRING_CONSTANT( Name, "Transformable" ); + STRING_CONSTANT( Name, "Transformable" ); -virtual void setType( TransformModifierType type ) = 0; -virtual void setTranslation( const Translation& value ) = 0; -virtual void setRotation( const Rotation& value ) = 0; -virtual void setScale( const Scale& value ) = 0; -virtual void setSkew( const Skew& value ) = 0; -virtual void freezeTransform() = 0; + virtual void setType( TransformModifierType type ) = 0; + virtual void setTranslation( const Translation& value ) = 0; + virtual void setRotation( const Rotation& value ) = 0; + virtual void setScale( const Scale& value ) = 0; + virtual void setSkew( const Skew& value ) = 0; + virtual void freezeTransform() = 0; }; const Translation c_translation_identity = Translation( 0, 0, 0 ); @@ -137,157 +137,157 @@ const Skew c_skew_identity = Skew( 4, 0 ); class TransformModifier : public Transformable { -Translation m_translation; -Rotation m_rotation; -Scale m_scale; -Skew m_skew; -Callback m_changed; -Callback m_apply; -TransformModifierType m_type; + Translation m_translation; + Rotation m_rotation; + Scale m_scale; + Skew m_skew; + Callback m_changed; + Callback m_apply; + TransformModifierType m_type; public: -TransformModifier( const Callback& changed, const Callback& apply ) : - m_translation( c_translation_identity ), - m_rotation( c_quaternion_identity ), - m_scale( c_scale_identity ), - m_skew( c_skew_identity ), - m_changed( changed ), - m_apply( apply ), - m_type( TRANSFORM_PRIMITIVE ){ -} -void setType( TransformModifierType type ){ - m_type = type; -} -TransformModifierType getType() const { - return m_type; -} -void setTranslation( const Translation& value ){ - m_translation = value; - m_changed(); -} -void setRotation( const Rotation& value ){ - m_rotation = value; - m_changed(); -} -void setScale( const Scale& value ){ - m_scale = value; - m_changed(); -} -void setSkew( const Skew& value ){ - m_skew = value; - m_changed(); -} -void freezeTransform(){ - if ( !isIdentity() ) { - m_apply(); - setIdentity(); + TransformModifier( const Callback& changed, const Callback& apply ) : + m_translation( c_translation_identity ), + m_rotation( c_quaternion_identity ), + m_scale( c_scale_identity ), + m_skew( c_skew_identity ), + m_changed( changed ), + m_apply( apply ), + m_type( TRANSFORM_PRIMITIVE ){ + } + void setType( TransformModifierType type ){ + m_type = type; + } + TransformModifierType getType() const { + return m_type; + } + void setTranslation( const Translation& value ){ + m_translation = value; m_changed(); } -} -const Translation& getTranslation() const { - return m_translation; -} -const Rotation& getRotation() const { - return m_rotation; -} -const Scale& getScale() const { - return m_scale; -} -const Skew& getSkew() const { - return m_skew; -} -Matrix4 calculateTransform() const { - return matrix4_transform_for_components( getTranslation(), getRotation(), getScale(), getSkew() ); -} + void setRotation( const Rotation& value ){ + m_rotation = value; + m_changed(); + } + void setScale( const Scale& value ){ + m_scale = value; + m_changed(); + } + void setSkew( const Skew& value ){ + m_skew = value; + m_changed(); + } + void freezeTransform(){ + if ( !isIdentity() ) { + m_apply(); + setIdentity(); + m_changed(); + } + } + const Translation& getTranslation() const { + return m_translation; + } + const Rotation& getRotation() const { + return m_rotation; + } + const Scale& getScale() const { + return m_scale; + } + const Skew& getSkew() const { + return m_skew; + } + Matrix4 calculateTransform() const { + return matrix4_transform_for_components( getTranslation(), getRotation(), getScale(), getSkew() ); + } private: -bool isIdentity() const { - return m_translation == c_translation_identity - && m_rotation == c_rotation_identity - && m_scale == c_scale_identity - && m_skew == c_skew_identity; -} -void setIdentity(){ - m_translation = c_translation_identity; - m_rotation = c_rotation_identity; - m_scale = c_scale_identity; - m_skew = c_skew_identity; -} + bool isIdentity() const { + return m_translation == c_translation_identity + && m_rotation == c_rotation_identity + && m_scale == c_scale_identity + && m_skew == c_skew_identity; + } + void setIdentity(){ + m_translation = c_translation_identity; + m_rotation = c_rotation_identity; + m_scale = c_scale_identity; + m_skew = c_skew_identity; + } }; class BrushTransformModifier : public Transformable { -Translation m_translation; -Rotation m_rotation; -Scale m_scale; -Skew m_skew; -Callback m_changed; -Callback m_apply; -TransformModifierType m_type; + Translation m_translation; + Rotation m_rotation; + Scale m_scale; + Skew m_skew; + Callback m_changed; + Callback m_apply; + TransformModifierType m_type; public: -bool m_transformFrozen = true; + bool m_transformFrozen = true; -BrushTransformModifier( const Callback& changed, const Callback& apply ) : - m_translation( c_translation_identity ), - m_rotation( c_quaternion_identity ), - m_scale( c_scale_identity ), - m_skew( c_skew_identity ), - m_changed( changed ), - m_apply( apply ), - m_type( TRANSFORM_PRIMITIVE ){ -} -void setType( TransformModifierType type ){ - m_type = type; -} -TransformModifierType getType() const { - return m_type; -} -void setTranslation( const Translation& value ){ - m_translation = value; - m_changed(); -} -void setRotation( const Rotation& value ){ - m_rotation = value; - m_changed(); -} -void setScale( const Scale& value ){ - m_scale = value; - m_changed(); -} -void setSkew( const Skew& value ){ - m_skew = value; - m_changed(); -} -void freezeTransform(){ - m_apply(); - m_transformFrozen = true; -} -const Translation& getTranslation() const { - return m_translation; -} -const Rotation& getRotation() const { - return m_rotation; -} -const Scale& getScale() const { - return m_scale; -} -const Skew& getSkew() const { - return m_skew; -} -Matrix4 calculateTransform() const { - return matrix4_transform_for_components( getTranslation(), getRotation(), getScale(), getSkew() ); -} -bool isIdentity() const { - return m_translation == c_translation_identity - && m_rotation == c_rotation_identity - && m_scale == c_scale_identity - && m_skew == c_skew_identity; -} -void setIdentity(){ - m_translation = c_translation_identity; - m_rotation = c_rotation_identity; - m_scale = c_scale_identity; - m_skew = c_skew_identity; -} + BrushTransformModifier( const Callback& changed, const Callback& apply ) : + m_translation( c_translation_identity ), + m_rotation( c_quaternion_identity ), + m_scale( c_scale_identity ), + m_skew( c_skew_identity ), + m_changed( changed ), + m_apply( apply ), + m_type( TRANSFORM_PRIMITIVE ){ + } + void setType( TransformModifierType type ){ + m_type = type; + } + TransformModifierType getType() const { + return m_type; + } + void setTranslation( const Translation& value ){ + m_translation = value; + m_changed(); + } + void setRotation( const Rotation& value ){ + m_rotation = value; + m_changed(); + } + void setScale( const Scale& value ){ + m_scale = value; + m_changed(); + } + void setSkew( const Skew& value ){ + m_skew = value; + m_changed(); + } + void freezeTransform(){ + m_apply(); + m_transformFrozen = true; + } + const Translation& getTranslation() const { + return m_translation; + } + const Rotation& getRotation() const { + return m_rotation; + } + const Scale& getScale() const { + return m_scale; + } + const Skew& getSkew() const { + return m_skew; + } + Matrix4 calculateTransform() const { + return matrix4_transform_for_components( getTranslation(), getRotation(), getScale(), getSkew() ); + } + bool isIdentity() const { + return m_translation == c_translation_identity + && m_rotation == c_rotation_identity + && m_scale == c_scale_identity + && m_skew == c_skew_identity; + } + void setIdentity(){ + m_translation = c_translation_identity; + m_rotation = c_rotation_identity; + m_scale = c_scale_identity; + m_skew = c_skew_identity; + } }; diff --git a/libs/traverselib.h b/libs/traverselib.h index d8479e35..90b0d9b6 100644 --- a/libs/traverselib.h +++ b/libs/traverselib.h @@ -35,55 +35,67 @@ class TraversableObserverInsertOutputIterator { protected: -scene::Traversable::Observer* m_observer; + scene::Traversable::Observer* m_observer; public: -typedef std::output_iterator_tag iterator_category; -typedef void difference_type; -typedef void value_type; -typedef void pointer; -typedef void reference; + typedef std::output_iterator_tag iterator_category; + typedef void difference_type; + typedef void value_type; + typedef void pointer; + typedef void reference; -TraversableObserverInsertOutputIterator( scene::Traversable::Observer* observer ) - : m_observer( observer ){ -} -TraversableObserverInsertOutputIterator& operator=( const NodeReference& node ){ - m_observer->insert( node ); - return *this; -} -TraversableObserverInsertOutputIterator& operator=( const NodeSmartReference& node ){ - m_observer->insert( node ); - return *this; -} -TraversableObserverInsertOutputIterator& operator*() { return *this; } -TraversableObserverInsertOutputIterator& operator++() { return *this; } -TraversableObserverInsertOutputIterator& operator++( int ) { return *this; } + TraversableObserverInsertOutputIterator( scene::Traversable::Observer* observer ) + : m_observer( observer ){ + } + TraversableObserverInsertOutputIterator& operator=( const NodeReference& node ){ + m_observer->insert( node ); + return *this; + } + TraversableObserverInsertOutputIterator& operator=( const NodeSmartReference& node ){ + m_observer->insert( node ); + return *this; + } + TraversableObserverInsertOutputIterator& operator*() { + return *this; + } + TraversableObserverInsertOutputIterator& operator++() { + return *this; + } + TraversableObserverInsertOutputIterator& operator++( int ) { + return *this; + } }; class TraversableObserverEraseOutputIterator { protected: -scene::Traversable::Observer* m_observer; + scene::Traversable::Observer* m_observer; public: -typedef std::output_iterator_tag iterator_category; -typedef void difference_type; -typedef void value_type; -typedef void pointer; -typedef void reference; + typedef std::output_iterator_tag iterator_category; + typedef void difference_type; + typedef void value_type; + typedef void pointer; + typedef void reference; -TraversableObserverEraseOutputIterator( scene::Traversable::Observer* observer ) - : m_observer( observer ){ -} -TraversableObserverEraseOutputIterator& operator=( const NodeReference& node ){ - m_observer->erase( node ); - return *this; -} -TraversableObserverEraseOutputIterator& operator=( const NodeSmartReference& node ){ - m_observer->erase( node ); - return *this; -} -TraversableObserverEraseOutputIterator& operator*() { return *this; } -TraversableObserverEraseOutputIterator& operator++() { return *this; } -TraversableObserverEraseOutputIterator& operator++( int ) { return *this; } + TraversableObserverEraseOutputIterator( scene::Traversable::Observer* observer ) + : m_observer( observer ){ + } + TraversableObserverEraseOutputIterator& operator=( const NodeReference& node ){ + m_observer->erase( node ); + return *this; + } + TraversableObserverEraseOutputIterator& operator=( const NodeSmartReference& node ){ + m_observer->erase( node ); + return *this; + } + TraversableObserverEraseOutputIterator& operator*() { + return *this; + } + TraversableObserverEraseOutputIterator& operator++() { + return *this; + } + TraversableObserverEraseOutputIterator& operator++( int ) { + return *this; + } }; typedef UnsortedSet UnsortedNodeSet; @@ -102,116 +114,116 @@ inline void nodeset_diff( const UnsortedNodeSet& self, const UnsortedNodeSet& ot /// \brief A sequence of node references which notifies an observer of inserts and deletions, and uses the global undo system to provide undo for modifications. class TraversableNodeSet : public scene::Traversable { -UnsortedNodeSet m_children; -UndoableObject m_undo; -Observer* m_observer; + UnsortedNodeSet m_children; + UndoableObject m_undo; + Observer* m_observer; -void copy( const TraversableNodeSet& other ){ - m_children = other.m_children; -} -void notifyInsertAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->insert( *i ); + void copy( const TraversableNodeSet& other ){ + m_children = other.m_children; + } + void notifyInsertAll(){ + if ( m_observer ) { + for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) + { + m_observer->insert( *i ); + } } } -} -void notifyEraseAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->erase( *i ); + void notifyEraseAll(){ + if ( m_observer ) { + for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) + { + m_observer->erase( *i ); + } } } -} public: -TraversableNodeSet() - : m_undo( *this ), m_observer( 0 ){ -} -TraversableNodeSet( const TraversableNodeSet& other ) - : scene::Traversable( other ), m_undo( *this ), m_observer( 0 ){ - copy( other ); - notifyInsertAll(); -} -~TraversableNodeSet(){ - notifyEraseAll(); -} -TraversableNodeSet& operator=( const TraversableNodeSet& other ){ + TraversableNodeSet() + : m_undo( *this ), m_observer( 0 ){ + } + TraversableNodeSet( const TraversableNodeSet& other ) + : scene::Traversable( other ), m_undo( *this ), m_observer( 0 ){ + copy( other ); + notifyInsertAll(); + } + ~TraversableNodeSet(){ + notifyEraseAll(); + } + TraversableNodeSet& operator=( const TraversableNodeSet& other ){ #if 1 // optimised change-tracking using diff algorithm - if ( m_observer ) { - nodeset_diff( m_children, other.m_children, m_observer ); - } - copy( other ); + if ( m_observer ) { + nodeset_diff( m_children, other.m_children, m_observer ); + } + copy( other ); #else - TraversableNodeSet tmp( other ); - tmp.swap( *this ); + TraversableNodeSet tmp( other ); + tmp.swap( *this ); #endif - return *this; -} -void swap( TraversableNodeSet& other ){ - std::swap( m_children, other.m_children ); - std::swap( m_observer, other.m_observer ); -} + return *this; + } + void swap( TraversableNodeSet& other ){ + std::swap( m_children, other.m_children ); + std::swap( m_observer, other.m_observer ); + } -void attach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == 0, "TraversableNodeSet::attach: observer cannot be attached" ); - m_observer = observer; - notifyInsertAll(); -} -void detach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == observer, "TraversableNodeSet::detach: observer cannot be detached" ); - notifyEraseAll(); - m_observer = 0; -} + void attach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == 0, "TraversableNodeSet::attach: observer cannot be attached" ); + m_observer = observer; + notifyInsertAll(); + } + void detach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == observer, "TraversableNodeSet::detach: observer cannot be detached" ); + notifyEraseAll(); + m_observer = 0; + } /// \brief \copydoc scene::Traversable::insert() -void insert( scene::Node& node ){ - ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableNodeSet::insert: sanity check failed" ); - m_undo.save(); + void insert( scene::Node& node ){ + ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableNodeSet::insert: sanity check failed" ); + m_undo.save(); - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) == m_children.end(), "TraversableNodeSet::insert - element already exists" ); + ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) == m_children.end(), "TraversableNodeSet::insert - element already exists" ); - m_children.insert( NodeSmartReference( node ) ); + m_children.insert( NodeSmartReference( node ) ); - if ( m_observer ) { - m_observer->insert( node ); + if ( m_observer ) { + m_observer->insert( node ); + } } -} /// \brief \copydoc scene::Traversable::erase() -void erase( scene::Node& node ){ - ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableNodeSet::erase: sanity check failed" ); - m_undo.save(); + void erase( scene::Node& node ){ + ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableNodeSet::erase: sanity check failed" ); + m_undo.save(); - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) != m_children.end(), "TraversableNodeSet::erase - failed to find element" ); + ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) != m_children.end(), "TraversableNodeSet::erase - failed to find element" ); - if ( m_observer ) { - m_observer->erase( node ); + if ( m_observer ) { + m_observer->erase( node ); + } + + m_children.erase( NodeSmartReference( node ) ); } - - m_children.erase( NodeSmartReference( node ) ); -} /// \brief \copydoc scene::Traversable::traverse() -void traverse( const Walker& walker ){ - UnsortedNodeSet::iterator i = m_children.begin(); - while ( i != m_children.end() ) - { - // post-increment the iterator - Node_traverseSubgraph( *i++, walker ); - // the Walker can safely remove the current node from - // this container without invalidating the iterator + void traverse( const Walker& walker ){ + UnsortedNodeSet::iterator i = m_children.begin(); + while ( i != m_children.end() ) + { + // post-increment the iterator + Node_traverseSubgraph( *i++, walker ); + // the Walker can safely remove the current node from + // this container without invalidating the iterator + } } -} /// \brief \copydoc scene::Traversable::empty() -bool empty() const { - return m_children.empty(); -} + bool empty() const { + return m_children.empty(); + } -void instanceAttach( MapFile* map ){ - m_undo.instanceAttach( map ); -} -void instanceDetach( MapFile* map ){ - m_undo.instanceDetach( map ); -} + void instanceAttach( MapFile* map ){ + m_undo.instanceAttach( map ); + } + void instanceDetach( MapFile* map ){ + m_undo.instanceDetach( map ); + } }; namespace std @@ -227,125 +239,125 @@ inline void swap( TraversableNodeSet& self, TraversableNodeSet& other ){ class TraversableNode : public scene::Traversable { public: -TraversableNode() : m_node( 0 ), m_observer( 0 ){ -} + TraversableNode() : m_node( 0 ), m_observer( 0 ){ + } // traverse -void attach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == 0, "TraversableNode::attach - cannot attach observer" ); - m_observer = observer; - if ( m_node != 0 ) { - m_observer->insert( *m_node ); + void attach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == 0, "TraversableNode::attach - cannot attach observer" ); + m_observer = observer; + if ( m_node != 0 ) { + m_observer->insert( *m_node ); + } } -} -void detach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == observer, "TraversableNode::detach - cannot detach observer" ); - if ( m_node != 0 ) { - m_observer->erase( *m_node ); + void detach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == observer, "TraversableNode::detach - cannot detach observer" ); + if ( m_node != 0 ) { + m_observer->erase( *m_node ); + } + m_observer = 0; } - m_observer = 0; -} -void insert( scene::Node& node ){ - ASSERT_MESSAGE( m_node == 0, "TraversableNode::insert - element already exists" ); + void insert( scene::Node& node ){ + ASSERT_MESSAGE( m_node == 0, "TraversableNode::insert - element already exists" ); - m_node = &node; - node.IncRef(); + m_node = &node; + node.IncRef(); - if ( m_observer != 0 ) { - m_observer->insert( node ); + if ( m_observer != 0 ) { + m_observer->insert( node ); + } } -} -void erase( scene::Node& node ){ - ASSERT_MESSAGE( m_node == &node, "TraversableNode::erase - failed to find element" ); + void erase( scene::Node& node ){ + ASSERT_MESSAGE( m_node == &node, "TraversableNode::erase - failed to find element" ); - if ( m_observer != 0 ) { - m_observer->erase( node ); + if ( m_observer != 0 ) { + m_observer->erase( node ); + } + + m_node = 0; + node.DecRef(); + } + void traverse( const scene::Traversable::Walker& walker ){ + if ( m_node != 0 ) { + Node_traverseSubgraph( *m_node, walker ); + } + } + bool empty() const { + return m_node != 0; } - m_node = 0; - node.DecRef(); -} -void traverse( const scene::Traversable::Walker& walker ){ - if ( m_node != 0 ) { - Node_traverseSubgraph( *m_node, walker ); + scene::Node& get(){ + return *m_node; } -} -bool empty() const { - return m_node != 0; -} - -scene::Node& get(){ - return *m_node; -} private: -scene::Node* m_node; -Observer* m_observer; + scene::Node* m_node; + Observer* m_observer; }; class TraversableObserverInsert { -scene::Node& node; + scene::Node& node; public: -TraversableObserverInsert( scene::Node& node ) : node( node ){ -} -void operator()( scene::Traversable::Observer& observer ) const { - observer.insert( node ); -} + TraversableObserverInsert( scene::Node& node ) : node( node ){ + } + void operator()( scene::Traversable::Observer& observer ) const { + observer.insert( node ); + } }; class TraversableObserverErase { -scene::Node& node; + scene::Node& node; public: -TraversableObserverErase( scene::Node& node ) : node( node ){ -} -void operator()( scene::Traversable::Observer& observer ) const { - observer.erase( node ); -} + TraversableObserverErase( scene::Node& node ) : node( node ){ + } + void operator()( scene::Traversable::Observer& observer ) const { + observer.erase( node ); + } }; class TraversableObserverPairRelay : public ReferencePair, public scene::Traversable::Observer { public: -void insert( scene::Node& node ){ - forEach( TraversableObserverInsert( node ) ); -} -void erase( scene::Node& node ){ - forEach( TraversableObserverErase( node ) ); -} + void insert( scene::Node& node ){ + forEach( TraversableObserverInsert( node ) ); + } + void erase( scene::Node& node ){ + forEach( TraversableObserverErase( node ) ); + } }; template class ReferenceSet { -typedef UniqueSet Values; -Values m_values; + typedef UniqueSet Values; + Values m_values; public: -void attach( Type& t ){ - m_values.insert( &t ); -} -void detach( Type& t ){ - m_values.erase( &t ); -} -template -void forEach( const Functor& functor ){ - for ( typename Values::iterator i = m_values.begin(); i != m_values.end(); ++i ) - { - functor( *( *i ) ); + void attach( Type& t ){ + m_values.insert( &t ); + } + void detach( Type& t ){ + m_values.erase( &t ); + } + template + void forEach( const Functor& functor ){ + for ( typename Values::iterator i = m_values.begin(); i != m_values.end(); ++i ) + { + functor( *( *i ) ); + } } -} }; class TraversableObserverRelay : public ReferenceSet, public scene::Traversable::Observer { public: -void insert( scene::Node& node ){ - forEach( TraversableObserverInsert( node ) ); -} -void erase( scene::Node& node ){ - forEach( TraversableObserverErase( node ) ); -} + void insert( scene::Node& node ){ + forEach( TraversableObserverInsert( node ) ); + } + void erase( scene::Node& node ){ + forEach( TraversableObserverErase( node ) ); + } }; diff --git a/libs/typesystem.h b/libs/typesystem.h index b789c5c4..fd242c44 100644 --- a/libs/typesystem.h +++ b/libs/typesystem.h @@ -30,25 +30,25 @@ class InitialiserList { -typedef std::list Initialisers; -Initialisers m_initialisers; -mutable bool m_initialised; + typedef std::list Initialisers; + Initialisers m_initialisers; + mutable bool m_initialised; public: -InitialiserList() : m_initialised( false ){ -} -void addInitialiser( const Callback& callback ){ - m_initialisers.push_back( callback ); -} -void initialise() const { - if ( !m_initialised ) { - m_initialised = true; + InitialiserList() : m_initialised( false ){ + } + void addInitialiser( const Callback& callback ){ + m_initialisers.push_back( callback ); + } + void initialise() const { + if ( !m_initialised ) { + m_initialised = true; - for ( Initialisers::const_iterator i = m_initialisers.begin(); i != m_initialisers.end(); ++i ) - { - ( *i )( ); + for ( Initialisers::const_iterator i = m_initialisers.begin(); i != m_initialisers.end(); ++i ) + { + ( *i )( ); + } } } -} }; //--Type System------------------- @@ -62,9 +62,9 @@ typedef SmartStatic StaticTypeSystemInitialiser; class TypeSystemRef : public StaticTypeSystemInitialiser { public: -TypeSystemRef(){ - StaticTypeSystemInitialiser::instance().initialise(); -} + TypeSystemRef(){ + StaticTypeSystemInitialiser::instance().initialise(); + } }; @@ -75,48 +75,48 @@ typedef void*( *TypeCast )( void* ); template class TypeCastTable { -TypeCast m_casts[SIZE]; + TypeCast m_casts[SIZE]; public: -TypeCastTable(){ - std::uninitialized_fill( m_casts, m_casts + SIZE, TypeCast( 0 ) ); -} -void install( TypeId typeId, TypeCast typeCast ){ - m_casts[typeId] = typeCast; -} -void* cast( TypeId typeId, void* p ){ - TypeCast typeCast = m_casts[typeId]; - if ( typeCast != 0 ) { - return typeCast( p ); + TypeCastTable(){ + std::uninitialized_fill( m_casts, m_casts + SIZE, TypeCast( 0 ) ); + } + void install( TypeId typeId, TypeCast typeCast ){ + m_casts[typeId] = typeCast; + } + void* cast( TypeId typeId, void* p ){ + TypeCast typeCast = m_casts[typeId]; + if ( typeCast != 0 ) { + return typeCast( p ); + } + return 0; } - return 0; -} }; template class CastInstaller { public: -static void install( TypeCastTable& table ){ - table.install( Type::getTypeId(), Cast::cast ); -} + static void install( TypeCastTable& table ){ + table.install( Type::getTypeId(), Cast::cast ); + } }; template class IdentityCast { public: -static void* cast( void* p ){ - return p; -} + static void* cast( void* p ){ + return p; + } }; template class StaticCast { public: -static void* cast( void* p ){ - return static_cast( reinterpret_cast( p ) ); -} + static void* cast( void* p ){ + return static_cast( reinterpret_cast( p ) ); + } }; template @@ -128,9 +128,9 @@ template class ContainedCast { public: -static void* cast( void* p ){ - return &reinterpret_cast( p )->get( NullType() ); -} + static void* cast( void* p ){ + return &reinterpret_cast( p )->get( NullType() ); + } }; diff --git a/libs/undolib.h b/libs/undolib.h index 4fc44119..8d7c41e9 100644 --- a/libs/undolib.h +++ b/libs/undolib.h @@ -30,112 +30,112 @@ template class BasicUndoMemento : public UndoMemento { -Copyable m_data; + Copyable m_data; public: -BasicUndoMemento( const Copyable& data ) - : m_data( data ){ -} + BasicUndoMemento( const Copyable& data ) + : m_data( data ){ + } -void release(){ - delete this; -} + void release(){ + delete this; + } -const Copyable& get() const { - return m_data; -} + const Copyable& get() const { + return m_data; + } }; template class ObservedUndoableObject : public Undoable { -typedef Callback1 ImportCallback; + typedef Callback1 ImportCallback; -Copyable& m_object; -ImportCallback m_importCallback; -UndoObserver* m_undoQueue; -MapFile* m_map; + Copyable& m_object; + ImportCallback m_importCallback; + UndoObserver* m_undoQueue; + MapFile* m_map; public: -ObservedUndoableObject( Copyable & object, const ImportCallback &importCallback ) - : m_object( object ), m_importCallback( importCallback ), m_undoQueue( 0 ), m_map( 0 ) -{ -} -~ObservedUndoableObject(){ -} - -MapFile* map(){ - return m_map; -} - -void instanceAttach( MapFile* map ){ - m_map = map; - m_undoQueue = GlobalUndoSystem().observer( this ); -} -void instanceDetach( MapFile* map ){ - m_map = 0; - m_undoQueue = 0; - GlobalUndoSystem().release( this ); -} - -void save(){ - if ( m_map != 0 ) { - m_map->changed(); + ObservedUndoableObject( Copyable & object, const ImportCallback &importCallback ) + : m_object( object ), m_importCallback( importCallback ), m_undoQueue( 0 ), m_map( 0 ) + { } - if ( m_undoQueue != 0 ) { - m_undoQueue->save( this ); + ~ObservedUndoableObject(){ } -} -UndoMemento* exportState() const { - return new BasicUndoMemento( m_object ); -} -void importState( const UndoMemento* state ){ - save(); - m_importCallback( ( static_cast*>( state ) )->get() ); -} + MapFile* map(){ + return m_map; + } + + void instanceAttach( MapFile* map ){ + m_map = map; + m_undoQueue = GlobalUndoSystem().observer( this ); + } + void instanceDetach( MapFile* map ){ + m_map = 0; + m_undoQueue = 0; + GlobalUndoSystem().release( this ); + } + + void save(){ + if ( m_map != 0 ) { + m_map->changed(); + } + if ( m_undoQueue != 0 ) { + m_undoQueue->save( this ); + } + } + + UndoMemento* exportState() const { + return new BasicUndoMemento( m_object ); + } + void importState( const UndoMemento* state ){ + save(); + m_importCallback( ( static_cast*>( state ) )->get() ); + } }; template class UndoableObject : public Undoable { -Copyable& m_object; -UndoObserver* m_undoQueue; -MapFile* m_map; + Copyable& m_object; + UndoObserver* m_undoQueue; + MapFile* m_map; public: -UndoableObject( Copyable& object ) - : m_object( object ), m_undoQueue( 0 ), m_map( 0 ) -{} -~UndoableObject(){ -} - -void instanceAttach( MapFile* map ){ - m_map = map; - m_undoQueue = GlobalUndoSystem().observer( this ); -} -void instanceDetach( MapFile* map ){ - m_map = 0; - m_undoQueue = 0; - GlobalUndoSystem().release( this ); -} - -void save(){ - if ( m_map != 0 ) { - m_map->changed(); + UndoableObject( Copyable& object ) + : m_object( object ), m_undoQueue( 0 ), m_map( 0 ) + {} + ~UndoableObject(){ } - if ( m_undoQueue != 0 ) { - m_undoQueue->save( this ); - } -} -UndoMemento* exportState() const { - return new BasicUndoMemento( m_object ); -} -void importState( const UndoMemento* state ){ - save(); - m_object = ( static_cast*>( state ) )->get(); -} + void instanceAttach( MapFile* map ){ + m_map = map; + m_undoQueue = GlobalUndoSystem().observer( this ); + } + void instanceDetach( MapFile* map ){ + m_map = 0; + m_undoQueue = 0; + GlobalUndoSystem().release( this ); + } + + void save(){ + if ( m_map != 0 ) { + m_map->changed(); + } + if ( m_undoQueue != 0 ) { + m_undoQueue->save( this ); + } + } + + UndoMemento* exportState() const { + return new BasicUndoMemento( m_object ); + } + void importState( const UndoMemento* state ){ + save(); + m_object = ( static_cast*>( state ) )->get(); + } }; #endif diff --git a/libs/uniquenames.h b/libs/uniquenames.h index b9a2f363..6ff544be 100644 --- a/libs/uniquenames.h +++ b/libs/uniquenames.h @@ -30,69 +30,69 @@ #if 1 class Postfix { -unsigned int m_value; + unsigned int m_value; public: -Postfix( const char* postfix ) : m_value( atoi( postfix ) ){ -} -unsigned int number() const { - return m_value; -} -void write( char* buffer ) const { - sprintf( buffer, "%u", m_value ); -} -Postfix& operator++(){ - ++m_value; - return *this; -} -bool operator<( const Postfix& other ) const { - return m_value < other.m_value; -} -bool operator==( const Postfix& other ) const { - return m_value == other.m_value; -} -bool operator!=( const Postfix& other ) const { - return !operator==( other ); -} + Postfix( const char* postfix ) : m_value( atoi( postfix ) ){ + } + unsigned int number() const { + return m_value; + } + void write( char* buffer ) const { + sprintf( buffer, "%u", m_value ); + } + Postfix& operator++(){ + ++m_value; + return *this; + } + bool operator<( const Postfix& other ) const { + return m_value < other.m_value; + } + bool operator==( const Postfix& other ) const { + return m_value == other.m_value; + } + bool operator!=( const Postfix& other ) const { + return !operator==( other ); + } }; #else class Postfix { -std::pair m_value; + std::pair m_value; public: -Postfix( unsigned int number, unsigned int leading_zeros ) - : m_value( leading_zeros, number ){ -} -Postfix( const char* postfix ) - : m_value( number_count_leading_zeros( postfix ), atoi( postfix ) ){ -} -unsigned int number() const { - return m_value.second; -} -unsigned int leading_zeros() const { - return m_value.first; -} -void write( char* buffer ){ - for ( unsigned int count = 0; count < m_value.first; ++count, ++buffer ) - *buffer = '0'; - sprintf( buffer, "%u", m_value.second ); -} -Postfix& operator++(){ - ++m_value.second; - if ( m_value.first != 0 && m_value.second % 10 == 0 ) { - --m_value.first; + Postfix( unsigned int number, unsigned int leading_zeros ) + : m_value( leading_zeros, number ){ + } + Postfix( const char* postfix ) + : m_value( number_count_leading_zeros( postfix ), atoi( postfix ) ){ + } + unsigned int number() const { + return m_value.second; + } + unsigned int leading_zeros() const { + return m_value.first; + } + void write( char* buffer ){ + for ( unsigned int count = 0; count < m_value.first; ++count, ++buffer ) + *buffer = '0'; + sprintf( buffer, "%u", m_value.second ); + } + Postfix& operator++(){ + ++m_value.second; + if ( m_value.first != 0 && m_value.second % 10 == 0 ) { + --m_value.first; + } + return *this; + } + bool operator<( const Postfix& other ) const { + return m_value < other.m_value; + } + bool operator==( const Postfix& other ) const { + return m_value == other.m_value; + } + bool operator!=( const Postfix& other ) const { + return !operator==( other ); } - return *this; -} -bool operator<( const Postfix& other ) const { - return m_value < other.m_value; -} -bool operator==( const Postfix& other ) const { - return m_value == other.m_value; -} -bool operator!=( const Postfix& other ) const { - return !operator==( other ); -} }; #endif @@ -121,129 +121,129 @@ inline name_t name_read( const char* name ){ class PostFixes { public: -typedef std::map postfixes_t; -postfixes_t m_postfixes; + typedef std::map postfixes_t; + postfixes_t m_postfixes; private: -Postfix find_first_empty() const { - Postfix postfix( "1" ); - for ( postfixes_t::const_iterator i = m_postfixes.find( postfix ); i != m_postfixes.end(); ++i, ++postfix ) - { - if ( ( *i ).first != postfix ) { - break; + Postfix find_first_empty() const { + Postfix postfix( "1" ); + for ( postfixes_t::const_iterator i = m_postfixes.find( postfix ); i != m_postfixes.end(); ++i, ++postfix ) + { + if ( ( *i ).first != postfix ) { + break; + } } - } - return postfix; -} - -public: -Postfix make_unique( Postfix postfix ) const { - postfixes_t::const_iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { return postfix; } - else - { - return find_first_empty(); - } -} -void insert( Postfix postfix ){ - postfixes_t::iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { - m_postfixes.insert( postfixes_t::value_type( postfix, 1 ) ); - } - else - { - ++( *i ).second; - } -} - -void erase( Postfix postfix ){ - postfixes_t::iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { - // error - } - else - { - if ( --( *i ).second == 0 ) { - m_postfixes.erase( i ); +public: + Postfix make_unique( Postfix postfix ) const { + postfixes_t::const_iterator i = m_postfixes.find( postfix ); + if ( i == m_postfixes.end() ) { + return postfix; + } + else + { + return find_first_empty(); } } -} -bool empty() const { - return m_postfixes.empty(); -} + void insert( Postfix postfix ){ + postfixes_t::iterator i = m_postfixes.find( postfix ); + if ( i == m_postfixes.end() ) { + m_postfixes.insert( postfixes_t::value_type( postfix, 1 ) ); + } + else + { + ++( *i ).second; + } + } + + void erase( Postfix postfix ){ + postfixes_t::iterator i = m_postfixes.find( postfix ); + if ( i == m_postfixes.end() ) { + // error + } + else + { + if ( --( *i ).second == 0 ) { + m_postfixes.erase( i ); + } + } + } + + bool empty() const { + return m_postfixes.empty(); + } }; class UniqueNames { -typedef std::map names_t; -names_t m_names; + typedef std::map names_t; + names_t m_names; public: -name_t make_unique( const name_t& name ) const { + name_t make_unique( const name_t& name ) const { #if 0 //debug - char buf[80]; - name_t r( "","" ); - name_write( buf, name ); - globalErrorStream() << "find unique name for " << buf << "\n"; - globalErrorStream() << "> currently registered names:\n"; - for ( names_t::const_iterator i = m_names.begin(); i != m_names.end(); ++i ) - { - globalErrorStream() << ">> " << i->first.c_str() << ": "; - for ( PostFixes::postfixes_t::const_iterator j = i->second.m_postfixes.begin(); j != i->second.m_postfixes.end(); ++j ) + char buf[80]; + name_t r( "","" ); + name_write( buf, name ); + globalErrorStream() << "find unique name for " << buf << "\n"; + globalErrorStream() << "> currently registered names:\n"; + for ( names_t::const_iterator i = m_names.begin(); i != m_names.end(); ++i ) { - j->first.write( buf ); - globalErrorStream() << " '" << buf << "'"; + globalErrorStream() << ">> " << i->first.c_str() << ": "; + for ( PostFixes::postfixes_t::const_iterator j = i->second.m_postfixes.begin(); j != i->second.m_postfixes.end(); ++j ) + { + j->first.write( buf ); + globalErrorStream() << " '" << buf << "'"; + } + globalErrorStream() << "\n"; } - globalErrorStream() << "\n"; - } - names_t::const_iterator i = m_names.find( name.first ); - if ( i == m_names.end() ) { - r = name; - } - else - { - r = name_t( name.first, ( *i ).second.make_unique( name.second ) ); - } - name_write( buf, r ); - globalErrorStream() << "> unique name is " << buf << "\n"; - return r; + names_t::const_iterator i = m_names.find( name.first ); + if ( i == m_names.end() ) { + r = name; + } + else + { + r = name_t( name.first, ( *i ).second.make_unique( name.second ) ); + } + name_write( buf, r ); + globalErrorStream() << "> unique name is " << buf << "\n"; + return r; #else - names_t::const_iterator i = m_names.find( name.first ); - if ( i == m_names.end() ) { - return name; - } - else - { - return name_t( name.first, ( *i ).second.make_unique( name.second ) ); - } + names_t::const_iterator i = m_names.find( name.first ); + if ( i == m_names.end() ) { + return name; + } + else + { + return name_t( name.first, ( *i ).second.make_unique( name.second ) ); + } #endif -} - -void insert( const name_t& name ){ - m_names[name.first].insert( name.second ); -} - -void erase( const name_t& name ){ - names_t::iterator i = m_names.find( name.first ); - if ( i == m_names.end() ) { - ASSERT_MESSAGE( true, "erase: name not found" ); } - else - { - ( *i ).second.erase( name.second ); - if ( ( *i ).second.empty() ) { - m_names.erase( i ); + + void insert( const name_t& name ){ + m_names[name.first].insert( name.second ); + } + + void erase( const name_t& name ){ + names_t::iterator i = m_names.find( name.first ); + if ( i == m_names.end() ) { + ASSERT_MESSAGE( true, "erase: name not found" ); + } + else + { + ( *i ).second.erase( name.second ); + if ( ( *i ).second.empty() ) { + m_names.erase( i ); + } } } -} -bool empty() const { - return m_names.empty(); -} + bool empty() const { + return m_names.empty(); + } }; @@ -255,74 +255,74 @@ bool empty() const { class TestUniqueName { -void name_check_equal( const name_t& name, const char* string, unsigned int postfix ){ - ASSERT_MESSAGE( strcmp( name.first.c_str(), string ) == 0 - && name.second.number() == postfix, - "test failed!" ); -} -void test_refcount(){ - Names names; - - names.insert( name_t( "func_bleh_", "100" ) ); - names.insert( name_t( "func_bleh_", "100" ) ); - names.insert( name_t( "func_bleh_", "100" ) ); - - - names.erase( name_t( "func_bleh_", "100" ) ); - names.erase( name_t( "func_bleh_", "100" ) ); - names.erase( name_t( "func_bleh_", "100" ) ); - - ASSERT_MESSAGE( names.empty(), "test failed!" ); -} - -void test_make_unique(){ - Names names; - - { - name_t name( names.make_unique( name_t( "func_bleh_", "01" ) ) ); - name_check_equal( name, "func_bleh_", 1 ); - names.insert( name ); + void name_check_equal( const name_t& name, const char* string, unsigned int postfix ){ + ASSERT_MESSAGE( strcmp( name.first.c_str(), string ) == 0 + && name.second.number() == postfix, + "test failed!" ); } - { - name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); - name_check_equal( name, "func_bleh_", 4 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); - name_check_equal( name, "func_bleh_", 2 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "1" ) ) ); - name_check_equal( name, "func_bleh_", 3 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "2" ) ) ); - name_check_equal( name, "func_bleh_", 5 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "3" ) ) ); - name_check_equal( name, "func_bleh_", 6 ); - names.insert( name ); + void test_refcount(){ + Names names; + + names.insert( name_t( "func_bleh_", "100" ) ); + names.insert( name_t( "func_bleh_", "100" ) ); + names.insert( name_t( "func_bleh_", "100" ) ); + + + names.erase( name_t( "func_bleh_", "100" ) ); + names.erase( name_t( "func_bleh_", "100" ) ); + names.erase( name_t( "func_bleh_", "100" ) ); + + ASSERT_MESSAGE( names.empty(), "test failed!" ); } - names.erase( name_t( "func_bleh_", "1" ) ); - names.erase( name_t( "func_bleh_", "2" ) ); - names.erase( name_t( "func_bleh_", "3" ) ); - names.erase( name_t( "func_bleh_", "4" ) ); - names.erase( name_t( "func_bleh_", "5" ) ); - names.erase( name_t( "func_bleh_", "6" ) ); + void test_make_unique(){ + Names names; - ASSERT_MESSAGE( names.empty(), "test failed!" ); -} + { + name_t name( names.make_unique( name_t( "func_bleh_", "01" ) ) ); + name_check_equal( name, "func_bleh_", 1 ); + names.insert( name ); + } + { + name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); + name_check_equal( name, "func_bleh_", 4 ); + names.insert( name ); + } + { + name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); + name_check_equal( name, "func_bleh_", 2 ); + names.insert( name ); + } + { + name_t name( names.make_unique( name_t( "func_bleh_", "1" ) ) ); + name_check_equal( name, "func_bleh_", 3 ); + names.insert( name ); + } + { + name_t name( names.make_unique( name_t( "func_bleh_", "2" ) ) ); + name_check_equal( name, "func_bleh_", 5 ); + names.insert( name ); + } + { + name_t name( names.make_unique( name_t( "func_bleh_", "3" ) ) ); + name_check_equal( name, "func_bleh_", 6 ); + names.insert( name ); + } + + names.erase( name_t( "func_bleh_", "1" ) ); + names.erase( name_t( "func_bleh_", "2" ) ); + names.erase( name_t( "func_bleh_", "3" ) ); + names.erase( name_t( "func_bleh_", "4" ) ); + names.erase( name_t( "func_bleh_", "5" ) ); + names.erase( name_t( "func_bleh_", "6" ) ); + + ASSERT_MESSAGE( names.empty(), "test failed!" ); + } public: -TestUniqueName(){ - test_refcount(); - test_make_unique(); -} + TestUniqueName(){ + test_refcount(); + test_make_unique(); + } }; const TestUniqueName g_testuniquename; diff --git a/libs/versionlib.h b/libs/versionlib.h index 75704cf1..e44961f0 100644 --- a/libs/versionlib.h +++ b/libs/versionlib.h @@ -29,8 +29,8 @@ class Version { public: -int major; -int minor; + int major; + int minor; }; inline bool operator<( const Version& version, const Version& other ){ @@ -45,7 +45,7 @@ TextOutputStreamType& ostream_write( TextOutputStreamType& outputStream, const V /// \brief Returns true if \p version (code) is compatible with \p other (data). inline bool version_compatible( const Version& version, const Version& other ){ return version.major == other.major // different major-versions are always incompatible - && !( version.minor < other.minor ); // data minor-version is incompatible if greater than code minor-version + && !( version.minor < other.minor ); // data minor-version is incompatible if greater than code minor-version } inline int string_range_parse_unsigned_decimal_integer( const char* first, const char* last ){ diff --git a/libs/xml/ixml.h b/libs/xml/ixml.h index 7b86020f..59f8e17a 100644 --- a/libs/xml/ixml.h +++ b/libs/xml/ixml.h @@ -28,32 +28,32 @@ class XMLAttrVisitor { public: -virtual void visit( const char* name, const char* value ) = 0; + virtual void visit( const char* name, const char* value ) = 0; }; class XMLElement { public: -virtual const char* name() const = 0; -virtual const char* attribute( const char* name ) const = 0; -virtual void forEachAttribute( XMLAttrVisitor& visitor ) const = 0; + virtual const char* name() const = 0; + virtual const char* attribute( const char* name ) const = 0; + virtual void forEachAttribute( XMLAttrVisitor& visitor ) const = 0; }; class XMLImporter : public TextOutputStream { public: -STRING_CONSTANT( Name, "XMLImporter" ); + STRING_CONSTANT( Name, "XMLImporter" ); -virtual void pushElement( const XMLElement& element ) = 0; -virtual void popElement( const char* name ) = 0; + virtual void pushElement( const XMLElement& element ) = 0; + virtual void popElement( const char* name ) = 0; }; class XMLExporter { public: -STRING_CONSTANT( Name, "XMLExporter" ); + STRING_CONSTANT( Name, "XMLExporter" ); -virtual void exportXML( XMLImporter& importer ) = 0; + virtual void exportXML( XMLImporter& importer ) = 0; }; diff --git a/libs/xml/xmlelement.h b/libs/xml/xmlelement.h index 5bedf554..8ca7d2da 100644 --- a/libs/xml/xmlelement.h +++ b/libs/xml/xmlelement.h @@ -31,69 +31,69 @@ /// copied and must stay valid for the lifetime of the instance. class StaticElement : public XMLElement { -typedef std::map attrs_t; + typedef std::map attrs_t; public: -StaticElement( const char* name ) - : m_name( name ){ -} -void insertAttribute( const char* name, const char* value ){ - m_attrs.insert( attrs_t::value_type( name, value ) ); -} -const char* name() const { - return m_name; -} -const char* attribute( const char* name ) const { - attrs_t::const_iterator i = m_attrs.find( name ); - if ( i != m_attrs.end() ) { - return i->second; + StaticElement( const char* name ) + : m_name( name ){ } - else{ - return ""; + void insertAttribute( const char* name, const char* value ){ + m_attrs.insert( attrs_t::value_type( name, value ) ); } -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) - { - visitor.visit( i->first, i->second ); + const char* name() const { + return m_name; + } + const char* attribute( const char* name ) const { + attrs_t::const_iterator i = m_attrs.find( name ); + if ( i != m_attrs.end() ) { + return i->second; + } + else{ + return ""; + } + } + void forEachAttribute( XMLAttrVisitor& visitor ) const { + for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) + { + visitor.visit( i->first, i->second ); + } } -} private: -const char* m_name; -attrs_t m_attrs; + const char* m_name; + attrs_t m_attrs; }; ///\brief All string pointers passed to an instance of this class are copied. class DynamicElement : public XMLElement { -typedef std::map attrs_t; + typedef std::map attrs_t; public: -DynamicElement( const char* name ) - : m_name( name ){ -} -void insertAttribute( const char* name, const char* value ){ - m_attrs.insert( attrs_t::value_type( name, value ) ); -} -const char* name() const { - return m_name.c_str(); -} -const char* attribute( const char* name ) const { - attrs_t::const_iterator i = m_attrs.find( name ); - if ( i != m_attrs.end() ) { - return i->second.c_str(); + DynamicElement( const char* name ) + : m_name( name ){ } - else{ - return ""; + void insertAttribute( const char* name, const char* value ){ + m_attrs.insert( attrs_t::value_type( name, value ) ); } -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) - { - visitor.visit( i->first.c_str(), i->second.c_str() ); + const char* name() const { + return m_name.c_str(); + } + const char* attribute( const char* name ) const { + attrs_t::const_iterator i = m_attrs.find( name ); + if ( i != m_attrs.end() ) { + return i->second.c_str(); + } + else{ + return ""; + } + } + void forEachAttribute( XMLAttrVisitor& visitor ) const { + for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) + { + visitor.visit( i->first.c_str(), i->second.c_str() ); + } } -} private: -CopiedString m_name; -attrs_t m_attrs; + CopiedString m_name; + attrs_t m_attrs; }; #endif diff --git a/libs/xml/xmlparser.h b/libs/xml/xmlparser.h index c30d0a26..185c26cd 100644 --- a/libs/xml/xmlparser.h +++ b/libs/xml/xmlparser.h @@ -33,34 +33,34 @@ class TextInputStream; class SAXElement : public XMLElement { public: -SAXElement( const char* name, const char** atts ) - : m_name( name ), m_atts( atts ){ -} -const char* name() const { - return m_name; -} -const char* attribute( const char* name ) const { - if ( m_atts != 0 ) { - for ( const char** att = m_atts; *att != 0; att += 2 ) - { - if ( strcmp( *att, name ) == 0 ) { - return *( ++att ); + SAXElement( const char* name, const char** atts ) + : m_name( name ), m_atts( atts ){ + } + const char* name() const { + return m_name; + } + const char* attribute( const char* name ) const { + if ( m_atts != 0 ) { + for ( const char** att = m_atts; *att != 0; att += 2 ) + { + if ( strcmp( *att, name ) == 0 ) { + return *( ++att ); + } + } + } + return ""; + } + void forEachAttribute( XMLAttrVisitor& visitor ) const { + if ( m_atts != 0 ) { + for ( const char** att = m_atts; *att != 0; att += 2 ) + { + visitor.visit( *att, *( att + 1 ) ); } } } - return ""; -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - if ( m_atts != 0 ) { - for ( const char** att = m_atts; *att != 0; att += 2 ) - { - visitor.visit( *att, *( att + 1 ) ); - } - } -} private: -const char* m_name; -const char** m_atts; + const char* m_name; + const char** m_atts; }; #include @@ -68,25 +68,25 @@ const char** m_atts; class FormattedVA { public: -const char* m_format; -va_list& m_arguments; -FormattedVA( const char* format, va_list& m_arguments ) - : m_format( format ), m_arguments( m_arguments ){ -} + const char* m_format; + va_list& m_arguments; + FormattedVA( const char* format, va_list& m_arguments ) + : m_format( format ), m_arguments( m_arguments ){ + } }; class Formatted { public: -const char* m_format; -mutable va_list m_arguments; -Formatted( const char* format, ... ) - : m_format( format ){ - va_start( m_arguments, format ); -} -~Formatted(){ - va_end( m_arguments ); -} + const char* m_format; + mutable va_list m_arguments; + Formatted( const char* format, ... ) + : m_format( format ){ + va_start( m_arguments, format ); + } + ~Formatted(){ + va_end( m_arguments ); + } }; #ifdef _MSC_VER @@ -111,107 +111,107 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class XMLSAXImporter { -XMLImporter& m_importer; -xmlSAXHandler m_sax; + XMLImporter& m_importer; + xmlSAXHandler m_sax; -static void startElement( void *user_data, const xmlChar *name, const xmlChar **atts ){ - SAXElement element( reinterpret_cast( name ), reinterpret_cast( atts ) ); - reinterpret_cast( user_data )->m_importer.pushElement( element ); -} -static void endElement( void *user_data, const xmlChar *name ){ - reinterpret_cast( user_data )->m_importer.popElement( reinterpret_cast( name ) ); -} -static void characters( void *user_data, const xmlChar *ch, int len ){ - reinterpret_cast( user_data )->m_importer - << StringRange( reinterpret_cast( ch ), reinterpret_cast( ch + len ) ); -} + static void startElement( void *user_data, const xmlChar *name, const xmlChar **atts ){ + SAXElement element( reinterpret_cast( name ), reinterpret_cast( atts ) ); + reinterpret_cast( user_data )->m_importer.pushElement( element ); + } + static void endElement( void *user_data, const xmlChar *name ){ + reinterpret_cast( user_data )->m_importer.popElement( reinterpret_cast( name ) ); + } + static void characters( void *user_data, const xmlChar *ch, int len ){ + reinterpret_cast( user_data )->m_importer + << StringRange( reinterpret_cast( ch ), reinterpret_cast( ch + len ) ); + } -static void warning( void *user_data, const char *msg, ... ){ - va_list args; - va_start( args, msg ); - globalWarningStream() << "XML WARNING: " << FormattedVA( msg, args ); - va_end( args ); -} -static void error( void *user_data, const char *msg, ... ){ - va_list args; - va_start( args, msg ); - globalErrorStream() << "XML ERROR: " << FormattedVA( msg, args ); - va_end( args ); -} + static void warning( void *user_data, const char *msg, ... ){ + va_list args; + va_start( args, msg ); + globalWarningStream() << "XML WARNING: " << FormattedVA( msg, args ); + va_end( args ); + } + static void error( void *user_data, const char *msg, ... ){ + va_list args; + va_start( args, msg ); + globalErrorStream() << "XML ERROR: " << FormattedVA( msg, args ); + va_end( args ); + } public: -XMLSAXImporter( XMLImporter& importer ) : m_importer( importer ){ - m_sax.internalSubset = 0; - m_sax.isStandalone = 0; - m_sax.hasInternalSubset = 0; - m_sax.hasExternalSubset = 0; - m_sax.resolveEntity = 0; - m_sax.getEntity = 0; - m_sax.entityDecl = 0; - m_sax.notationDecl = 0; - m_sax.attributeDecl = 0; - m_sax.elementDecl = 0; - m_sax.unparsedEntityDecl = 0; - m_sax.setDocumentLocator = 0; - m_sax.startDocument = 0; - m_sax.endDocument = 0; - m_sax.startElement = startElement; - m_sax.endElement = endElement; - m_sax.reference = 0; - m_sax.characters = characters; - m_sax.ignorableWhitespace = 0; - m_sax.processingInstruction = 0; - m_sax.comment = 0; - m_sax.warning = warning; - m_sax.error = error; - m_sax.fatalError = 0; - m_sax.getParameterEntity = 0; - m_sax.cdataBlock = 0; - m_sax.externalSubset = 0; - m_sax.initialized = 1; -} + XMLSAXImporter( XMLImporter& importer ) : m_importer( importer ){ + m_sax.internalSubset = 0; + m_sax.isStandalone = 0; + m_sax.hasInternalSubset = 0; + m_sax.hasExternalSubset = 0; + m_sax.resolveEntity = 0; + m_sax.getEntity = 0; + m_sax.entityDecl = 0; + m_sax.notationDecl = 0; + m_sax.attributeDecl = 0; + m_sax.elementDecl = 0; + m_sax.unparsedEntityDecl = 0; + m_sax.setDocumentLocator = 0; + m_sax.startDocument = 0; + m_sax.endDocument = 0; + m_sax.startElement = startElement; + m_sax.endElement = endElement; + m_sax.reference = 0; + m_sax.characters = characters; + m_sax.ignorableWhitespace = 0; + m_sax.processingInstruction = 0; + m_sax.comment = 0; + m_sax.warning = warning; + m_sax.error = error; + m_sax.fatalError = 0; + m_sax.getParameterEntity = 0; + m_sax.cdataBlock = 0; + m_sax.externalSubset = 0; + m_sax.initialized = 1; + } -xmlSAXHandler* callbacks(){ - return &m_sax; -} -void* context(){ - return this; -} + xmlSAXHandler* callbacks(){ + return &m_sax; + } + void* context(){ + return this; + } }; class XMLStreamParser : public XMLExporter { -enum unnamed0 { BUFSIZE = 1024 }; + enum unnamed0 { BUFSIZE = 1024 }; public: -XMLStreamParser( TextInputStream& istream ) - : m_istream( istream ){ -} -virtual void exportXML( XMLImporter& importer ){ - //bool wellFormed = false; - - char chars[BUFSIZE]; - std::size_t res = m_istream.read( chars, 4 ); - if ( res > 0 ) { - XMLSAXImporter sax( importer ); - - xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt( sax.callbacks(), sax.context(), chars, static_cast( res ), 0 ); - ctxt->replaceEntities = 1; - - while ( ( res = m_istream.read( chars, BUFSIZE ) ) > 0 ) - { - xmlParseChunk( ctxt, chars, static_cast( res ), 0 ); - } - xmlParseChunk( ctxt, chars, 0, 1 ); - - //wellFormed = ( ctxt->wellFormed == 1 ); - - xmlFreeParserCtxt( ctxt ); + XMLStreamParser( TextInputStream& istream ) + : m_istream( istream ){ } + virtual void exportXML( XMLImporter& importer ){ + //bool wellFormed = false; - //return wellFormed; -} + char chars[BUFSIZE]; + std::size_t res = m_istream.read( chars, 4 ); + if ( res > 0 ) { + XMLSAXImporter sax( importer ); + + xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt( sax.callbacks(), sax.context(), chars, static_cast( res ), 0 ); + ctxt->replaceEntities = 1; + + while ( ( res = m_istream.read( chars, BUFSIZE ) ) > 0 ) + { + xmlParseChunk( ctxt, chars, static_cast( res ), 0 ); + } + xmlParseChunk( ctxt, chars, 0, 1 ); + + //wellFormed = ( ctxt->wellFormed == 1 ); + + xmlFreeParserCtxt( ctxt ); + } + + //return wellFormed; + } private: -TextInputStream& m_istream; + TextInputStream& m_istream; }; diff --git a/libs/xml/xmltextags.h b/libs/xml/xmltextags.h index 5b19a761..4e8555cf 100644 --- a/libs/xml/xmltextags.h +++ b/libs/xml/xmltextags.h @@ -52,52 +52,52 @@ enum TextureType class XmlTagBuilder { private: -CopiedString m_savefilename; -xmlDocPtr doc; -xmlXPathContextPtr context; + CopiedString m_savefilename; + xmlDocPtr doc; + xmlXPathContextPtr context; -xmlXPathObjectPtr XpathEval( const char* queryString ){ - const xmlChar* expression = (const xmlChar*)queryString; - xmlXPathObjectPtr result = xmlXPathEvalExpression( expression, context ); - return result; -}; - -char* GetTagsXpathExpression( char* buffer, const char* shader, NodeTagType nodeTagType ){ - strcpy( buffer, "/root/*/*[@path='" ); - strcat( buffer, shader ); - - switch ( nodeTagType ) - { - case TAG: - strcat( buffer, "']/tag" ); - break; - case EMPTY: - strcat( buffer, "']" ); + xmlXPathObjectPtr XpathEval( const char* queryString ){ + const xmlChar* expression = (const xmlChar*)queryString; + xmlXPathObjectPtr result = xmlXPathEvalExpression( expression, context ); + return result; }; - return buffer; -} + char* GetTagsXpathExpression( char* buffer, const char* shader, NodeTagType nodeTagType ){ + strcpy( buffer, "/root/*/*[@path='" ); + strcat( buffer, shader ); + + switch ( nodeTagType ) + { + case TAG: + strcat( buffer, "']/tag" ); + break; + case EMPTY: + strcat( buffer, "']" ); + }; + + return buffer; + } public: -XmlTagBuilder(); -~XmlTagBuilder(); + XmlTagBuilder(); + ~XmlTagBuilder(); -bool CreateXmlDocument(); -bool OpenXmlDoc( const char* file, const char* savefile = 0 ); -bool SaveXmlDoc( const char* file ); -bool SaveXmlDoc( void ); -bool AddShaderNode( const char* shader, TextureType textureType, NodeShaderType nodeShaderType ); -bool DeleteShaderNode( const char* shader ); -bool CheckShaderTag( const char* shader ); -bool CheckShaderTag( const char* shader, const char* content ); -bool AddShaderTag( const char* shader, const char* content, NodeTagType nodeTagType ); -bool DeleteTag( const char* tag ); -int RenameShaderTag( const char* oldtag, CopiedString newtag ); -bool DeleteShaderTag( const char* shader, const char* tag ); -void GetShaderTags( const char* shader, std::vector& tags ); -void GetUntagged( std::set& shaders ); -void GetAllTags( std::set& tags ); -void TagSearch( const char* expression, std::set& paths ); + bool CreateXmlDocument(); + bool OpenXmlDoc( const char* file, const char* savefile = 0 ); + bool SaveXmlDoc( const char* file ); + bool SaveXmlDoc( void ); + bool AddShaderNode( const char* shader, TextureType textureType, NodeShaderType nodeShaderType ); + bool DeleteShaderNode( const char* shader ); + bool CheckShaderTag( const char* shader ); + bool CheckShaderTag( const char* shader, const char* content ); + bool AddShaderTag( const char* shader, const char* content, NodeTagType nodeTagType ); + bool DeleteTag( const char* tag ); + int RenameShaderTag( const char* oldtag, CopiedString newtag ); + bool DeleteShaderTag( const char* shader, const char* tag ); + void GetShaderTags( const char* shader, std::vector& tags ); + void GetUntagged( std::set& shaders ); + void GetAllTags( std::set& tags ); + void TagSearch( const char* expression, std::set& paths ); }; #endif diff --git a/libs/xml/xmlwriter.h b/libs/xml/xmlwriter.h index f54662f7..be660236 100644 --- a/libs/xml/xmlwriter.h +++ b/libs/xml/xmlwriter.h @@ -28,57 +28,57 @@ class XMLEntityOutputStream { -SingleCharacterOutputStream m_ostream; + SingleCharacterOutputStream m_ostream; public: -XMLEntityOutputStream( TextOutputStream& ostream ) - : m_ostream( ostream ){ -} -void write( const char c ){ - m_ostream.write( c ); -} -void writeEscaped( const char c ){ - switch ( c ) - { - case '<': - write( '&' ); - write( 'l' ); - write( 't' ); - write( ';' ); - break; - case '>': - write( '&' ); - write( 'g' ); - write( 't' ); - write( ';' ); - break; - case '"': - write( '&' ); - write( 'q' ); - write( 'u' ); - write( 'o' ); - write( 't' ); - write( ';' ); - break; - case '&': - write( '&' ); - write( 'a' ); - write( 'm' ); - write( 'p' ); - write( ';' ); - break; - default: - write( c ); - break; + XMLEntityOutputStream( TextOutputStream& ostream ) + : m_ostream( ostream ){ } -} -std::size_t write( const char* buffer, std::size_t length ){ - const char*const end = buffer + length; - for ( const char* p = buffer; p != end; ++p ) - { - writeEscaped( *p ); + void write( const char c ){ + m_ostream.write( c ); + } + void writeEscaped( const char c ){ + switch ( c ) + { + case '<': + write( '&' ); + write( 'l' ); + write( 't' ); + write( ';' ); + break; + case '>': + write( '&' ); + write( 'g' ); + write( 't' ); + write( ';' ); + break; + case '"': + write( '&' ); + write( 'q' ); + write( 'u' ); + write( 'o' ); + write( 't' ); + write( ';' ); + break; + case '&': + write( '&' ); + write( 'a' ); + write( 'm' ); + write( 'p' ); + write( ';' ); + break; + default: + write( c ); + break; + } + } + std::size_t write( const char* buffer, std::size_t length ){ + const char*const end = buffer + length; + for ( const char* p = buffer; p != end; ++p ) + { + writeEscaped( *p ); + } + return length; } - return length; -} }; template @@ -89,89 +89,89 @@ inline XMLEntityOutputStream& operator<<( XMLEntityOutputStream& ostream, const class XMLStreamWriter : public XMLImporter, public XMLAttrVisitor { -class state_t -{ -public: -enum EState -{ - eStartElement, - eContent, -}; -state_t() - : m_state( eStartElement ) -{} -EState m_state; -}; - -XMLEntityOutputStream m_ostream; -std::vector m_elements; - -void write_cdata( const char* buffer, std::size_t length ){ - m_ostream << StringRange( buffer, buffer + length ); -} -void write_string( const char* string ){ - m_ostream << string; -} -void write_quoted_string( const char* string ){ - m_ostream.write( '"' ); - m_ostream << string; - m_ostream.write( '"' ); -} -public: -XMLStreamWriter( TextOutputStream& ostream ) - : m_ostream( ostream ){ - m_elements.push_back( state_t() ); - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '<' ); - m_ostream.write( '?' ); - write_string( "xml" ); - visit( "version", "1.0" ); - m_ostream.write( '?' ); - m_ostream.write( '>' ); -} - -void pushElement( const XMLElement& element ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '>' ); - } - - m_elements.push_back( state_t() ); - - m_ostream.write( '<' ); - write_string( element.name() ); - element.forEachAttribute( *this ); -} -void popElement( const char* name ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_ostream.write( '/' ); - m_ostream.write( '>' ); - m_elements.pop_back(); - } - else + class state_t { - m_ostream.write( '<' ); - m_ostream.write( '/' ); - write_string( name ); - m_ostream.write( '>' ); - m_elements.pop_back(); - } -} -std::size_t write( const char* data, std::size_t length ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '>' ); - } - write_cdata( data, length ); - return length; -} + public: + enum EState + { + eStartElement, + eContent, + }; + state_t() + : m_state( eStartElement ) + {} + EState m_state; + }; -void visit( const char* name, const char* value ){ - m_ostream.write( ' ' ); - write_string( name ); - m_ostream.write( '=' ); - write_quoted_string( value ); -} + XMLEntityOutputStream m_ostream; + std::vector m_elements; + + void write_cdata( const char* buffer, std::size_t length ){ + m_ostream << StringRange( buffer, buffer + length ); + } + void write_string( const char* string ){ + m_ostream << string; + } + void write_quoted_string( const char* string ){ + m_ostream.write( '"' ); + m_ostream << string; + m_ostream.write( '"' ); + } +public: + XMLStreamWriter( TextOutputStream& ostream ) + : m_ostream( ostream ){ + m_elements.push_back( state_t() ); + m_elements.back().m_state = state_t::eContent; + m_ostream.write( '<' ); + m_ostream.write( '?' ); + write_string( "xml" ); + visit( "version", "1.0" ); + m_ostream.write( '?' ); + m_ostream.write( '>' ); + } + + void pushElement( const XMLElement& element ){ + if ( m_elements.back().m_state == state_t::eStartElement ) { + m_elements.back().m_state = state_t::eContent; + m_ostream.write( '>' ); + } + + m_elements.push_back( state_t() ); + + m_ostream.write( '<' ); + write_string( element.name() ); + element.forEachAttribute( *this ); + } + void popElement( const char* name ){ + if ( m_elements.back().m_state == state_t::eStartElement ) { + m_ostream.write( '/' ); + m_ostream.write( '>' ); + m_elements.pop_back(); + } + else + { + m_ostream.write( '<' ); + m_ostream.write( '/' ); + write_string( name ); + m_ostream.write( '>' ); + m_elements.pop_back(); + } + } + std::size_t write( const char* data, std::size_t length ){ + if ( m_elements.back().m_state == state_t::eStartElement ) { + m_elements.back().m_state = state_t::eContent; + m_ostream.write( '>' ); + } + write_cdata( data, length ); + return length; + } + + void visit( const char* name, const char* value ){ + m_ostream.write( ' ' ); + write_string( name ); + m_ostream.write( '=' ); + write_quoted_string( value ); + } }; diff --git a/plugins/archivepak/archive.cpp b/plugins/archivepak/archive.cpp index d99ac858..ec88f15f 100644 --- a/plugins/archivepak/archive.cpp +++ b/plugins/archivepak/archive.cpp @@ -52,88 +52,88 @@ inline void buffer_findreplace( char* buffer, char find, char replace ){ class PakArchive final : public Archive { -class PakRecord -{ -public: -PakRecord( unsigned int position, unsigned int stream_size ) - : m_position( position ), m_stream_size( stream_size ){ -} -unsigned int m_position; -unsigned int m_stream_size; -}; -typedef GenericFileSystem PakFileSystem; -PakFileSystem m_filesystem; -FileInputStream m_pakfile; -CopiedString m_name; + class PakRecord + { + public: + PakRecord( unsigned int position, unsigned int stream_size ) + : m_position( position ), m_stream_size( stream_size ){ + } + unsigned int m_position; + unsigned int m_stream_size; + }; + typedef GenericFileSystem PakFileSystem; + PakFileSystem m_filesystem; + FileInputStream m_pakfile; + CopiedString m_name; public: -PakArchive( const char* name ) - : m_pakfile( name ), m_name( name ){ - if ( !m_pakfile.failed() ) { - pakheader_t header; + PakArchive( const char* name ) + : m_pakfile( name ), m_name( name ){ + if ( !m_pakfile.failed() ) { + pakheader_t header; - m_pakfile.read( reinterpret_cast( header.magic ), 4 ); - header.diroffset = istream_read_uint32_le( m_pakfile ); - header.dirsize = istream_read_uint32_le( m_pakfile ); + m_pakfile.read( reinterpret_cast( header.magic ), 4 ); + header.diroffset = istream_read_uint32_le( m_pakfile ); + header.dirsize = istream_read_uint32_le( m_pakfile ); - if ( strncmp( header.magic, "PACK", 4 ) == 0 ) { - m_pakfile.seek( header.diroffset ); + if ( strncmp( header.magic, "PACK", 4 ) == 0 ) { + m_pakfile.seek( header.diroffset ); - for ( unsigned int i = 0; i < header.dirsize; i += sizeof( pakentry_t ) ) - { - pakentry_t entry; - - m_pakfile.read( reinterpret_cast( entry.filename ), 0x38 ); - entry.offset = istream_read_uint32_le( m_pakfile ); - entry.size = istream_read_uint32_le( m_pakfile ); - - buffer_findreplace( entry.filename, '\\', '/' ); - - PakFileSystem::entry_type& file = m_filesystem[entry.filename]; - if ( !file.is_directory() ) { - globalWarningStream() << "Warning: pak archive " << makeQuoted( m_name.c_str() ) << " contains duplicated file: " << makeQuoted( entry.filename ) << "\n"; - } - else + for ( unsigned int i = 0; i < header.dirsize; i += sizeof( pakentry_t ) ) { - file = new PakRecord( entry.offset, entry.size ); + pakentry_t entry; + + m_pakfile.read( reinterpret_cast( entry.filename ), 0x38 ); + entry.offset = istream_read_uint32_le( m_pakfile ); + entry.size = istream_read_uint32_le( m_pakfile ); + + buffer_findreplace( entry.filename, '\\', '/' ); + + PakFileSystem::entry_type& file = m_filesystem[entry.filename]; + if ( !file.is_directory() ) { + globalWarningStream() << "Warning: pak archive " << makeQuoted( m_name.c_str() ) << " contains duplicated file: " << makeQuoted( entry.filename ) << "\n"; + } + else + { + file = new PakRecord( entry.offset, entry.size ); + } } } } } -} -~PakArchive(){ - for ( PakFileSystem::iterator i = m_filesystem.begin(); i != m_filesystem.end(); ++i ) - delete i->second.file(); -} + ~PakArchive(){ + for ( PakFileSystem::iterator i = m_filesystem.begin(); i != m_filesystem.end(); ++i ) + delete i->second.file(); + } -void release(){ - delete this; -} -ArchiveFile* openFile( const char* name ){ - PakFileSystem::iterator i = m_filesystem.find( name ); - if ( i != m_filesystem.end() && !i->second.is_directory() ) { - PakRecord* file = i->second.file(); - return StoredArchiveFile::create( name, m_name.c_str(), file->m_position, file->m_stream_size, file->m_stream_size ); + void release(){ + delete this; } - return 0; -} -virtual ArchiveTextFile* openTextFile( const char* name ){ - PakFileSystem::iterator i = m_filesystem.find( name ); - if ( i != m_filesystem.end() && !i->second.is_directory() ) { - PakRecord* file = i->second.file(); - return StoredArchiveTextFile::create( name, m_name.c_str(), file->m_position, file->m_stream_size ); + ArchiveFile* openFile( const char* name ){ + PakFileSystem::iterator i = m_filesystem.find( name ); + if ( i != m_filesystem.end() && !i->second.is_directory() ) { + PakRecord* file = i->second.file(); + return StoredArchiveFile::create( name, m_name.c_str(), file->m_position, file->m_stream_size, file->m_stream_size ); + } + return 0; + } + virtual ArchiveTextFile* openTextFile( const char* name ){ + PakFileSystem::iterator i = m_filesystem.find( name ); + if ( i != m_filesystem.end() && !i->second.is_directory() ) { + PakRecord* file = i->second.file(); + return StoredArchiveTextFile::create( name, m_name.c_str(), file->m_position, file->m_stream_size ); + } + return 0; + } + bool containsFile( const char* name ){ + PakFileSystem::iterator i = m_filesystem.find( name ); + return i != m_filesystem.end() && !i->second.is_directory(); + } + void forEachFile( VisitorFunc visitor, const char* root ){ + m_filesystem.traverse( visitor, root ); } - return 0; -} -bool containsFile( const char* name ){ - PakFileSystem::iterator i = m_filesystem.find( name ); - return i != m_filesystem.end() && !i->second.is_directory(); -} -void forEachFile( VisitorFunc visitor, const char* root ){ - m_filesystem.traverse( visitor, root ); -} }; @@ -146,16 +146,16 @@ Archive* OpenArchive( const char* name ){ class TestArchive { public: -TestArchive(){ - Archive* archive = OpenArchive( "c:/quake3/baseq3/pak0.pak" ); - ArchiveFile* file = archive->openFile( "gfx/palette.lmp" ); - if ( file != 0 ) { - char buffer[1024]; - file->getInputStream().read( (InputStream::byte_type*)buffer, 1024 ); - file->release(); + TestArchive(){ + Archive* archive = OpenArchive( "c:/quake3/baseq3/pak0.pak" ); + ArchiveFile* file = archive->openFile( "gfx/palette.lmp" ); + if ( file != 0 ) { + char buffer[1024]; + file->getInputStream().read( (InputStream::byte_type*)buffer, 1024 ); + file->release(); + } + archive->release(); } - archive->release(); -} }; TestArchive g_test; @@ -166,43 +166,43 @@ TestArchive g_test; class TestArchive { -class TestVisitor : public Archive::IVisitor -{ -public: -void visit( const char* name ){ - int bleh = 0; -} -}; -public: -TestArchive(){ + class TestVisitor : public Archive::IVisitor { - Archive* archive = OpenArchive( "" ); - archive->release(); - } - { - Archive* archive = OpenArchive( "NONEXISTANTFILE" ); - archive->release(); - } - { - Archive* archive = OpenArchive( "c:/quake/id1/pak0.pak" ); - ArchiveFile* file = archive->openFile( "gfx/palette.lmp" ); - if ( file != 0 ) { - char buffer[1024]; - file->getInputStream().read( (InputStream::byte_type*)buffer, 1024 ); - file->release(); + public: + void visit( const char* name ){ + int bleh = 0; + } + }; +public: + TestArchive(){ + { + Archive* archive = OpenArchive( "" ); + archive->release(); + } + { + Archive* archive = OpenArchive( "NONEXISTANTFILE" ); + archive->release(); + } + { + Archive* archive = OpenArchive( "c:/quake/id1/pak0.pak" ); + ArchiveFile* file = archive->openFile( "gfx/palette.lmp" ); + if ( file != 0 ) { + char buffer[1024]; + file->getInputStream().read( (InputStream::byte_type*)buffer, 1024 ); + file->release(); + } + TestVisitor visitor; + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 0 ), "progs/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 0 ), "maps/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "sound/ambience/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "sound/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "sound/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "sound/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); + archive->release(); } - TestVisitor visitor; - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 0 ), "progs/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 0 ), "maps/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "sound/ambience/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "sound/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "sound/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "sound/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); - archive->release(); } -} }; TestArchive g_test; diff --git a/plugins/archivepak/plugin.cpp b/plugins/archivepak/plugin.cpp index e334248e..8df7bf86 100644 --- a/plugins/archivepak/plugin.cpp +++ b/plugins/archivepak/plugin.cpp @@ -30,17 +30,17 @@ class ArchivePakAPI { -_QERArchiveTable m_archivepak; + _QERArchiveTable m_archivepak; public: -typedef _QERArchiveTable Type; -STRING_CONSTANT( Name, "pak" ); + typedef _QERArchiveTable Type; + STRING_CONSTANT( Name, "pak" ); -ArchivePakAPI(){ - m_archivepak.m_pfnOpenArchive = &OpenArchive; -} -_QERArchiveTable* getTable(){ - return &m_archivepak; -} + ArchivePakAPI(){ + m_archivepak.m_pfnOpenArchive = &OpenArchive; + } + _QERArchiveTable* getTable(){ + return &m_archivepak; + } }; typedef SingletonModule ArchivePakModule; diff --git a/plugins/archivewad/archive.cpp b/plugins/archivewad/archive.cpp index 2f3e7134..80e6beb2 100644 --- a/plugins/archivewad/archive.cpp +++ b/plugins/archivewad/archive.cpp @@ -40,127 +40,127 @@ class WadArchive final : public Archive { -class wad_record_t -{ -public: -wad_record_t( unsigned int position, unsigned int stream_size, unsigned int file_size ) - : m_position( position ), m_stream_size( stream_size ), m_file_size( file_size ) -{} -unsigned int m_position; -unsigned int m_stream_size; -unsigned int m_file_size; -}; - -enum EWadVersion -{ - eNotValid, - eWAD2, - eWAD3, -}; - -typedef std::map files_t; -files_t m_files; -CopiedString m_name; -FileInputStream m_wadfile; - -EWadVersion wad_version( const char* identification ){ - if ( strncmp( identification, "WAD2", 4 ) == 0 ) { - return eWAD2; - } - if ( strncmp( identification, "WAD3", 4 ) == 0 ) { - return eWAD3; - } - return eNotValid; -} - -const char* type_for_version( EWadVersion version ){ - switch ( version ) + class wad_record_t { - case eWAD2: - return ".mip"; - case eWAD3: - return ".hlw"; - default: - break; - } - return ""; -} + public: + wad_record_t( unsigned int position, unsigned int stream_size, unsigned int file_size ) + : m_position( position ), m_stream_size( stream_size ), m_file_size( file_size ) + {} + unsigned int m_position; + unsigned int m_stream_size; + unsigned int m_file_size; + }; -int miptex_type_for_version( EWadVersion version ){ - switch ( version ) + enum EWadVersion { - case eWAD2: - return TYP_MIPTEX; - case eWAD3: - return 67; - default: - break; + eNotValid, + eWAD2, + eWAD3, + }; + + typedef std::map files_t; + files_t m_files; + CopiedString m_name; + FileInputStream m_wadfile; + + EWadVersion wad_version( const char* identification ){ + if ( strncmp( identification, "WAD2", 4 ) == 0 ) { + return eWAD2; + } + if ( strncmp( identification, "WAD3", 4 ) == 0 ) { + return eWAD3; + } + return eNotValid; + } + + const char* type_for_version( EWadVersion version ){ + switch ( version ) + { + case eWAD2: + return ".mip"; + case eWAD3: + return ".hlw"; + default: + break; + } + return ""; + } + + int miptex_type_for_version( EWadVersion version ){ + switch ( version ) + { + case eWAD2: + return TYP_MIPTEX; + case eWAD3: + return 67; + default: + break; + } + return -1; } - return -1; -} public: -WadArchive( const char* name ) - : m_name( name ), m_wadfile( name ){ - if ( !m_wadfile.failed() ) { - wadinfo_t wadinfo; - istream_read_wadinfo( m_wadfile, wadinfo ); + WadArchive( const char* name ) + : m_name( name ), m_wadfile( name ){ + if ( !m_wadfile.failed() ) { + wadinfo_t wadinfo; + istream_read_wadinfo( m_wadfile, wadinfo ); - EWadVersion version = wad_version( wadinfo.identification ); - int miptexType = miptex_type_for_version( version ); + EWadVersion version = wad_version( wadinfo.identification ); + int miptexType = miptex_type_for_version( version ); - if ( version != eNotValid ) { - m_wadfile.seek( wadinfo.infotableofs ); + if ( version != eNotValid ) { + m_wadfile.seek( wadinfo.infotableofs ); - for ( int i = 0; i < wadinfo.numlumps; ++i ) - { - char buffer[32]; - lumpinfo_t lumpinfo; - istream_read_lumpinfo( m_wadfile, lumpinfo ); - if ( lumpinfo.type == miptexType ) { - strcpy( buffer, "textures/" ); - strcat( buffer, lumpinfo.name ); - strcat( buffer, type_for_version( version ) ); - m_files.insert( files_t::value_type( buffer, wad_record_t( lumpinfo.filepos, lumpinfo.disksize, lumpinfo.size ) ) ); + for ( int i = 0; i < wadinfo.numlumps; ++i ) + { + char buffer[32]; + lumpinfo_t lumpinfo; + istream_read_lumpinfo( m_wadfile, lumpinfo ); + if ( lumpinfo.type == miptexType ) { + strcpy( buffer, "textures/" ); + strcat( buffer, lumpinfo.name ); + strcat( buffer, type_for_version( version ) ); + m_files.insert( files_t::value_type( buffer, wad_record_t( lumpinfo.filepos, lumpinfo.disksize, lumpinfo.size ) ) ); + } } } } } -} -void release(){ - delete this; -} -ArchiveFile* openFile( const char* name ){ - files_t::iterator i = m_files.find( name ); - if ( i != m_files.end() ) { - return StoredArchiveFile::create( name, m_name.c_str(), i->second.m_position, i->second.m_stream_size, i->second.m_file_size ); + void release(){ + delete this; } - return 0; -} -virtual ArchiveTextFile* openTextFile( const char* name ){ - files_t::iterator i = m_files.find( name ); - if ( i != m_files.end() ) { - return StoredArchiveTextFile::create( name, m_name.c_str(), i->second.m_position, i->second.m_stream_size ); + ArchiveFile* openFile( const char* name ){ + files_t::iterator i = m_files.find( name ); + if ( i != m_files.end() ) { + return StoredArchiveFile::create( name, m_name.c_str(), i->second.m_position, i->second.m_stream_size, i->second.m_file_size ); + } + return 0; } - return 0; -} -bool containsFile( const char* name ){ - return m_files.find( name ) != m_files.end(); -} -void forEachFile( VisitorFunc visitor, const char* root ){ - if ( root[0] == '\0' ) { - if ( visitor.directory( "textures/", 1 ) ) { + virtual ArchiveTextFile* openTextFile( const char* name ){ + files_t::iterator i = m_files.find( name ); + if ( i != m_files.end() ) { + return StoredArchiveTextFile::create( name, m_name.c_str(), i->second.m_position, i->second.m_stream_size ); + } + return 0; + } + bool containsFile( const char* name ){ + return m_files.find( name ) != m_files.end(); + } + void forEachFile( VisitorFunc visitor, const char* root ){ + if ( root[0] == '\0' ) { + if ( visitor.directory( "textures/", 1 ) ) { + return; + } + } + else if ( strcmp( root, "textures/" ) != 0 ) { return; } - } - else if ( strcmp( root, "textures/" ) != 0 ) { - return; - } - for ( files_t::iterator i = m_files.begin(); i != m_files.end(); ++i ) - visitor.file( i->first.c_str() ); -} + for ( files_t::iterator i = m_files.begin(); i != m_files.end(); ++i ) + visitor.file( i->first.c_str() ); + } }; @@ -172,40 +172,40 @@ Archive* OpenArchive( const char* name ){ class TestArchive { -class TestVisitor : public Archive::IVisitor -{ -public: -void visit( const char* name ){ - int bleh = 0; -} -}; -public: -TestArchive(){ + class TestVisitor : public Archive::IVisitor { - Archive* archive = OpenArchive( "" ); - archive->release(); - } - { - Archive* archive = OpenArchive( "NONEXISTANTFILE" ); - archive->release(); - } - { - Archive* archive = OpenArchive( "c:/quake/id1/quake101.wad" ); - ArchiveFile* file = archive->openFile( "textures/sky1.mip" ); - if ( file != 0 ) { - unsigned char* buffer = new unsigned char[file->size()]; - file->getInputStream().read( (InputStream::byte_type*)buffer, file->size() ); - delete[] buffer; - file->release(); + public: + void visit( const char* name ){ + int bleh = 0; + } + }; +public: + TestArchive(){ + { + Archive* archive = OpenArchive( "" ); + archive->release(); + } + { + Archive* archive = OpenArchive( "NONEXISTANTFILE" ); + archive->release(); + } + { + Archive* archive = OpenArchive( "c:/quake/id1/quake101.wad" ); + ArchiveFile* file = archive->openFile( "textures/sky1.mip" ); + if ( file != 0 ) { + unsigned char* buffer = new unsigned char[file->size()]; + file->getInputStream().read( (InputStream::byte_type*)buffer, file->size() ); + delete[] buffer; + file->release(); + } + TestVisitor visitor; + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "textures/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures/" ); + archive->release(); } - TestVisitor visitor; - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "textures/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures/" ); - archive->release(); } -} }; TestArchive g_test; diff --git a/plugins/archivewad/plugin.cpp b/plugins/archivewad/plugin.cpp index 2ade32ab..8c4a740d 100644 --- a/plugins/archivewad/plugin.cpp +++ b/plugins/archivewad/plugin.cpp @@ -30,17 +30,17 @@ class ArchiveWadAPI { -_QERArchiveTable m_archivewad; + _QERArchiveTable m_archivewad; public: -typedef _QERArchiveTable Type; -STRING_CONSTANT( Name, "wad" ); + typedef _QERArchiveTable Type; + STRING_CONSTANT( Name, "wad" ); -ArchiveWadAPI(){ - m_archivewad.m_pfnOpenArchive = &OpenArchive; -} -_QERArchiveTable* getTable(){ - return &m_archivewad; -} + ArchiveWadAPI(){ + m_archivewad.m_pfnOpenArchive = &OpenArchive; + } + _QERArchiveTable* getTable(){ + return &m_archivewad; + } }; typedef SingletonModule ArchiveWadModule; diff --git a/plugins/archivezip/archive.cpp b/plugins/archivezip/archive.cpp index 5d1bf25c..c79c334b 100644 --- a/plugins/archivezip/archive.cpp +++ b/plugins/archivezip/archive.cpp @@ -34,54 +34,54 @@ class DeflatedArchiveFile final : public ArchiveFile { -CopiedString m_name; -FileInputStream m_istream; -SubFileInputStream m_substream; -DeflatedInputStream m_zipstream; -FileInputStream::size_type m_size; + CopiedString m_name; + FileInputStream m_istream; + SubFileInputStream m_substream; + DeflatedInputStream m_zipstream; + FileInputStream::size_type m_size; public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; + typedef FileInputStream::size_type size_type; + typedef FileInputStream::position_type position_type; -DeflatedArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) - : m_name( name ), m_istream( archiveName ), m_substream( m_istream, position, stream_size ), m_zipstream( m_substream ), m_size( file_size ){ -} + DeflatedArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) + : m_name( name ), m_istream( archiveName ), m_substream( m_istream, position, stream_size ), m_zipstream( m_substream ), m_size( file_size ){ + } -void release(){ - delete this; -} -size_type size() const { - return m_size; -} -const char* getName() const { - return m_name.c_str(); -} -InputStream& getInputStream(){ - return m_zipstream; -} + void release(){ + delete this; + } + size_type size() const { + return m_size; + } + const char* getName() const { + return m_name.c_str(); + } + InputStream& getInputStream(){ + return m_zipstream; + } }; class DeflatedArchiveTextFile final : public ArchiveTextFile { -CopiedString m_name; -FileInputStream m_istream; -SubFileInputStream m_substream; -DeflatedInputStream m_zipstream; -BinaryToTextInputStream m_textStream; + CopiedString m_name; + FileInputStream m_istream; + SubFileInputStream m_substream; + DeflatedInputStream m_zipstream; + BinaryToTextInputStream m_textStream; public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; + typedef FileInputStream::size_type size_type; + typedef FileInputStream::position_type position_type; -DeflatedArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) - : m_name( name ), m_istream( archiveName ), m_substream( m_istream, position, stream_size ), m_zipstream( m_substream ), m_textStream( m_zipstream ){ -} + DeflatedArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) + : m_name( name ), m_istream( archiveName ), m_substream( m_istream, position, stream_size ), m_zipstream( m_substream ), m_textStream( m_zipstream ){ + } -void release(){ - delete this; -} -TextInputStream& getInputStream(){ - return m_textStream; -} + void release(){ + delete this; + } + TextInputStream& getInputStream(){ + return m_textStream; + } }; #include "pkzip.h" @@ -93,182 +93,182 @@ TextInputStream& getInputStream(){ class ZipArchive final : public Archive { -class ZipRecord -{ -public: -enum ECompressionMode -{ - eStored, - eDeflated, -}; -ZipRecord( unsigned int position, unsigned int compressed_size, unsigned int uncompressed_size, ECompressionMode mode ) - : m_position( position ), m_stream_size( compressed_size ), m_file_size( uncompressed_size ), m_mode( mode ){ -} -unsigned int m_position; -unsigned int m_stream_size; -unsigned int m_file_size; -ECompressionMode m_mode; -}; - -typedef GenericFileSystem ZipFileSystem; -ZipFileSystem m_filesystem; -CopiedString m_name; -FileInputStream m_istream; - -bool read_record(){ - zip_magic magic; - istream_read_zip_magic( m_istream, magic ); - if ( !( magic == zip_root_dirent_magic ) ) { - return false; - } - zip_version version_encoder; - istream_read_zip_version( m_istream, version_encoder ); - zip_version version_extract; - istream_read_zip_version( m_istream, version_extract ); - //unsigned short flags = - istream_read_int16_le( m_istream ); - unsigned short compression_mode = istream_read_int16_le( m_istream ); - if ( compression_mode != Z_DEFLATED && compression_mode != 0 ) { - return false; - } - zip_dostime dostime; - istream_read_zip_dostime( m_istream, dostime ); - //unsigned int crc32 = - istream_read_int32_le( m_istream ); - unsigned int compressed_size = istream_read_uint32_le( m_istream ); - unsigned int uncompressed_size = istream_read_uint32_le( m_istream ); - unsigned int namelength = istream_read_uint16_le( m_istream ); - unsigned short extras = istream_read_uint16_le( m_istream ); - unsigned short comment = istream_read_uint16_le( m_istream ); - //unsigned short diskstart = - istream_read_int16_le( m_istream ); - //unsigned short filetype = - istream_read_int16_le( m_istream ); - //unsigned int filemode = - istream_read_int32_le( m_istream ); - unsigned int position = istream_read_int32_le( m_istream ); - - Array filename( namelength + 1 ); - m_istream.read( reinterpret_cast( filename.data() ), namelength ); - filename[namelength] = '\0'; - - m_istream.seek( extras + comment, FileInputStream::cur ); - - if ( path_is_directory( filename.data() ) ) { - m_filesystem[filename.data()] = 0; - } - else + class ZipRecord { - ZipFileSystem::entry_type& file = m_filesystem[filename.data()]; - if ( !file.is_directory() ) { - globalWarningStream() << "Warning: zip archive " << makeQuoted( m_name.c_str() ) << " contains duplicated file: " << makeQuoted( filename.data() ) << "\n"; + public: + enum ECompressionMode + { + eStored, + eDeflated, + }; + ZipRecord( unsigned int position, unsigned int compressed_size, unsigned int uncompressed_size, ECompressionMode mode ) + : m_position( position ), m_stream_size( compressed_size ), m_file_size( uncompressed_size ), m_mode( mode ){ + } + unsigned int m_position; + unsigned int m_stream_size; + unsigned int m_file_size; + ECompressionMode m_mode; + }; + + typedef GenericFileSystem ZipFileSystem; + ZipFileSystem m_filesystem; + CopiedString m_name; + FileInputStream m_istream; + + bool read_record(){ + zip_magic magic; + istream_read_zip_magic( m_istream, magic ); + if ( !( magic == zip_root_dirent_magic ) ) { + return false; + } + zip_version version_encoder; + istream_read_zip_version( m_istream, version_encoder ); + zip_version version_extract; + istream_read_zip_version( m_istream, version_extract ); + //unsigned short flags = + istream_read_int16_le( m_istream ); + unsigned short compression_mode = istream_read_int16_le( m_istream ); + if ( compression_mode != Z_DEFLATED && compression_mode != 0 ) { + return false; + } + zip_dostime dostime; + istream_read_zip_dostime( m_istream, dostime ); + //unsigned int crc32 = + istream_read_int32_le( m_istream ); + unsigned int compressed_size = istream_read_uint32_le( m_istream ); + unsigned int uncompressed_size = istream_read_uint32_le( m_istream ); + unsigned int namelength = istream_read_uint16_le( m_istream ); + unsigned short extras = istream_read_uint16_le( m_istream ); + unsigned short comment = istream_read_uint16_le( m_istream ); + //unsigned short diskstart = + istream_read_int16_le( m_istream ); + //unsigned short filetype = + istream_read_int16_le( m_istream ); + //unsigned int filemode = + istream_read_int32_le( m_istream ); + unsigned int position = istream_read_int32_le( m_istream ); + + Array filename( namelength + 1 ); + m_istream.read( reinterpret_cast( filename.data() ), namelength ); + filename[namelength] = '\0'; + + m_istream.seek( extras + comment, FileInputStream::cur ); + + if ( path_is_directory( filename.data() ) ) { + m_filesystem[filename.data()] = 0; } else { - file = new ZipRecord( position, compressed_size, uncompressed_size, ( compression_mode == Z_DEFLATED ) ? ZipRecord::eDeflated : ZipRecord::eStored ); - } - } - - return true; -} - -bool read_pkzip(){ - SeekableStream::position_type pos = pkzip_find_disk_trailer( m_istream ); - if ( pos != 0 ) { - zip_disk_trailer disk_trailer; - m_istream.seek( pos ); - istream_read_zip_disk_trailer( m_istream, disk_trailer ); - if ( !( disk_trailer.z_magic == zip_disk_trailer_magic ) ) { - return false; - } - - m_istream.seek( disk_trailer.z_rootseek ); - for ( unsigned int i = 0; i < disk_trailer.z_entries; ++i ) - { - if ( !read_record() ) { - return false; + ZipFileSystem::entry_type& file = m_filesystem[filename.data()]; + if ( !file.is_directory() ) { + globalWarningStream() << "Warning: zip archive " << makeQuoted( m_name.c_str() ) << " contains duplicated file: " << makeQuoted( filename.data() ) << "\n"; + } + else + { + file = new ZipRecord( position, compressed_size, uncompressed_size, ( compression_mode == Z_DEFLATED ) ? ZipRecord::eDeflated : ZipRecord::eStored ); } } + return true; } - return false; -} + + bool read_pkzip(){ + SeekableStream::position_type pos = pkzip_find_disk_trailer( m_istream ); + if ( pos != 0 ) { + zip_disk_trailer disk_trailer; + m_istream.seek( pos ); + istream_read_zip_disk_trailer( m_istream, disk_trailer ); + if ( !( disk_trailer.z_magic == zip_disk_trailer_magic ) ) { + return false; + } + + m_istream.seek( disk_trailer.z_rootseek ); + for ( unsigned int i = 0; i < disk_trailer.z_entries; ++i ) + { + if ( !read_record() ) { + return false; + } + } + return true; + } + return false; + } public: -ZipArchive( const char* name ) - : m_name( name ), m_istream( name ){ - if ( !m_istream.failed() ) { - if ( !read_pkzip() ) { - globalErrorStream() << "ERROR: invalid zip-file " << makeQuoted( name ) << '\n'; + ZipArchive( const char* name ) + : m_name( name ), m_istream( name ){ + if ( !m_istream.failed() ) { + if ( !read_pkzip() ) { + globalErrorStream() << "ERROR: invalid zip-file " << makeQuoted( name ) << '\n'; + } } } -} -~ZipArchive(){ - for ( ZipFileSystem::iterator i = m_filesystem.begin(); i != m_filesystem.end(); ++i ) - { - delete i->second.file(); - } -} - -bool failed(){ - return m_istream.failed(); -} - -void release(){ - delete this; -} -ArchiveFile* openFile( const char* name ){ - ZipFileSystem::iterator i = m_filesystem.find( name ); - if ( i != m_filesystem.end() && !i->second.is_directory() ) { - ZipRecord* file = i->second.file(); - - m_istream.seek( file->m_position ); - zip_file_header file_header; - istream_read_zip_file_header( m_istream, file_header ); - if ( file_header.z_magic != zip_file_header_magic ) { - globalErrorStream() << "error reading zip file " << makeQuoted( m_name.c_str() ); - return 0; - } - - switch ( file->m_mode ) + ~ZipArchive(){ + for ( ZipFileSystem::iterator i = m_filesystem.begin(); i != m_filesystem.end(); ++i ) { - case ZipRecord::eStored: - return StoredArchiveFile::create( name, m_name.c_str(), m_istream.tell(), file->m_stream_size, file->m_file_size ); - case ZipRecord::eDeflated: - return new DeflatedArchiveFile( name, m_name.c_str(), m_istream.tell(), file->m_stream_size, file->m_file_size ); + delete i->second.file(); } } - return 0; -} -ArchiveTextFile* openTextFile( const char* name ){ - ZipFileSystem::iterator i = m_filesystem.find( name ); - if ( i != m_filesystem.end() && !i->second.is_directory() ) { - ZipRecord* file = i->second.file(); - m_istream.seek( file->m_position ); - zip_file_header file_header; - istream_read_zip_file_header( m_istream, file_header ); - if ( file_header.z_magic != zip_file_header_magic ) { - globalErrorStream() << "error reading zip file " << makeQuoted( m_name.c_str() ); - return 0; - } - - switch ( file->m_mode ) - { - case ZipRecord::eStored: - return StoredArchiveTextFile::create( name, m_name.c_str(), m_istream.tell(), file->m_stream_size ); - case ZipRecord::eDeflated: - return new DeflatedArchiveTextFile( name, m_name.c_str(), m_istream.tell(), file->m_stream_size ); - } + bool failed(){ + return m_istream.failed(); + } + + void release(){ + delete this; + } + ArchiveFile* openFile( const char* name ){ + ZipFileSystem::iterator i = m_filesystem.find( name ); + if ( i != m_filesystem.end() && !i->second.is_directory() ) { + ZipRecord* file = i->second.file(); + + m_istream.seek( file->m_position ); + zip_file_header file_header; + istream_read_zip_file_header( m_istream, file_header ); + if ( file_header.z_magic != zip_file_header_magic ) { + globalErrorStream() << "error reading zip file " << makeQuoted( m_name.c_str() ); + return 0; + } + + switch ( file->m_mode ) + { + case ZipRecord::eStored: + return StoredArchiveFile::create( name, m_name.c_str(), m_istream.tell(), file->m_stream_size, file->m_file_size ); + case ZipRecord::eDeflated: + return new DeflatedArchiveFile( name, m_name.c_str(), m_istream.tell(), file->m_stream_size, file->m_file_size ); + } + } + return 0; + } + ArchiveTextFile* openTextFile( const char* name ){ + ZipFileSystem::iterator i = m_filesystem.find( name ); + if ( i != m_filesystem.end() && !i->second.is_directory() ) { + ZipRecord* file = i->second.file(); + + m_istream.seek( file->m_position ); + zip_file_header file_header; + istream_read_zip_file_header( m_istream, file_header ); + if ( file_header.z_magic != zip_file_header_magic ) { + globalErrorStream() << "error reading zip file " << makeQuoted( m_name.c_str() ); + return 0; + } + + switch ( file->m_mode ) + { + case ZipRecord::eStored: + return StoredArchiveTextFile::create( name, m_name.c_str(), m_istream.tell(), file->m_stream_size ); + case ZipRecord::eDeflated: + return new DeflatedArchiveTextFile( name, m_name.c_str(), m_istream.tell(), file->m_stream_size ); + } + } + return 0; + } + bool containsFile( const char* name ){ + ZipFileSystem::iterator i = m_filesystem.find( name ); + return i != m_filesystem.end() && !i->second.is_directory(); + } + void forEachFile( VisitorFunc visitor, const char* root ){ + m_filesystem.traverse( visitor, root ); } - return 0; -} -bool containsFile( const char* name ){ - ZipFileSystem::iterator i = m_filesystem.find( name ); - return i != m_filesystem.end() && !i->second.is_directory(); -} -void forEachFile( VisitorFunc visitor, const char* root ){ - m_filesystem.traverse( visitor, root ); -} }; Archive* OpenArchive( const char* name ){ @@ -279,36 +279,36 @@ Archive* OpenArchive( const char* name ){ class TestZip { -class TestVisitor : public Archive::IVisitor -{ + class TestVisitor : public Archive::IVisitor + { + public: + void visit( const char* name ){ + int bleh = 0; + } + }; public: -void visit( const char* name ){ - int bleh = 0; -} -}; -public: -TestZip(){ - testzip( "c:/quake3/baseq3/mapmedia.pk3", "textures/radiant/notex.tga" ); -} - -void testzip( const char* name, const char* filename ){ - Archive* archive = OpenArchive( name ); - ArchiveFile* file = archive->openFile( filename ); - if ( file != 0 ) { - unsigned char buffer[4096]; - std::size_t count = file->getInputStream().read( (InputStream::byte_type*)buffer, 4096 ); - file->release(); + TestZip(){ + testzip( "c:/quake3/baseq3/mapmedia.pk3", "textures/radiant/notex.tga" ); + } + + void testzip( const char* name, const char* filename ){ + Archive* archive = OpenArchive( name ); + ArchiveFile* file = archive->openFile( filename ); + if ( file != 0 ) { + unsigned char buffer[4096]; + std::size_t count = file->getInputStream().read( (InputStream::byte_type*)buffer, 4096 ); + file->release(); + } + TestVisitor visitor; + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures/" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); + archive->release(); } - TestVisitor visitor; - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures/" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); - archive->release(); -} }; TestZip g_TestZip; diff --git a/plugins/archivezip/pkzip.h b/plugins/archivezip/pkzip.h index 146c4075..921293b5 100644 --- a/plugins/archivezip/pkzip.h +++ b/plugins/archivezip/pkzip.h @@ -29,16 +29,16 @@ class zip_magic { public: -bool operator==( const zip_magic& other ) const { - return m_value[0] == other.m_value[0] - && m_value[1] == other.m_value[1] - && m_value[2] == other.m_value[2] - && m_value[3] == other.m_value[3]; -} -bool operator!=( const zip_magic& other ) const { - return !( *this == other ); -} -char m_value[4]; + bool operator==( const zip_magic& other ) const { + return m_value[0] == other.m_value[0] + && m_value[1] == other.m_value[1] + && m_value[2] == other.m_value[2] + && m_value[3] == other.m_value[3]; + } + bool operator!=( const zip_magic& other ) const { + return !( *this == other ); + } + char m_value[4]; }; inline void istream_read_zip_magic( InputStream& istream, zip_magic& magic ){ diff --git a/plugins/archivezip/plugin.cpp b/plugins/archivezip/plugin.cpp index 8375eafa..37045fb9 100644 --- a/plugins/archivezip/plugin.cpp +++ b/plugins/archivezip/plugin.cpp @@ -31,17 +31,17 @@ class ArchiveZipAPI { -_QERArchiveTable m_archivezip; + _QERArchiveTable m_archivezip; public: -typedef _QERArchiveTable Type; -STRING_CONSTANT( Name, "pk3" ); + typedef _QERArchiveTable Type; + STRING_CONSTANT( Name, "pk3" ); -ArchiveZipAPI(){ - m_archivezip.m_pfnOpenArchive = &OpenArchive; -} -_QERArchiveTable* getTable(){ - return &m_archivezip; -} + ArchiveZipAPI(){ + m_archivezip.m_pfnOpenArchive = &OpenArchive; + } + _QERArchiveTable* getTable(){ + return &m_archivezip; + } }; typedef SingletonModule ArchiveZipModule; @@ -51,17 +51,17 @@ ArchiveZipModule g_ArchiveZipModule; class ArchivePK4API { -_QERArchiveTable m_archivepk4; + _QERArchiveTable m_archivepk4; public: -typedef _QERArchiveTable Type; -STRING_CONSTANT( Name, "pk4" ); + typedef _QERArchiveTable Type; + STRING_CONSTANT( Name, "pk4" ); -ArchivePK4API(){ - m_archivepk4.m_pfnOpenArchive = &OpenArchive; -} -_QERArchiveTable* getTable(){ - return &m_archivepk4; -} + ArchivePK4API(){ + m_archivepk4.m_pfnOpenArchive = &OpenArchive; + } + _QERArchiveTable* getTable(){ + return &m_archivepk4; + } }; typedef SingletonModule ArchivePK4Module; diff --git a/plugins/archivezip/zlibstream.h b/plugins/archivezip/zlibstream.h index 2e2e7d8f..c2f3887a 100644 --- a/plugins/archivezip/zlibstream.h +++ b/plugins/archivezip/zlibstream.h @@ -31,38 +31,38 @@ /// - Uses a buffer to reduce the number of times the wrapped stream must be read. class DeflatedInputStream : public InputStream { -InputStream& m_istream; -z_stream m_zipstream; -enum unnamed0 { m_bufsize = 1024 }; -unsigned char m_buffer[m_bufsize]; + InputStream& m_istream; + z_stream m_zipstream; + enum unnamed0 { m_bufsize = 1024 }; + unsigned char m_buffer[m_bufsize]; public: -DeflatedInputStream( InputStream& istream ) - : m_istream( istream ){ - m_zipstream.zalloc = 0; - m_zipstream.zfree = 0; - m_zipstream.opaque = 0; - m_zipstream.avail_in = 0; - inflateInit2( &m_zipstream, -MAX_WBITS ); -} -~DeflatedInputStream(){ - inflateEnd( &m_zipstream ); -} -size_type read( byte_type* buffer, size_type length ){ - m_zipstream.next_out = buffer; - m_zipstream.avail_out = static_cast( length ); - while ( m_zipstream.avail_out != 0 ) - { - if ( m_zipstream.avail_in == 0 ) { - m_zipstream.next_in = m_buffer; - m_zipstream.avail_in = static_cast( m_istream.read( m_buffer, m_bufsize ) ); - } - if ( inflate( &m_zipstream, Z_SYNC_FLUSH ) != Z_OK ) { - break; - } + DeflatedInputStream( InputStream& istream ) + : m_istream( istream ){ + m_zipstream.zalloc = 0; + m_zipstream.zfree = 0; + m_zipstream.opaque = 0; + m_zipstream.avail_in = 0; + inflateInit2( &m_zipstream, -MAX_WBITS ); + } + ~DeflatedInputStream(){ + inflateEnd( &m_zipstream ); + } + size_type read( byte_type* buffer, size_type length ){ + m_zipstream.next_out = buffer; + m_zipstream.avail_out = static_cast( length ); + while ( m_zipstream.avail_out != 0 ) + { + if ( m_zipstream.avail_in == 0 ) { + m_zipstream.next_in = m_buffer; + m_zipstream.avail_in = static_cast( m_istream.read( m_buffer, m_bufsize ) ); + } + if ( inflate( &m_zipstream, Z_SYNC_FLUSH ) != Z_OK ) { + break; + } + } + return length - m_zipstream.avail_out; } - return length - m_zipstream.avail_out; -} }; #endif diff --git a/plugins/entity/angle.h b/plugins/entity/angle.h index e3a1a38d..18f0d6c4 100644 --- a/plugins/entity/angle.h +++ b/plugins/entity/angle.h @@ -59,24 +59,24 @@ inline void write_angle( float angle, Entity* entity ){ class AngleKey { -Callback m_angleChanged; + Callback m_angleChanged; public: -float m_angle; + float m_angle; -AngleKey( const Callback& angleChanged ) - : m_angleChanged( angleChanged ), m_angle( ANGLEKEY_IDENTITY ){ -} + AngleKey( const Callback& angleChanged ) + : m_angleChanged( angleChanged ), m_angle( ANGLEKEY_IDENTITY ){ + } -void angleChanged( const char* value ){ - read_angle( m_angle, value ); - m_angleChanged(); -} -typedef MemberCaller1 AngleChangedCaller; + void angleChanged( const char* value ){ + read_angle( m_angle, value ); + m_angleChanged(); + } + typedef MemberCaller1 AngleChangedCaller; -void write( Entity* entity ) const { - write_angle( m_angle, entity ); -} + void write( Entity* entity ) const { + write_angle( m_angle, entity ); + } }; inline float float_snapped_to_zero( float value ){ @@ -85,13 +85,13 @@ inline float float_snapped_to_zero( float value ){ inline float angle_rotated( float angle, const Quaternion& rotation ){ return float_snapped_to_zero( - matrix4_get_rotation_euler_xyz_degrees( - matrix4_multiplied_by_matrix4( - matrix4_rotation_for_quaternion_quantised( rotation ), - matrix4_rotation_for_z_degrees( angle ) - ) - ).z() - ); + matrix4_get_rotation_euler_xyz_degrees( + matrix4_multiplied_by_matrix4( + matrix4_rotation_for_quaternion_quantised( rotation ), + matrix4_rotation_for_z_degrees( angle ) + ) + ).z() + ); } #endif diff --git a/plugins/entity/angles.h b/plugins/entity/angles.h index 655f6f82..77643a8d 100644 --- a/plugins/entity/angles.h +++ b/plugins/entity/angles.h @@ -64,9 +64,7 @@ inline void read_angles( Vector3& angles, const char* value ){ } } inline void write_angles( const Vector3& angles, Entity* entity ){ - if ( angles[0] == 0 - && angles[1] == 0 - && angles[2] == 0 ) { + if ( angles == ANGLESKEY_IDENTITY ) { entity->setKeyValue( "angle", "" ); entity->setKeyValue( "angles", "" ); } @@ -103,70 +101,70 @@ inline Matrix4 matrix4_rotation_for_euler_xyz_degrees_quantised( const Vector3& inline Vector3 angles_snapped_to_zero( const Vector3& angles ){ float epsilon = ( fabs( angles[0] ) > 0.001f || fabs( angles[1] ) > 0.001f || fabs( angles[2] ) > 0.001f ) ? 5e-5 : 1e-6; return Vector3( fabs( angles[0] ) < epsilon ? 0.f : angles[0], - fabs( angles[1] ) < epsilon ? 0.f : angles[1], - fabs( angles[2] ) < epsilon ? 0.f : angles[2] - ); + fabs( angles[1] ) < epsilon ? 0.f : angles[1], + fabs( angles[2] ) < epsilon ? 0.f : angles[2] + ); } inline Vector3 angles_rotated( const Vector3& angles, const Quaternion& rotation ){ return angles_snapped_to_zero( - matrix4_get_rotation_euler_xyz_degrees( - matrix4_multiplied_by_matrix4( - matrix4_rotation_for_quaternion_quantised( rotation ), - matrix4_rotation_for_euler_xyz_degrees_quantised( angles ) - ) - ) - ); + matrix4_get_rotation_euler_xyz_degrees( + matrix4_multiplied_by_matrix4( + matrix4_rotation_for_quaternion_quantised( rotation ), + matrix4_rotation_for_euler_xyz_degrees_quantised( angles ) + ) + ) + ); } #if 0 inline Vector3 angles_rotated_for_rotated_pivot( const Vector3& angles, const Quaternion& rotation ){ return angles_snapped_to_zero( - matrix4_get_rotation_euler_xyz_degrees( - matrix4_multiplied_by_matrix4( - matrix4_rotation_for_euler_xyz_degrees_quantised( angles ), - matrix4_rotation_for_quaternion_quantised( rotation ) - ) - ) - ); + matrix4_get_rotation_euler_xyz_degrees( + matrix4_multiplied_by_matrix4( + matrix4_rotation_for_euler_xyz_degrees_quantised( angles ), + matrix4_rotation_for_quaternion_quantised( rotation ) + ) + ) + ); } #endif class AnglesKey { -Callback m_anglesChanged; + Callback m_anglesChanged; public: -Vector3 m_angles; + Vector3 m_angles; -AnglesKey( const Callback& anglesChanged ) - : m_anglesChanged( anglesChanged ), m_angles( ANGLESKEY_IDENTITY ){ -} + AnglesKey( const Callback& anglesChanged ) + : m_anglesChanged( anglesChanged ), m_angles( ANGLESKEY_IDENTITY ){ + } -void angleChanged( const char* value ){ - read_angle( m_angles, value ); - m_anglesChanged(); -} -typedef MemberCaller1 AngleChangedCaller; - -void groupAngleChanged( const char* value ){ - if( strlen( value ) == 2 && value[0] == '-' && value[1] == '1' ) - m_angles = Vector3( 0, -90, 0 ); - else if( strlen( value ) == 2 && value[0] == '-' && value[1] == '2' ) - m_angles = Vector3( 0, 90, 0 ); - else + void angleChanged( const char* value ){ read_angle( m_angles, value ); - m_anglesChanged(); -} -typedef MemberCaller1 GroupAngleChangedCaller; + m_anglesChanged(); + } + typedef MemberCaller1 AngleChangedCaller; -void anglesChanged( const char* value ){ - read_angles( m_angles, value ); - m_anglesChanged(); -} -typedef MemberCaller1 AnglesChangedCaller; + void groupAngleChanged( const char* value ){ + if( strlen( value ) == 2 && value[0] == '-' && value[1] == '1' ) + m_angles = Vector3( 0, -90, 0 ); + else if( strlen( value ) == 2 && value[0] == '-' && value[1] == '2' ) + m_angles = Vector3( 0, 90, 0 ); + else + read_angle( m_angles, value ); + m_anglesChanged(); + } + typedef MemberCaller1 GroupAngleChangedCaller; -void write( Entity* entity ) const { - write_angles( m_angles, entity ); -} + void anglesChanged( const char* value ){ + read_angles( m_angles, value ); + m_anglesChanged(); + } + typedef MemberCaller1 AnglesChangedCaller; + + void write( Entity* entity ) const { + write_angles( m_angles, entity ); + } }; diff --git a/plugins/entity/colour.h b/plugins/entity/colour.h index 2ecbc3d2..b5cd860b 100644 --- a/plugins/entity/colour.h +++ b/plugins/entity/colour.h @@ -47,51 +47,51 @@ inline void write_colour( const Vector3& colour, Entity* entity ){ class Colour { -Callback m_colourChanged; -Shader* m_state; -Shader* m_state_additive; + Callback m_colourChanged; + Shader* m_state; + Shader* m_state_additive; -void capture_state(){ - m_state = colour_capture_state_fill( m_colour ); - m_state_additive = colour_capture_state_add( m_colour ); -} -void release_state(){ - colour_release_state_fill( m_colour ); - colour_release_state_add( m_colour ); -} + void capture_state(){ + m_state = colour_capture_state_fill( m_colour ); + m_state_additive = colour_capture_state_add( m_colour ); + } + void release_state(){ + colour_release_state_fill( m_colour ); + colour_release_state_add( m_colour ); + } public: -Vector3 m_colour; + Vector3 m_colour; -Colour( const Callback& colourChanged ) - : m_colourChanged( colourChanged ){ - default_colour( m_colour ); - capture_state(); -} -~Colour(){ - release_state(); -} + Colour( const Callback& colourChanged ) + : m_colourChanged( colourChanged ){ + default_colour( m_colour ); + capture_state(); + } + ~Colour(){ + release_state(); + } -void colourChanged( const char* value ){ - release_state(); - read_colour( m_colour, value ); - capture_state(); + void colourChanged( const char* value ){ + release_state(); + read_colour( m_colour, value ); + capture_state(); - m_colourChanged(); -} -typedef MemberCaller1 ColourChangedCaller; + m_colourChanged(); + } + typedef MemberCaller1 ColourChangedCaller; -void write( Entity* entity ) const { - write_colour( m_colour, entity ); -} + void write( Entity* entity ) const { + write_colour( m_colour, entity ); + } -Shader* state() const { - return m_state; -} -Shader* state_additive() const { - return m_state_additive; -} + Shader* state() const { + return m_state; + } + Shader* state_additive() const { + return m_state_additive; + } }; #endif diff --git a/plugins/entity/curve.h b/plugins/entity/curve.h index de610de3..37fac120 100644 --- a/plugins/entity/curve.h +++ b/plugins/entity/curve.h @@ -38,11 +38,11 @@ class RenderableCurve : public OpenGLRenderable { public: -std::vector m_vertices; -void render( RenderStateFlags state ) const { - pointvertex_gl_array( &m_vertices.front() ); - glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) ); -} + std::vector m_vertices; + void render( RenderStateFlags state ) const { + pointvertex_gl_array( &m_vertices.front() ); + glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) ); + } }; inline void plotBasisFunction( std::size_t numSegments, int point, int degree ){ @@ -83,8 +83,8 @@ inline bool ControlPoints_parse( ControlPoints& controlPoints, const char* value for ( ControlPoints::iterator i = controlPoints.begin(); i != controlPoints.end(); ++i ) { if ( !string_parse_float( tokeniser.getToken(), ( *i ).x() ) - || !string_parse_float( tokeniser.getToken(), ( *i ).y() ) - || !string_parse_float( tokeniser.getToken(), ( *i ).z() ) ) { + || !string_parse_float( tokeniser.getToken(), ( *i ).y() ) + || !string_parse_float( tokeniser.getToken(), ( *i ).z() ) ) { return false; } } @@ -113,53 +113,53 @@ inline void ControlPoint_testSelect( const Vector3& point, ObservedSelectable& s class ControlPointTransform { -const Matrix4& m_matrix; + const Matrix4& m_matrix; public: -ControlPointTransform( const Matrix4& matrix ) : m_matrix( matrix ){ -} -void operator()( Vector3& point ) const { - matrix4_transform_point( m_matrix, point ); -} + ControlPointTransform( const Matrix4& matrix ) : m_matrix( matrix ){ + } + void operator()( Vector3& point ) const { + matrix4_transform_point( m_matrix, point ); + } }; class ControlPointSnap { -float m_snap; + float m_snap; public: -ControlPointSnap( float snap ) : m_snap( snap ){ -} -void operator()( Vector3& point ) const { - vector3_snap( point, m_snap ); -} + ControlPointSnap( float snap ) : m_snap( snap ){ + } + void operator()( Vector3& point ) const { + vector3_snap( point, m_snap ); + } }; class ControlPointAdd { -RenderablePointVector& m_points; + RenderablePointVector& m_points; public: -ControlPointAdd( RenderablePointVector& points ) : m_points( points ){ -} -void operator()( const Vector3& point ) const { - m_points.push_back( PointVertex( vertex3f_for_vector3( point ), colour_vertex ) ); -} + ControlPointAdd( RenderablePointVector& points ) : m_points( points ){ + } + void operator()( const Vector3& point ) const { + m_points.push_back( PointVertex( vertex3f_for_vector3( point ), colour_vertex ) ); + } }; class ControlPointAddSelected { -RenderablePointVector& m_points; + RenderablePointVector& m_points; public: -ControlPointAddSelected( RenderablePointVector& points ) : m_points( points ){ -} -void operator()( const Vector3& point ) const { - m_points.push_back( PointVertex( vertex3f_for_vector3( point ), colour_selected ) ); -} + ControlPointAddSelected( RenderablePointVector& points ) : m_points( points ){ + } + void operator()( const Vector3& point ) const { + m_points.push_back( PointVertex( vertex3f_for_vector3( point ), colour_selected ) ); + } }; class CurveEditType { public: -Shader* m_controlsShader; -Shader* m_selectedShader; + Shader* m_controlsShader; + Shader* m_selectedShader; }; inline void ControlPoints_write( ControlPoints& controlPoints, const char* key, Entity& entity ){ @@ -172,124 +172,124 @@ inline void ControlPoints_write( ControlPoints& controlPoints, const char* key, class CurveEdit { -SelectionChangeCallback m_selectionChanged; -ControlPoints& m_controlPoints; -typedef Array Selectables; -Selectables m_selectables; + SelectionChangeCallback m_selectionChanged; + ControlPoints& m_controlPoints; + typedef Array Selectables; + Selectables m_selectables; -RenderablePointVector m_controlsRender; -mutable RenderablePointVector m_selectedRender; + RenderablePointVector m_controlsRender; + mutable RenderablePointVector m_selectedRender; public: -typedef Static Type; + typedef Static Type; -CurveEdit( ControlPoints& controlPoints, const SelectionChangeCallback& selectionChanged ) : - m_selectionChanged( selectionChanged ), - m_controlPoints( controlPoints ), - m_controlsRender( GL_POINTS ), - m_selectedRender( GL_POINTS ){ -} + CurveEdit( ControlPoints& controlPoints, const SelectionChangeCallback& selectionChanged ) : + m_selectionChanged( selectionChanged ), + m_controlPoints( controlPoints ), + m_controlsRender( GL_POINTS ), + m_selectedRender( GL_POINTS ){ + } -template -const Functor& forEachSelected( const Functor& functor ){ - ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); - ControlPoints::iterator p = m_controlPoints.begin(); - for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) - { - if ( ( *i ).isSelected() ) { - functor( *p ); + template + const Functor& forEachSelected( const Functor& functor ){ + ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); + ControlPoints::iterator p = m_controlPoints.begin(); + for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) + { + if ( ( *i ).isSelected() ) { + functor( *p ); + } + } + return functor; + } + template + const Functor& forEachSelected( const Functor& functor ) const { + ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); + ControlPoints::const_iterator p = m_controlPoints.begin(); + for ( Selectables::const_iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) + { + if ( ( *i ).isSelected() ) { + functor( *p ); + } + } + return functor; + } + template + const Functor& forEach( const Functor& functor ) const { + for ( ControlPoints::const_iterator i = m_controlPoints.begin(); i != m_controlPoints.end(); ++i ) + { + functor( *i ); + } + return functor; + } + + void testSelect( Selector& selector, SelectionTest& test ){ + ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); + ControlPoints::const_iterator p = m_controlPoints.begin(); + for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) + { + ControlPoint_testSelect( *p, *i, selector, test ); } } - return functor; -} -template -const Functor& forEachSelected( const Functor& functor ) const { - ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); - ControlPoints::const_iterator p = m_controlPoints.begin(); - for ( Selectables::const_iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) - { - if ( ( *i ).isSelected() ) { - functor( *p ); + + bool isSelected() const { + for ( Selectables::const_iterator i = m_selectables.begin(); i != m_selectables.end(); ++i ) + { + if ( ( *i ).isSelected() ) { + return true; + } + } + return false; + } + void setSelected( bool selected ){ + for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i ) + { + ( *i ).setSelected( selected ); } } - return functor; -} -template -const Functor& forEach( const Functor& functor ) const { - for ( ControlPoints::const_iterator i = m_controlPoints.begin(); i != m_controlPoints.end(); ++i ) - { - functor( *i ); - } - return functor; -} -void testSelect( Selector& selector, SelectionTest& test ){ - ASSERT_MESSAGE( m_controlPoints.size() == m_selectables.size(), "curve instance mismatch" ); - ControlPoints::const_iterator p = m_controlPoints.begin(); - for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i, ++p ) - { - ControlPoint_testSelect( *p, *i, selector, test ); + void write( const char* key, Entity& entity ){ + ControlPoints_write( m_controlPoints, key, entity ); } -} -bool isSelected() const { - for ( Selectables::const_iterator i = m_selectables.begin(); i != m_selectables.end(); ++i ) - { - if ( ( *i ).isSelected() ) { - return true; + void transform( const Matrix4& matrix ){ + forEachSelected( ControlPointTransform( matrix ) ); + } + void snapto( float snap ){ + forEachSelected( ControlPointSnap( snap ) ); + } + + void updateSelected() const { + m_selectedRender.clear(); + forEachSelected( ControlPointAddSelected( m_selectedRender ) ); + } + + void renderComponents( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( Type::instance().m_controlsShader, Renderer::eWireframeOnly ); + renderer.SetState( Type::instance().m_controlsShader, Renderer::eFullMaterials ); + renderer.addRenderable( m_controlsRender, localToWorld ); + } + + void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + updateSelected(); + if ( !m_selectedRender.empty() ) { + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.SetState( Type::instance().m_selectedShader, Renderer::eWireframeOnly ); + renderer.SetState( Type::instance().m_selectedShader, Renderer::eFullMaterials ); + renderer.addRenderable( m_selectedRender, localToWorld ); } } - return false; -} -void setSelected( bool selected ){ - for ( Selectables::iterator i = m_selectables.begin(); i != m_selectables.end(); ++i ) - { - ( *i ).setSelected( selected ); + + void curveChanged(){ + m_selectables.resize( m_controlPoints.size(), m_selectionChanged ); + + m_controlsRender.clear(); + m_controlsRender.reserve( m_controlPoints.size() ); + forEach( ControlPointAdd( m_controlsRender ) ); + + m_selectedRender.reserve( m_controlPoints.size() ); } -} - -void write( const char* key, Entity& entity ){ - ControlPoints_write( m_controlPoints, key, entity ); -} - -void transform( const Matrix4& matrix ){ - forEachSelected( ControlPointTransform( matrix ) ); -} -void snapto( float snap ){ - forEachSelected( ControlPointSnap( snap ) ); -} - -void updateSelected() const { - m_selectedRender.clear(); - forEachSelected( ControlPointAddSelected( m_selectedRender ) ); -} - -void renderComponents( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( Type::instance().m_controlsShader, Renderer::eWireframeOnly ); - renderer.SetState( Type::instance().m_controlsShader, Renderer::eFullMaterials ); - renderer.addRenderable( m_controlsRender, localToWorld ); -} - -void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - updateSelected(); - if ( !m_selectedRender.empty() ) { - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.SetState( Type::instance().m_selectedShader, Renderer::eWireframeOnly ); - renderer.SetState( Type::instance().m_selectedShader, Renderer::eFullMaterials ); - renderer.addRenderable( m_selectedRender, localToWorld ); - } -} - -void curveChanged(){ - m_selectables.resize( m_controlPoints.size(), m_selectionChanged ); - - m_controlsRender.clear(); - m_controlsRender.reserve( m_controlPoints.size() ); - forEach( ControlPointAdd( m_controlsRender ) ); - - m_selectedRender.reserve( m_controlPoints.size() ); -} -typedef MemberCaller CurveChangedCaller; + typedef MemberCaller CurveChangedCaller; }; @@ -298,156 +298,156 @@ const int NURBS_degree = 3; class NURBSCurve { -Signal0 m_curveChanged; -Callback m_boundsChanged; + Signal0 m_curveChanged; + Callback m_boundsChanged; public: -ControlPoints m_controlPoints; -ControlPoints m_controlPointsTransformed; -NURBSWeights m_weights; -Knots m_knots; -RenderableCurve m_renderCurve; -AABB m_bounds; + ControlPoints m_controlPoints; + ControlPoints m_controlPointsTransformed; + NURBSWeights m_weights; + Knots m_knots; + RenderableCurve m_renderCurve; + AABB m_bounds; -NURBSCurve( const Callback& boundsChanged ) : m_boundsChanged( boundsChanged ){ -} + NURBSCurve( const Callback& boundsChanged ) : m_boundsChanged( boundsChanged ){ + } -SignalHandlerId connect( const SignalHandler& curveChanged ){ - curveChanged(); - return m_curveChanged.connectLast( curveChanged ); -} -void disconnect( SignalHandlerId id ){ - m_curveChanged.disconnect( id ); -} -void notify(){ - m_curveChanged(); -} + SignalHandlerId connect( const SignalHandler& curveChanged ){ + curveChanged(); + return m_curveChanged.connectLast( curveChanged ); + } + void disconnect( SignalHandlerId id ){ + m_curveChanged.disconnect( id ); + } + void notify(){ + m_curveChanged(); + } -void tesselate(){ - if ( !m_controlPointsTransformed.empty() ) { - const std::size_t numSegments = ( m_controlPointsTransformed.size() - 1 ) * 16; - m_renderCurve.m_vertices.resize( numSegments + 1 ); - m_renderCurve.m_vertices[0].vertex = vertex3f_for_vector3( m_controlPointsTransformed[0] ); - for ( std::size_t i = 1; i < numSegments; ++i ) - { - m_renderCurve.m_vertices[i].vertex = vertex3f_for_vector3( NURBS_evaluate( m_controlPointsTransformed, m_weights, m_knots, NURBS_degree, ( 1.0 / double(numSegments) ) * double(i) ) ); + void tesselate(){ + if ( !m_controlPointsTransformed.empty() ) { + const std::size_t numSegments = ( m_controlPointsTransformed.size() - 1 ) * 16; + m_renderCurve.m_vertices.resize( numSegments + 1 ); + m_renderCurve.m_vertices[0].vertex = vertex3f_for_vector3( m_controlPointsTransformed[0] ); + for ( std::size_t i = 1; i < numSegments; ++i ) + { + m_renderCurve.m_vertices[i].vertex = vertex3f_for_vector3( NURBS_evaluate( m_controlPointsTransformed, m_weights, m_knots, NURBS_degree, ( 1.0 / double(numSegments) ) * double(i) ) ); + } + m_renderCurve.m_vertices[numSegments].vertex = vertex3f_for_vector3( m_controlPointsTransformed[m_controlPointsTransformed.size() - 1] ); + } + else + { + m_renderCurve.m_vertices.clear(); } - m_renderCurve.m_vertices[numSegments].vertex = vertex3f_for_vector3( m_controlPointsTransformed[m_controlPointsTransformed.size() - 1] ); - } - else - { - m_renderCurve.m_vertices.clear(); - } -} - -void curveChanged(){ - tesselate(); - - m_bounds = AABB(); - for ( ControlPoints::iterator i = m_controlPointsTransformed.begin(); i != m_controlPointsTransformed.end(); ++i ) - { - aabb_extend_by_point_safe( m_bounds, ( *i ) ); } - m_boundsChanged(); - notify(); -} + void curveChanged(){ + tesselate(); -bool parseCurve( const char* value ){ - if ( !ControlPoints_parse( m_controlPoints, value ) ) { - return false; + m_bounds = AABB(); + for ( ControlPoints::iterator i = m_controlPointsTransformed.begin(); i != m_controlPointsTransformed.end(); ++i ) + { + aabb_extend_by_point_safe( m_bounds, ( *i ) ); + } + + m_boundsChanged(); + notify(); } - m_weights.resize( m_controlPoints.size() ); - for ( NURBSWeights::iterator i = m_weights.begin(); i != m_weights.end(); ++i ) - { - ( *i ) = 1; + bool parseCurve( const char* value ){ + if ( !ControlPoints_parse( m_controlPoints, value ) ) { + return false; + } + + m_weights.resize( m_controlPoints.size() ); + for ( NURBSWeights::iterator i = m_weights.begin(); i != m_weights.end(); ++i ) + { + ( *i ) = 1; + } + + KnotVector_openUniform( m_knots, m_controlPoints.size(), NURBS_degree ); + + //plotBasisFunction(8, 0, NURBS_degree); + + return true; } - KnotVector_openUniform( m_knots, m_controlPoints.size(), NURBS_degree ); - - //plotBasisFunction(8, 0, NURBS_degree); - - return true; -} - -void curveChanged( const char* value ){ - if ( string_empty( value ) || !parseCurve( value ) ) { - m_controlPoints.resize( 0 ); - m_knots.resize( 0 ); - m_weights.resize( 0 ); + void curveChanged( const char* value ){ + if ( string_empty( value ) || !parseCurve( value ) ) { + m_controlPoints.resize( 0 ); + m_knots.resize( 0 ); + m_weights.resize( 0 ); + } + m_controlPointsTransformed = m_controlPoints; + curveChanged(); } - m_controlPointsTransformed = m_controlPoints; - curveChanged(); -} -typedef MemberCaller1 CurveChangedCaller; + typedef MemberCaller1 CurveChangedCaller; }; class CatmullRomSpline { -Signal0 m_curveChanged; -Callback m_boundsChanged; + Signal0 m_curveChanged; + Callback m_boundsChanged; public: -ControlPoints m_controlPoints; -ControlPoints m_controlPointsTransformed; -RenderableCurve m_renderCurve; -AABB m_bounds; + ControlPoints m_controlPoints; + ControlPoints m_controlPointsTransformed; + RenderableCurve m_renderCurve; + AABB m_bounds; -CatmullRomSpline( const Callback& boundsChanged ) : m_boundsChanged( boundsChanged ){ -} + CatmullRomSpline( const Callback& boundsChanged ) : m_boundsChanged( boundsChanged ){ + } -SignalHandlerId connect( const SignalHandler& curveChanged ){ - curveChanged(); - return m_curveChanged.connectLast( curveChanged ); -} -void disconnect( SignalHandlerId id ){ - m_curveChanged.disconnect( id ); -} -void notify(){ - m_curveChanged(); -} + SignalHandlerId connect( const SignalHandler& curveChanged ){ + curveChanged(); + return m_curveChanged.connectLast( curveChanged ); + } + void disconnect( SignalHandlerId id ){ + m_curveChanged.disconnect( id ); + } + void notify(){ + m_curveChanged(); + } -void tesselate(){ - if ( !m_controlPointsTransformed.empty() ) { - const std::size_t numSegments = ( m_controlPointsTransformed.size() - 1 ) * 16; - m_renderCurve.m_vertices.resize( numSegments + 1 ); - m_renderCurve.m_vertices[0].vertex = vertex3f_for_vector3( m_controlPointsTransformed[0] ); - for ( std::size_t i = 1; i < numSegments; ++i ) - { - m_renderCurve.m_vertices[i].vertex = vertex3f_for_vector3( CatmullRom_evaluate( m_controlPointsTransformed, ( 1.0 / double(numSegments) ) * double(i) ) ); + void tesselate(){ + if ( !m_controlPointsTransformed.empty() ) { + const std::size_t numSegments = ( m_controlPointsTransformed.size() - 1 ) * 16; + m_renderCurve.m_vertices.resize( numSegments + 1 ); + m_renderCurve.m_vertices[0].vertex = vertex3f_for_vector3( m_controlPointsTransformed[0] ); + for ( std::size_t i = 1; i < numSegments; ++i ) + { + m_renderCurve.m_vertices[i].vertex = vertex3f_for_vector3( CatmullRom_evaluate( m_controlPointsTransformed, ( 1.0 / double(numSegments) ) * double(i) ) ); + } + m_renderCurve.m_vertices[numSegments].vertex = vertex3f_for_vector3( m_controlPointsTransformed[m_controlPointsTransformed.size() - 1] ); + } + else + { + m_renderCurve.m_vertices.clear(); } - m_renderCurve.m_vertices[numSegments].vertex = vertex3f_for_vector3( m_controlPointsTransformed[m_controlPointsTransformed.size() - 1] ); - } - else - { - m_renderCurve.m_vertices.clear(); - } -} - -bool parseCurve( const char* value ){ - return ControlPoints_parse( m_controlPoints, value ); -} - -void curveChanged(){ - tesselate(); - - m_bounds = AABB(); - for ( ControlPoints::iterator i = m_controlPointsTransformed.begin(); i != m_controlPointsTransformed.end(); ++i ) - { - aabb_extend_by_point_safe( m_bounds, ( *i ) ); } - m_boundsChanged(); - notify(); -} - -void curveChanged( const char* value ){ - if ( string_empty( value ) || !parseCurve( value ) ) { - m_controlPoints.resize( 0 ); + bool parseCurve( const char* value ){ + return ControlPoints_parse( m_controlPoints, value ); } - m_controlPointsTransformed = m_controlPoints; - curveChanged(); -} -typedef MemberCaller1 CurveChangedCaller; + + void curveChanged(){ + tesselate(); + + m_bounds = AABB(); + for ( ControlPoints::iterator i = m_controlPointsTransformed.begin(); i != m_controlPointsTransformed.end(); ++i ) + { + aabb_extend_by_point_safe( m_bounds, ( *i ) ); + } + + m_boundsChanged(); + notify(); + } + + void curveChanged( const char* value ){ + if ( string_empty( value ) || !parseCurve( value ) ) { + m_controlPoints.resize( 0 ); + } + m_controlPointsTransformed = m_controlPoints; + curveChanged(); + } + typedef MemberCaller1 CurveChangedCaller; }; const char* const curve_Nurbs = "curve_Nurbs"; diff --git a/plugins/entity/doom3group.cpp b/plugins/entity/doom3group.cpp index 4a9dbb16..58ba8451 100644 --- a/plugins/entity/doom3group.cpp +++ b/plugins/entity/doom3group.cpp @@ -60,13 +60,13 @@ inline void PointVertexArray_testSelect( PointVertex* first, std::size_t count, SelectionTest& test, SelectionIntersection& best ){ test.TestLineStrip( - VertexPointer( - reinterpret_cast( &first->vertex ), - sizeof( PointVertex ) - ), - IndexPointer::index_type( count ), - best - ); + VertexPointer( + reinterpret_cast( &first->vertex ), + sizeof( PointVertex ) + ), + IndexPointer::index_type( count ), + best + ); } const char EXCLUDE_NAME[] = "worldspawn"; @@ -75,364 +75,364 @@ class Doom3Group : public Bounded, public Snappable { -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; -TraversableNodeSet m_traverse; -MatrixTransform m_transform; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; + TraversableNodeSet m_traverse; + MatrixTransform m_transform; -SingletonModel m_model; -OriginKey m_originKey; -Vector3 m_origin; + SingletonModel m_model; + OriginKey m_originKey; + Vector3 m_origin; -RotationKey m_rotationKey; -Float9 m_rotation; + RotationKey m_rotationKey; + Float9 m_rotation; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; -TraversableObserverPairRelay m_traverseObservers; -Doom3GroupOrigin m_funcStaticOrigin; -RenderablePivot m_renderOrigin; -mutable Vector3 m_name_origin; -RenderableNamedEntity m_renderName; -ModelSkinKey m_skin; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; + TraversableObserverPairRelay m_traverseObservers; + Doom3GroupOrigin m_funcStaticOrigin; + RenderablePivot m_renderOrigin; + mutable Vector3 m_name_origin; + RenderableNamedEntity m_renderName; + ModelSkinKey m_skin; public: -NURBSCurve m_curveNURBS; -SignalHandlerId m_curveNURBSChanged; -CatmullRomSpline m_curveCatmullRom; -SignalHandlerId m_curveCatmullRomChanged; + NURBSCurve m_curveNURBS; + SignalHandlerId m_curveNURBSChanged; + CatmullRomSpline m_curveCatmullRom; + SignalHandlerId m_curveCatmullRomChanged; private: -mutable AABB m_curveBounds; + mutable AABB m_curveBounds; -Callback m_transformChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_evaluateTransform; -CopiedString m_name; -CopiedString m_modelKey; -bool m_isModel; + CopiedString m_name; + CopiedString m_modelKey; + bool m_isModel; -scene::Traversable* m_traversable; + scene::Traversable* m_traversable; -void construct(){ - default_rotation( m_rotation ); + void construct(){ + default_rotation( m_rotation ); - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - m_keyObservers.insert( "model", Doom3Group::ModelChangedCaller( *this ) ); - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); - m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); - m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); - m_keyObservers.insert( "name", NameChangedCaller( *this ) ); - m_keyObservers.insert( curve_Nurbs, NURBSCurve::CurveChangedCaller( m_curveNURBS ) ); - m_keyObservers.insert( curve_CatmullRomSpline, CatmullRomSpline::CurveChangedCaller( m_curveCatmullRom ) ); - m_keyObservers.insert( "skin", ModelSkinKey::SkinChangedCaller( m_skin ) ); + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + m_keyObservers.insert( "model", Doom3Group::ModelChangedCaller( *this ) ); + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); + m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "name", NameChangedCaller( *this ) ); + m_keyObservers.insert( curve_Nurbs, NURBSCurve::CurveChangedCaller( m_curveNURBS ) ); + m_keyObservers.insert( curve_CatmullRomSpline, CatmullRomSpline::CurveChangedCaller( m_curveCatmullRom ) ); + m_keyObservers.insert( "skin", ModelSkinKey::SkinChangedCaller( m_skin ) ); - m_traverseObservers.attach( m_funcStaticOrigin ); - m_isModel = false; - m_nameKeys.setKeyIsName( keyIsNameDoom3Doom3Group ); - attachTraverse(); - - m_entity.attach( m_keyObservers ); -} -void destroy(){ - m_entity.detach( m_keyObservers ); - - if ( isModel() ) { - detachModel(); - } - else - { - detachTraverse(); - } - - m_traverseObservers.detach( m_funcStaticOrigin ); -} - -void attachModel(){ - m_traversable = &m_model.getTraversable(); - m_model.attach( &m_traverseObservers ); -} -void detachModel(){ - m_traversable = 0; - m_model.detach( &m_traverseObservers ); -} -void attachTraverse(){ - m_traversable = &m_traverse; - m_traverse.attach( &m_traverseObservers ); -} -void detachTraverse(){ - m_traversable = 0; - m_traverse.detach( &m_traverseObservers ); -} - -bool isModel() const { - return m_isModel; -} - -void setIsModel( bool newValue ){ - if ( newValue && !m_isModel ) { - detachTraverse(); - attachModel(); - - m_nameKeys.setKeyIsName( Static::instance().m_keyIsName ); - m_model.modelChanged( m_modelKey.c_str() ); - } - else if ( !newValue && m_isModel ) { - detachModel(); + m_traverseObservers.attach( m_funcStaticOrigin ); + m_isModel = false; + m_nameKeys.setKeyIsName( keyIsNameDoom3Doom3Group ); attachTraverse(); - m_nameKeys.setKeyIsName( keyIsNameDoom3Doom3Group ); + m_entity.attach( m_keyObservers ); } - m_isModel = newValue; - updateTransform(); -} + void destroy(){ + m_entity.detach( m_keyObservers ); -void updateIsModel(){ - setIsModel( !string_equal( m_modelKey.c_str(), m_name.c_str() ) ); -} + if ( isModel() ) { + detachModel(); + } + else + { + detachTraverse(); + } + + m_traverseObservers.detach( m_funcStaticOrigin ); + } + + void attachModel(){ + m_traversable = &m_model.getTraversable(); + m_model.attach( &m_traverseObservers ); + } + void detachModel(){ + m_traversable = 0; + m_model.detach( &m_traverseObservers ); + } + void attachTraverse(){ + m_traversable = &m_traverse; + m_traverse.attach( &m_traverseObservers ); + } + void detachTraverse(){ + m_traversable = 0; + m_traverse.detach( &m_traverseObservers ); + } + + bool isModel() const { + return m_isModel; + } + + void setIsModel( bool newValue ){ + if ( newValue && !m_isModel ) { + detachTraverse(); + attachModel(); + + m_nameKeys.setKeyIsName( Static::instance().m_keyIsName ); + m_model.modelChanged( m_modelKey.c_str() ); + } + else if ( !newValue && m_isModel ) { + detachModel(); + attachTraverse(); + + m_nameKeys.setKeyIsName( keyIsNameDoom3Doom3Group ); + } + m_isModel = newValue; + updateTransform(); + } + + void updateIsModel(){ + setIsModel( !string_equal( m_modelKey.c_str(), m_name.c_str() ) ); + } // vc 2k5 compiler fix #if _MSC_VER >= 1400 public: #endif -void nameChanged( const char* value ){ - m_name = value; - updateIsModel(); -} -typedef MemberCaller1 NameChangedCaller; - -void modelChanged( const char* value ){ - m_modelKey = value; - updateIsModel(); - if ( isModel() ) { - m_model.modelChanged( value ); + void nameChanged( const char* value ){ + m_name = value; + updateIsModel(); } - else - { - m_model.modelChanged( "" ); - } -} -typedef MemberCaller1 ModelChangedCaller; + typedef MemberCaller1 NameChangedCaller; -void updateTransform(){ - m_transform.localToParent() = g_matrix4_identity; - if ( isModel() ) { - matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); - matrix4_multiply_by_matrix4( m_transform.localToParent(), rotation_toMatrix( m_rotation ) ); - } - m_transformChanged(); - if ( !isModel() ) { - m_funcStaticOrigin.originChanged(); - } -} -typedef MemberCaller UpdateTransformCaller; - -void originChanged(){ - m_origin = m_originKey.m_origin; - updateTransform(); -} -typedef MemberCaller OriginChangedCaller; - -void rotationChanged(){ - rotation_assign( m_rotation, m_rotationKey.m_rotation ); - updateTransform(); -} -typedef MemberCaller RotationChangedCaller; - -void skinChanged(){ - if ( isModel() ) { - scene::Node* node = m_model.getNode(); - if ( node != 0 ) { - Node_modelSkinChanged( *node ); + void modelChanged( const char* value ){ + m_modelKey = value; + updateIsModel(); + if ( isModel() ) { + m_model.modelChanged( value ); + } + else + { + m_model.modelChanged( "" ); } } -} -typedef MemberCaller SkinChangedCaller; + typedef MemberCaller1 ModelChangedCaller; + + void updateTransform(){ + m_transform.localToParent() = g_matrix4_identity; + if ( isModel() ) { + matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); + matrix4_multiply_by_matrix4( m_transform.localToParent(), rotation_toMatrix( m_rotation ) ); + } + m_transformChanged(); + if ( !isModel() ) { + m_funcStaticOrigin.originChanged(); + } + } + typedef MemberCaller UpdateTransformCaller; + + void originChanged(){ + m_origin = m_originKey.m_origin; + updateTransform(); + } + typedef MemberCaller OriginChangedCaller; + + void rotationChanged(){ + rotation_assign( m_rotation, m_rotationKey.m_rotation ); + updateTransform(); + } + typedef MemberCaller RotationChangedCaller; + + void skinChanged(){ + if ( isModel() ) { + scene::Node* node = m_model.getNode(); + if ( node != 0 ) { + Node_modelSkinChanged( *node ); + } + } + } + typedef MemberCaller SkinChangedCaller; public: -Doom3Group( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_funcStaticOrigin( m_traverse, m_origin ), - m_name_origin( g_vector3_identity ), - m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), - m_skin( SkinChangedCaller( *this ) ), - m_curveNURBS( boundsChanged ), - m_curveCatmullRom( boundsChanged ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ), - m_traversable( 0 ){ - construct(); -} -Doom3Group( const Doom3Group& other, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_funcStaticOrigin( m_traverse, m_origin ), - m_name_origin( g_vector3_identity ), - m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), - m_skin( SkinChangedCaller( *this ) ), - m_curveNURBS( boundsChanged ), - m_curveCatmullRom( boundsChanged ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ), - m_traversable( 0 ){ - construct(); -} -~Doom3Group(){ - destroy(); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - - m_funcStaticOrigin.enable(); + Doom3Group( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_funcStaticOrigin( m_traverse, m_origin ), + m_name_origin( g_vector3_identity ), + m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), + m_skin( SkinChangedCaller( *this ) ), + m_curveNURBS( boundsChanged ), + m_curveCatmullRom( boundsChanged ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ), + m_traversable( 0 ){ + construct(); } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_funcStaticOrigin.disable(); - - m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); + Doom3Group( const Doom3Group& other, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_funcStaticOrigin( m_traverse, m_origin ), + m_name_origin( g_vector3_identity ), + m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), + m_skin( SkinChangedCaller( *this ) ), + m_curveNURBS( boundsChanged ), + m_curveCatmullRom( boundsChanged ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ), + m_traversable( 0 ){ + construct(); } -} - -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} - -scene::Traversable& getTraversable(){ - return *m_traversable; -} -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} -ModelSkin& getModelSkin(){ - return m_skin.get(); -} - -void attach( scene::Traversable::Observer* observer ){ - m_traverseObservers.attach( *observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_traverseObservers.detach( *observer ); -} - -const AABB& localAABB() const { - m_curveBounds = m_curveNURBS.m_bounds; - aabb_extend_by_aabb_safe( m_curveBounds, m_curveCatmullRom.m_bounds ); - return m_curveBounds; -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { - if ( isModel() && selected ) { - m_renderOrigin.render( renderer, volume, localToWorld ); + ~Doom3Group(){ + destroy(); } - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - if ( !m_curveNURBS.m_renderCurve.m_vertices.empty() ) { - renderer.addRenderable( m_curveNURBS.m_renderCurve, localToWorld ); - } - if ( !m_curveCatmullRom.m_renderCurve.m_vertices.empty() ) { - renderer.addRenderable( m_curveCatmullRom.m_renderCurve, localToWorld ); - } - - if ( m_renderName.excluded_not() - && ( selected || childSelected || ( g_showNames && ( volume.fill() || aabb_fits_view( childBounds, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { - // draw models as usual - if ( isModel() ) { - m_renderName.render( renderer, volume, localToWorld, selected, childSelected ); - } - else{ - // place name in the middle of the "children cloud" - m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); - m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); + m_funcStaticOrigin.enable(); } } -} + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_funcStaticOrigin.disable(); -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { - renderSolid( renderer, volume, localToWorld, selected, childSelected, childBounds ); -} + m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); + } + } -void testSelect( Selector& selector, SelectionTest& test, SelectionIntersection& best ){ - PointVertexArray_testSelect( &m_curveNURBS.m_renderCurve.m_vertices[0], m_curveNURBS.m_renderCurve.m_vertices.size(), test, best ); - PointVertexArray_testSelect( &m_curveCatmullRom.m_renderCurve.m_vertices[0], m_curveCatmullRom.m_renderCurve.m_vertices.size(), test, best ); -} + EntityKeyValues& getEntity(){ + return m_entity; + } + const EntityKeyValues& getEntity() const { + return m_entity; + } -void translate( const Vector3& translation ){ - m_origin = origin_translated( m_origin, translation ); -} -void rotate( const Quaternion& rotation ){ - rotation_rotate( m_rotation, rotation ); -} -void snapto( float snap ){ - m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); - m_originKey.write( &m_entity ); -} -void revertTransform(){ - m_origin = m_originKey.m_origin; - rotation_assign( m_rotation, m_rotationKey.m_rotation ); - m_curveNURBS.m_controlPointsTransformed = m_curveNURBS.m_controlPoints; - m_curveCatmullRom.m_controlPointsTransformed = m_curveCatmullRom.m_controlPoints; -} -void freezeTransform(){ - m_originKey.m_origin = m_origin; - m_originKey.write( &m_entity ); - rotation_assign( m_rotationKey.m_rotation, m_rotation ); - m_rotationKey.write( &m_entity ); - m_curveNURBS.m_controlPoints = m_curveNURBS.m_controlPointsTransformed; - ControlPoints_write( m_curveNURBS.m_controlPoints, curve_Nurbs, m_entity ); - m_curveCatmullRom.m_controlPoints = m_curveCatmullRom.m_controlPointsTransformed; - ControlPoints_write( m_curveCatmullRom.m_controlPoints, curve_CatmullRomSpline, m_entity ); -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateTransform(); - m_curveNURBS.curveChanged(); - m_curveCatmullRom.curveChanged(); -} -typedef MemberCaller TransformChangedCaller; + scene::Traversable& getTraversable(){ + return *m_traversable; + } + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } + ModelSkin& getModelSkin(){ + return m_skin.get(); + } + + void attach( scene::Traversable::Observer* observer ){ + m_traverseObservers.attach( *observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_traverseObservers.detach( *observer ); + } + + const AABB& localAABB() const { + m_curveBounds = m_curveNURBS.m_bounds; + aabb_extend_by_aabb_safe( m_curveBounds, m_curveCatmullRom.m_bounds ); + return m_curveBounds; + } + + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { + if ( isModel() && selected ) { + m_renderOrigin.render( renderer, volume, localToWorld ); + } + + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); + + if ( !m_curveNURBS.m_renderCurve.m_vertices.empty() ) { + renderer.addRenderable( m_curveNURBS.m_renderCurve, localToWorld ); + } + if ( !m_curveCatmullRom.m_renderCurve.m_vertices.empty() ) { + renderer.addRenderable( m_curveCatmullRom.m_renderCurve, localToWorld ); + } + + if ( m_renderName.excluded_not() + && ( selected || childSelected || ( g_showNames && ( volume.fill() || aabb_fits_view( childBounds, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { + // draw models as usual + if ( isModel() ) { + m_renderName.render( renderer, volume, localToWorld, selected, childSelected ); + } + else{ + // place name in the middle of the "children cloud" + m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); + m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); + } + } + } + + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { + renderSolid( renderer, volume, localToWorld, selected, childSelected, childBounds ); + } + + void testSelect( Selector& selector, SelectionTest& test, SelectionIntersection& best ){ + PointVertexArray_testSelect( &m_curveNURBS.m_renderCurve.m_vertices[0], m_curveNURBS.m_renderCurve.m_vertices.size(), test, best ); + PointVertexArray_testSelect( &m_curveCatmullRom.m_renderCurve.m_vertices[0], m_curveCatmullRom.m_renderCurve.m_vertices.size(), test, best ); + } + + void translate( const Vector3& translation ){ + m_origin = origin_translated( m_origin, translation ); + } + void rotate( const Quaternion& rotation ){ + rotation_rotate( m_rotation, rotation ); + } + void snapto( float snap ){ + m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); + m_originKey.write( &m_entity ); + } + void revertTransform(){ + m_origin = m_originKey.m_origin; + rotation_assign( m_rotation, m_rotationKey.m_rotation ); + m_curveNURBS.m_controlPointsTransformed = m_curveNURBS.m_controlPoints; + m_curveCatmullRom.m_controlPointsTransformed = m_curveCatmullRom.m_controlPoints; + } + void freezeTransform(){ + m_originKey.m_origin = m_origin; + m_originKey.write( &m_entity ); + rotation_assign( m_rotationKey.m_rotation, m_rotation ); + m_rotationKey.write( &m_entity ); + m_curveNURBS.m_controlPoints = m_curveNURBS.m_controlPointsTransformed; + ControlPoints_write( m_curveNURBS.m_controlPoints, curve_Nurbs, m_entity ); + m_curveCatmullRom.m_controlPoints = m_curveCatmullRom.m_controlPointsTransformed; + ControlPoints_write( m_curveCatmullRom.m_controlPoints, curve_CatmullRomSpline, m_entity ); + } + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateTransform(); + m_curveNURBS.curveChanged(); + m_curveCatmullRom.curveChanged(); + } + typedef MemberCaller TransformChangedCaller; }; class ControlPointAddBounds { -AABB& m_bounds; + AABB& m_bounds; public: -ControlPointAddBounds( AABB& bounds ) : m_bounds( bounds ){ -} -void operator()( const Vector3& point ) const { - aabb_extend_by_point_safe( m_bounds, point ); -} + ControlPointAddBounds( AABB& bounds ) : m_bounds( bounds ){ + } + void operator()( const Vector3& point ) const { + aabb_extend_by_point_safe( m_bounds, point ); + } }; class Doom3GroupInstance : @@ -444,160 +444,160 @@ class Doom3GroupInstance : public ComponentEditable, public ComponentSnappable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - -Doom3Group& m_contained; -CurveEdit m_curveNURBS; -CurveEdit m_curveCatmullRom; -mutable AABB m_aabb_component; -public: - -typedef LazyStatic StaticTypeCasts; - - -Bounded& get( NullType){ - return m_contained; -} - -STRING_CONSTANT( Name, "Doom3GroupInstance" ); - -Doom3GroupInstance( const scene::Path& path, scene::Instance* parent, Doom3Group& contained ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), - TransformModifier( Doom3Group::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), - m_contained( contained ), - m_curveNURBS( m_contained.m_curveNURBS.m_controlPointsTransformed, SelectionChangedComponentCaller( *this ) ), - m_curveCatmullRom( m_contained.m_curveCatmullRom.m_controlPointsTransformed, SelectionChangedComponentCaller( *this ) ){ - m_contained.instanceAttach( Instance::path() ); - m_contained.m_curveNURBSChanged = m_contained.m_curveNURBS.connect( CurveEdit::CurveChangedCaller( m_curveNURBS ) ); - m_contained.m_curveCatmullRomChanged = m_contained.m_curveCatmullRom.connect( CurveEdit::CurveChangedCaller( m_curveCatmullRom ) ); - - StaticRenderableConnectionLines::instance().attach( *this ); -} -~Doom3GroupInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); - - m_contained.m_curveCatmullRom.disconnect( m_contained.m_curveCatmullRomChanged ); - m_contained.m_curveNURBS.disconnect( m_contained.m_curveNURBSChanged ); - m_contained.instanceDetach( Instance::path() ); -} -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); - - m_curveNURBS.renderComponentsSelected( renderer, volume, localToWorld() ); - m_curveCatmullRom.renderComponentsSelected( renderer, volume, localToWorld() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); - - m_curveNURBS.renderComponentsSelected( renderer, volume, localToWorld() ); - m_curveCatmullRom.renderComponentsSelected( renderer, volume, localToWorld() ); -} -void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { - if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { - m_curveNURBS.renderComponents( renderer, volume, localToWorld() ); - m_curveCatmullRom.renderComponents( renderer, volume, localToWorld() ); - } -} - -void testSelect( Selector& selector, SelectionTest& test ){ - test.BeginMesh( localToWorld() ); - SelectionIntersection best; - - m_contained.testSelect( selector, test, best ); - - if ( best.valid() ) { - Selector_add( selector, getSelectable(), best ); - } -} - -bool isSelectedComponents() const { - return m_curveNURBS.isSelected() || m_curveCatmullRom.isSelected(); -} -void setSelectedComponents( bool selected, SelectionSystem::EComponentMode mode ){ - if ( mode == SelectionSystem::eVertex ) { - m_curveNURBS.setSelected( selected ); - m_curveCatmullRom.setSelected( selected ); - } -} -void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ - if ( mode == SelectionSystem::eVertex ) { - test.BeginMesh( localToWorld() ); - m_curveNURBS.testSelect( selector, test ); - m_curveCatmullRom.testSelect( selector, test ); - } -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { -} - -void transformComponents( const Matrix4& matrix ){ - if ( m_curveNURBS.isSelected() ) { - m_curveNURBS.transform( matrix ); - } - if ( m_curveCatmullRom.isSelected() ) { - m_curveCatmullRom.transform( matrix ); - } -} - -const AABB& getSelectedComponentsBounds() const { - m_aabb_component = AABB(); - m_curveNURBS.forEachSelected( ControlPointAddBounds( m_aabb_component ) ); - m_curveCatmullRom.forEachSelected( ControlPointAddBounds( m_aabb_component ) ); - return m_aabb_component; -} -void gatherSelectedComponents( const Vector3Callback& callback ) const { -} - -void snapComponents( float snap ){ - if ( m_curveNURBS.isSelected() ) { - m_curveNURBS.snapto( snap ); - m_curveNURBS.write( curve_Nurbs, m_contained.getEntity() ); - } - if ( m_curveCatmullRom.isSelected() ) { - m_curveCatmullRom.snapto( snap ); - m_curveCatmullRom.write( curve_CatmullRomSpline, m_contained.getEntity() ); - } -} - -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); - m_contained.rotate( getRotation() ); - } - else + class TypeCasts { - transformComponents( calculateTransform() ); - } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -void selectionChangedComponent( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); - GlobalSelectionSystem().onComponentSelection( *this, selectable ); -} -typedef MemberCaller1 SelectionChangedComponentCaller; + Doom3Group& m_contained; + CurveEdit m_curveNURBS; + CurveEdit m_curveCatmullRom; + mutable AABB m_aabb_component; +public: + + typedef LazyStatic StaticTypeCasts; + + + Bounded& get( NullType){ + return m_contained; + } + + STRING_CONSTANT( Name, "Doom3GroupInstance" ); + + Doom3GroupInstance( const scene::Path& path, scene::Instance* parent, Doom3Group& contained ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), + TransformModifier( Doom3Group::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), + m_contained( contained ), + m_curveNURBS( m_contained.m_curveNURBS.m_controlPointsTransformed, SelectionChangedComponentCaller( *this ) ), + m_curveCatmullRom( m_contained.m_curveCatmullRom.m_controlPointsTransformed, SelectionChangedComponentCaller( *this ) ){ + m_contained.instanceAttach( Instance::path() ); + m_contained.m_curveNURBSChanged = m_contained.m_curveNURBS.connect( CurveEdit::CurveChangedCaller( m_curveNURBS ) ); + m_contained.m_curveCatmullRomChanged = m_contained.m_curveCatmullRom.connect( CurveEdit::CurveChangedCaller( m_curveCatmullRom ) ); + + StaticRenderableConnectionLines::instance().attach( *this ); + } + ~Doom3GroupInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); + + m_contained.m_curveCatmullRom.disconnect( m_contained.m_curveCatmullRomChanged ); + m_contained.m_curveNURBS.disconnect( m_contained.m_curveNURBSChanged ); + m_contained.instanceDetach( Instance::path() ); + } + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); + + m_curveNURBS.renderComponentsSelected( renderer, volume, localToWorld() ); + m_curveCatmullRom.renderComponentsSelected( renderer, volume, localToWorld() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); + + m_curveNURBS.renderComponentsSelected( renderer, volume, localToWorld() ); + m_curveCatmullRom.renderComponentsSelected( renderer, volume, localToWorld() ); + } + void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { + if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { + m_curveNURBS.renderComponents( renderer, volume, localToWorld() ); + m_curveCatmullRom.renderComponents( renderer, volume, localToWorld() ); + } + } + + void testSelect( Selector& selector, SelectionTest& test ){ + test.BeginMesh( localToWorld() ); + SelectionIntersection best; + + m_contained.testSelect( selector, test, best ); + + if ( best.valid() ) { + Selector_add( selector, getSelectable(), best ); + } + } + + bool isSelectedComponents() const { + return m_curveNURBS.isSelected() || m_curveCatmullRom.isSelected(); + } + void setSelectedComponents( bool selected, SelectionSystem::EComponentMode mode ){ + if ( mode == SelectionSystem::eVertex ) { + m_curveNURBS.setSelected( selected ); + m_curveCatmullRom.setSelected( selected ); + } + } + void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ + if ( mode == SelectionSystem::eVertex ) { + test.BeginMesh( localToWorld() ); + m_curveNURBS.testSelect( selector, test ); + m_curveCatmullRom.testSelect( selector, test ); + } + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { + } + + void transformComponents( const Matrix4& matrix ){ + if ( m_curveNURBS.isSelected() ) { + m_curveNURBS.transform( matrix ); + } + if ( m_curveCatmullRom.isSelected() ) { + m_curveCatmullRom.transform( matrix ); + } + } + + const AABB& getSelectedComponentsBounds() const { + m_aabb_component = AABB(); + m_curveNURBS.forEachSelected( ControlPointAddBounds( m_aabb_component ) ); + m_curveCatmullRom.forEachSelected( ControlPointAddBounds( m_aabb_component ) ); + return m_aabb_component; + } + void gatherSelectedComponents( const Vector3Callback& callback ) const { + } + + void snapComponents( float snap ){ + if ( m_curveNURBS.isSelected() ) { + m_curveNURBS.snapto( snap ); + m_curveNURBS.write( curve_Nurbs, m_contained.getEntity() ); + } + if ( m_curveCatmullRom.isSelected() ) { + m_curveCatmullRom.snapto( snap ); + m_curveCatmullRom.write( curve_CatmullRomSpline, m_contained.getEntity() ); + } + } + + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + m_contained.rotate( getRotation() ); + } + else + { + transformComponents( calculateTransform() ); + } + } + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; + + void selectionChangedComponent( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); + GlobalSelectionSystem().onComponentSelection( *this, selectable ); + } + typedef MemberCaller1 SelectionChangedComponentCaller; }; class Doom3GroupNode : @@ -606,111 +606,111 @@ class Doom3GroupNode : public scene::Cloneable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -Doom3Group m_contained; + scene::Node m_node; + InstanceSet m_instances; + Doom3Group m_contained; -void construct(){ - m_contained.attach( this ); -} -void destroy(){ - m_contained.detach( this ); -} + void construct(){ + m_contained.attach( this ); + } + void destroy(){ + m_contained.detach( this ); + } public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_contained.getTraversable(); -} -Snappable& get( NullType){ - return m_contained; -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} -ModelSkin& get( NullType){ - return m_contained.getModelSkin(); -} + scene::Traversable& get( NullType){ + return m_contained.getTraversable(); + } + Snappable& get( NullType){ + return m_contained; + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); + } + ModelSkin& get( NullType){ + return m_contained.getModelSkin(); + } -Doom3GroupNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -Doom3GroupNode( const Doom3GroupNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -~Doom3GroupNode(){ - destroy(); -} + Doom3GroupNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + Doom3GroupNode( const Doom3GroupNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + ~Doom3GroupNode(){ + destroy(); + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Node& clone() const { - return ( new Doom3GroupNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new Doom3GroupNode( *this ) )->node(); + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new Doom3GroupInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new Doom3GroupInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; void Doom3Group_construct(){ diff --git a/plugins/entity/eclassmodel.cpp b/plugins/entity/eclassmodel.cpp index 385cc5e2..25e2cb29 100644 --- a/plugins/entity/eclassmodel.cpp +++ b/plugins/entity/eclassmodel.cpp @@ -61,312 +61,312 @@ inline void read_aabb( AABB& aabb, const EntityClass& eclass ){ class EclassModel : public Snappable { -MatrixTransform m_transform; -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; + MatrixTransform m_transform; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; -OriginKey m_originKey; -Vector3 m_origin; -AngleKey m_angleKey; -float m_angle; -RotationKey m_rotationKey; -Float9 m_rotation; -SingletonModel m_model; + OriginKey m_originKey; + Vector3 m_origin; + AngleKey m_angleKey; + float m_angle; + RotationKey m_rotationKey; + Float9 m_rotation; + SingletonModel m_model; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; -RenderablePivot m_renderOrigin; -RenderableNamedEntity m_renderName; -ModelSkinKey m_skin; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; + RenderablePivot m_renderOrigin; + RenderableNamedEntity m_renderName; + ModelSkinKey m_skin; -AABB m_aabb_local; -RenderableWireframeAABB m_aabb_wire; -Matrix4 m_translation; + AABB m_aabb_local; + RenderableWireframeAABB m_aabb_wire; + Matrix4 m_translation; -Callback m_transformChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_evaluateTransform; -void construct(){ - read_aabb( m_aabb_local, m_entity.getEntityClass() ); + void construct(){ + read_aabb( m_aabb_local, m_entity.getEntityClass() ); - default_rotation( m_rotation ); + default_rotation( m_rotation ); - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - if ( g_gameType == eGameTypeDoom3 ) { - m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); - m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + if ( g_gameType == eGameTypeDoom3 ) { + m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); + } + else + { + m_keyObservers.insert( "angle", AngleKey::AngleChangedCaller( m_angleKey ) ); + } + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); } - else - { - m_keyObservers.insert( "angle", AngleKey::AngleChangedCaller( m_angleKey ) ); - } - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); -} // vc 2k5 compiler fix #if _MSC_VER >= 1400 public: #endif -void updateTransform(){ - m_transform.localToParent() = g_matrix4_identity; - matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); + void updateTransform(){ + m_transform.localToParent() = g_matrix4_identity; + matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); - m_translation = m_transform.localToParent(); + m_translation = m_transform.localToParent(); - if ( g_gameType == eGameTypeDoom3 ) { - matrix4_multiply_by_matrix4( m_transform.localToParent(), rotation_toMatrix( m_rotation ) ); + if ( g_gameType == eGameTypeDoom3 ) { + matrix4_multiply_by_matrix4( m_transform.localToParent(), rotation_toMatrix( m_rotation ) ); + } + else + { + matrix4_multiply_by_matrix4( m_transform.localToParent(), matrix4_rotation_for_z_degrees( m_angle ) ); + } + + m_transformChanged(); } - else - { - matrix4_multiply_by_matrix4( m_transform.localToParent(), matrix4_rotation_for_z_degrees( m_angle ) ); + typedef MemberCaller UpdateTransformCaller; + + void originChanged(){ + m_origin = m_originKey.m_origin; + updateTransform(); } - - m_transformChanged(); -} -typedef MemberCaller UpdateTransformCaller; - -void originChanged(){ - m_origin = m_originKey.m_origin; - updateTransform(); -} -typedef MemberCaller OriginChangedCaller; -void angleChanged(){ - m_angle = m_angleKey.m_angle; - updateTransform(); -} -typedef MemberCaller AngleChangedCaller; -void rotationChanged(){ - rotation_assign( m_rotation, m_rotationKey.m_rotation ); - updateTransform(); -} -typedef MemberCaller RotationChangedCaller; - -void skinChanged(){ - scene::Node* node = m_model.getNode(); - if ( node != 0 ) { - Node_modelSkinChanged( *node ); + typedef MemberCaller OriginChangedCaller; + void angleChanged(){ + m_angle = m_angleKey.m_angle; + updateTransform(); } -} -typedef MemberCaller SkinChangedCaller; + typedef MemberCaller AngleChangedCaller; + void rotationChanged(){ + rotation_assign( m_rotation, m_rotationKey.m_rotation ); + updateTransform(); + } + typedef MemberCaller RotationChangedCaller; + + void skinChanged(){ + scene::Node* node = m_model.getNode(); + if ( node != 0 ) { + Node_modelSkinChanged( *node ); + } + } + typedef MemberCaller SkinChangedCaller; public: -EclassModel( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_angleKey( AngleChangedCaller( *this ) ), - m_angle( ANGLEKEY_IDENTITY ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_renderName( m_named, g_vector3_identity ), - m_skin( SkinChangedCaller( *this ) ), - m_aabb_wire( m_aabb_local ), - m_translation( g_matrix4_identity ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -EclassModel( const EclassModel& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_angleKey( AngleChangedCaller( *this ) ), - m_angle( ANGLEKEY_IDENTITY ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_renderName( m_named, g_vector3_identity ), - m_skin( SkinChangedCaller( *this ) ), - m_aabb_wire( m_aabb_local ), - m_translation( g_matrix4_identity ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.attach( m_keyObservers ); - m_model.modelChanged( m_entity.getEntityClass().modelpath() ); - m_skin.skinChanged( m_entity.getEntityClass().skin() ); + EclassModel( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_angleKey( AngleChangedCaller( *this ) ), + m_angle( ANGLEKEY_IDENTITY ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_renderName( m_named, g_vector3_identity ), + m_skin( SkinChangedCaller( *this ) ), + m_aabb_wire( m_aabb_local ), + m_translation( g_matrix4_identity ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_skin.skinChanged( "" ); - m_model.modelChanged( "" ); - m_entity.detach( m_keyObservers ); - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); + EclassModel( const EclassModel& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_angleKey( AngleChangedCaller( *this ) ), + m_angle( ANGLEKEY_IDENTITY ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_renderName( m_named, g_vector3_identity ), + m_skin( SkinChangedCaller( *this ) ), + m_aabb_wire( m_aabb_local ), + m_translation( g_matrix4_identity ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.attach( m_keyObservers ); + m_model.modelChanged( m_entity.getEntityClass().modelpath() ); + m_skin.skinChanged( m_entity.getEntityClass().skin() ); + } + } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_skin.skinChanged( "" ); + m_model.modelChanged( "" ); + m_entity.detach( m_keyObservers ); + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); + } + } -scene::Traversable& getTraversable(){ - return m_model.getTraversable(); -} -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} -ModelSkin& getModelSkin(){ - return m_skin.get(); -} + EntityKeyValues& getEntity(){ + return m_entity; + } + const EntityKeyValues& getEntity() const { + return m_entity; + } -void attach( scene::Traversable::Observer* observer ){ - m_model.attach( observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_model.detach( observer ); -} + scene::Traversable& getTraversable(){ + return m_model.getTraversable(); + } + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } + ModelSkin& getModelSkin(){ + return m_skin.get(); + } -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - if ( selected || g_showBboxes ) { - if( selected ) - m_renderOrigin.render( renderer, volume, localToWorld ); + void attach( scene::Traversable::Observer* observer ){ + m_model.attach( observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_model.detach( observer ); + } - renderer.PushState(); - renderer.Highlight( Renderer::ePrimitive, false ); + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + if ( selected || g_showBboxes ) { + if( selected ) + m_renderOrigin.render( renderer, volume, localToWorld ); + + renderer.PushState(); + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); + renderer.addRenderable( m_aabb_wire, m_translation ); + renderer.PopState(); + } renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); - renderer.addRenderable( m_aabb_wire, m_translation ); - renderer.PopState(); + if ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( m_aabb_local, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) { + m_renderName.render( renderer, volume, localToWorld, selected ); + } } - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - if ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( m_aabb_local, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) { - m_renderName.render( renderer, volume, localToWorld, selected ); + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderSolid( renderer, volume, localToWorld, selected ); } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderSolid( renderer, volume, localToWorld, selected ); -} -void translate( const Vector3& translation ){ - m_origin = origin_translated( m_origin, translation ); -} -void rotate( const Quaternion& rotation ){ - if ( g_gameType == eGameTypeDoom3 ) { - rotation_rotate( m_rotation, rotation ); + void translate( const Vector3& translation ){ + m_origin = origin_translated( m_origin, translation ); } - else - { - m_angle = angle_rotated( m_angle, rotation ); + void rotate( const Quaternion& rotation ){ + if ( g_gameType == eGameTypeDoom3 ) { + rotation_rotate( m_rotation, rotation ); + } + else + { + m_angle = angle_rotated( m_angle, rotation ); + } } -} -void snapto( float snap ){ - m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); - m_originKey.write( &m_entity ); -} -void revertTransform(){ - m_origin = m_originKey.m_origin; - if ( g_gameType == eGameTypeDoom3 ) { - rotation_assign( m_rotation, m_rotationKey.m_rotation ); + void snapto( float snap ){ + m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); + m_originKey.write( &m_entity ); } - else - { - m_angle = m_angleKey.m_angle; + void revertTransform(){ + m_origin = m_originKey.m_origin; + if ( g_gameType == eGameTypeDoom3 ) { + rotation_assign( m_rotation, m_rotationKey.m_rotation ); + } + else + { + m_angle = m_angleKey.m_angle; + } } -} -void freezeTransform(){ - m_originKey.m_origin = m_origin; - m_originKey.write( &m_entity ); - if ( g_gameType == eGameTypeDoom3 ) { - rotation_assign( m_rotationKey.m_rotation, m_rotation ); - m_rotationKey.write( &m_entity ); + void freezeTransform(){ + m_originKey.m_origin = m_origin; + m_originKey.write( &m_entity ); + if ( g_gameType == eGameTypeDoom3 ) { + rotation_assign( m_rotationKey.m_rotation, m_rotation ); + m_rotationKey.write( &m_entity ); + } + else if( m_angleKey.m_angle != m_angle ) + { + m_angleKey.m_angle = m_angle; + m_angleKey.write( &m_entity ); + } } - else if( m_angleKey.m_angle != m_angle ) - { - m_angleKey.m_angle = m_angle; - m_angleKey.write( &m_entity ); + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateTransform(); } -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateTransform(); -} -typedef MemberCaller TransformChangedCaller; + typedef MemberCaller TransformChangedCaller; }; class EclassModelInstance : public TargetableInstance, public TransformModifier, public Renderable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - -EclassModel& m_contained; -public: -typedef LazyStatic StaticTypeCasts; - -STRING_CONSTANT( Name, "EclassModelInstance" ); - -EclassModelInstance( const scene::Path& path, scene::Instance* parent, EclassModel& contained ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), - TransformModifier( EclassModel::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), - m_contained( contained ){ - m_contained.instanceAttach( Instance::path() ); - - StaticRenderableConnectionLines::instance().attach( *this ); -} -~EclassModelInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); - - m_contained.instanceDetach( Instance::path() ); -} -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} - -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); - if( getRotation() != c_quaternion_identity ){ - m_contained.rotate( getRotation() ); + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + EclassModel& m_contained; +public: + typedef LazyStatic StaticTypeCasts; + + STRING_CONSTANT( Name, "EclassModelInstance" ); + + EclassModelInstance( const scene::Path& path, scene::Instance* parent, EclassModel& contained ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), + TransformModifier( EclassModel::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), + m_contained( contained ){ + m_contained.instanceAttach( Instance::path() ); + + StaticRenderableConnectionLines::instance().attach( *this ); } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; + ~EclassModelInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); + + m_contained.instanceDetach( Instance::path() ); + } + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + if( getRotation() != c_quaternion_identity ){ + m_contained.rotate( getRotation() ); + } + + } + } + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; }; class EclassModelNode : @@ -375,110 +375,110 @@ class EclassModelNode : public scene::Cloneable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -EclassModel m_contained; + scene::Node m_node; + InstanceSet m_instances; + EclassModel m_contained; -void construct(){ - m_contained.attach( this ); -} -void destroy(){ - m_contained.detach( this ); -} + void construct(){ + m_contained.attach( this ); + } + void destroy(){ + m_contained.detach( this ); + } public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_contained.getTraversable(); -} -Snappable& get( NullType){ - return m_contained; -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} -ModelSkin& get( NullType){ - return m_contained.getModelSkin(); -} + scene::Traversable& get( NullType){ + return m_contained.getTraversable(); + } + Snappable& get( NullType){ + return m_contained; + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); + } + ModelSkin& get( NullType){ + return m_contained.getModelSkin(); + } -EclassModelNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -EclassModelNode( const EclassModelNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -~EclassModelNode(){ - destroy(); -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + EclassModelNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + EclassModelNode( const EclassModelNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + ~EclassModelNode(){ + destroy(); + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -scene::Node& clone() const { - return ( new EclassModelNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new EclassModelNode( *this ) )->node(); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new EclassModelInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new EclassModelInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; scene::Node& New_EclassModel( EntityClass* eclass ){ diff --git a/plugins/entity/entity.cpp b/plugins/entity/entity.cpp index 60adceff..c783e5d2 100644 --- a/plugins/entity/entity.cpp +++ b/plugins/entity/entity.cpp @@ -55,7 +55,7 @@ inline scene::Node& entity_for_eclass( EntityClass* eclass ){ return New_MiscModel( eclass ); } else if ( classname_equal( eclass->name(), "light" ) - || classname_equal( eclass->name(), "lightJunior" ) ) { + || classname_equal( eclass->name(), "lightJunior" ) ) { return New_Light( eclass ); } if ( !eclass->fixedsize ) { @@ -90,9 +90,9 @@ inline scene::Node& node_for_eclass( EntityClass* eclass ){ Node_getEntity( node )->setKeyValue( "classname", eclass->name() ); if ( g_gameType == eGameTypeDoom3 - && string_not_empty( eclass->name() ) - && !string_equal( eclass->name(), "worldspawn" ) - && !string_equal( eclass->name(), "UNKNOWN_CLASS" ) ) { + && string_not_empty( eclass->name() ) + && !string_equal( eclass->name(), "worldspawn" ) + && !string_equal( eclass->name(), "UNKNOWN_CLASS" ) ) { char buffer[1024]; strcpy( buffer, eclass->name() ); strcat( buffer, "_1" ); @@ -126,27 +126,27 @@ bool g_stupidQuakeBug = false; class ConnectEntities { public: -Entity* m_e1; -Entity* m_e2; -int m_index; -ConnectEntities( Entity* e1, Entity* e2, int index ) : m_e1( e1 ), m_e2( e2 ), m_index( index ){ -} -const char *keyname(){ - StringOutputStream key( 16 ); - if ( m_index <= 0 ) { - return "target"; + Entity* m_e1; + Entity* m_e2; + int m_index; + ConnectEntities( Entity* e1, Entity* e2, int index ) : m_e1( e1 ), m_e2( e2 ), m_index( index ){ } - if ( m_index == 1 ) { - return "killtarget"; + const char *keyname(){ + StringOutputStream key( 16 ); + if ( m_index <= 0 ) { + return "target"; + } + if ( m_index == 1 ) { + return "killtarget"; + } + key << "target" << m_index; + return key.c_str(); } - key << "target" << m_index; - return key.c_str(); -} -void connect( const char* name ){ - m_e1->setKeyValue( keyname(), name ); - m_e2->setKeyValue( "targetname", name ); -} -typedef MemberCaller1 ConnectCaller; + void connect( const char* name ){ + m_e1->setKeyValue( keyname(), name ); + m_e2->setKeyValue( "targetname", name ); + } + typedef MemberCaller1 ConnectCaller; }; inline Entity* ScenePath_getEntity( const scene::Path& path ){ @@ -160,93 +160,70 @@ inline Entity* ScenePath_getEntity( const scene::Path& path ){ class Quake3EntityCreator : public EntityCreator { public: -scene::Node& createEntity( EntityClass* eclass ){ - return node_for_eclass( eclass ); -} -void setKeyValueChangedFunc( KeyValueChangedFunc func ){ - EntityKeyValues::setKeyValueChangedFunc( func ); -} -void setCounter( Counter* counter ){ - EntityKeyValues::setCounter( counter ); -} -void connectEntities( const scene::Path& path, const scene::Path& targetPath, int index ){ - Entity* e1 = ScenePath_getEntity( path ); - Entity* e2 = ScenePath_getEntity( targetPath ); - - if ( e1 == 0 || e2 == 0 ) { - globalErrorStream() << "entityConnectSelected: both of the selected instances must be an entity\n"; - return; + scene::Node& createEntity( EntityClass* eclass ){ + return node_for_eclass( eclass ); } - - if ( e1 == e2 ) { - globalErrorStream() << "entityConnectSelected: the selected instances must not both be from the same entity\n"; - return; + void setKeyValueChangedFunc( KeyValueChangedFunc func ){ + EntityKeyValues::setKeyValueChangedFunc( func ); } + void setCounter( Counter* counter ){ + EntityKeyValues::setCounter( counter ); + } + void connectEntities( const scene::Path& path, const scene::Path& targetPath, int index ){ + Entity* e1 = ScenePath_getEntity( path ); + Entity* e2 = ScenePath_getEntity( targetPath ); - - UndoableCommand undo( "entityConnectSelected" ); - - if ( g_gameType == eGameTypeDoom3 ) { - StringOutputStream key( 16 ); - if ( index >= 0 ) { - key << "target"; - if ( index != 0 ) { - key << index; - } - e1->setKeyValue( key.c_str(), e2->getKeyValue( "name" ) ); - key.clear(); + if ( e1 == 0 || e2 == 0 ) { + globalErrorStream() << "entityConnectSelected: both of the selected instances must be an entity\n"; + return; } - else - { - for ( unsigned int i = 0; ; ++i ) - { + + if ( e1 == e2 ) { + globalErrorStream() << "entityConnectSelected: the selected instances must not both be from the same entity\n"; + return; + } + + + UndoableCommand undo( "entityConnectSelected" ); + + if ( g_gameType == eGameTypeDoom3 ) { + StringOutputStream key( 16 ); + if ( index >= 0 ) { key << "target"; - if ( i != 0 ) { - key << i; - } - const char* value = e1->getKeyValue( key.c_str() ); - if ( string_empty( value ) ) { - e1->setKeyValue( key.c_str(), e2->getKeyValue( "name" ) ); - break; + if ( index != 0 ) { + key << index; } + e1->setKeyValue( key.c_str(), e2->getKeyValue( "name" ) ); key.clear(); } - } - } - else - { - ConnectEntities connector( e1, e2, index ); - //killconnect - if( index == 1 ){ - const char* value = e2->getKeyValue( "targetname" ); - if ( !string_empty( value ) ) { - connector.connect( value ); - } else { - const char* type = e2->getKeyValue( "classname" ); - if ( string_empty( type ) ) { - type = "t"; + for ( unsigned int i = 0; ; ++i ) + { + key << "target"; + if ( i != 0 ) { + key << i; + } + const char* value = e1->getKeyValue( key.c_str() ); + if ( string_empty( value ) ) { + e1->setKeyValue( key.c_str(), e2->getKeyValue( "name" ) ); + break; + } + key.clear(); } - StringOutputStream key( 64 ); - key << type << "1"; - GlobalNamespace().makeUnique( key.c_str(), ConnectEntities::ConnectCaller( connector ) ); } } - //normal connect - else{ - //prioritize existing target key - //checking, if ent got other connected ones already, could be better solution - const char* value = e1->getKeyValue( "target" ); - if ( !string_empty( value ) ) { - connector.connect( value ); - } - else{ - value = e2->getKeyValue( "targetname" ); + else + { + ConnectEntities connector( e1, e2, index ); + //killconnect + if( index == 1 ){ + const char* value = e2->getKeyValue( "targetname" ); if ( !string_empty( value ) ) { connector.connect( value ); } - else{ + else + { const char* type = e2->getKeyValue( "classname" ); if ( string_empty( type ) ) { type = "t"; @@ -256,62 +233,85 @@ void connectEntities( const scene::Path& path, const scene::Path& targetPath, in GlobalNamespace().makeUnique( key.c_str(), ConnectEntities::ConnectCaller( connector ) ); } } + //normal connect + else{ + //prioritize existing target key + //checking, if ent got other connected ones already, could be better solution + const char* value = e1->getKeyValue( "target" ); + if ( !string_empty( value ) ) { + connector.connect( value ); + } + else{ + value = e2->getKeyValue( "targetname" ); + if ( !string_empty( value ) ) { + connector.connect( value ); + } + else{ + const char* type = e2->getKeyValue( "classname" ); + if ( string_empty( type ) ) { + type = "t"; + } + StringOutputStream key( 64 ); + key << type << "1"; + GlobalNamespace().makeUnique( key.c_str(), ConnectEntities::ConnectCaller( connector ) ); + } + } + } } + SceneChangeNotify(); + } + void setLightRadii( bool lightRadii ){ + g_lightRadii = lightRadii; + } + bool getLightRadii(){ + return g_lightRadii; + } + void setShowNames( bool showNames ){ + g_showNames = showNames; + } + bool getShowNames(){ + return g_showNames; + } + void setShowBboxes( bool showBboxes ){ + g_showBboxes = showBboxes; + } + bool getShowBboxes(){ + return g_showBboxes; + } + void setShowConnections( bool showConnections ){ + g_showConnections = showConnections; + } + bool getShowConnections(){ + return g_showConnections; + } + void setShowNamesDist( int dist ){ + g_showNamesDist = dist; + } + int getShowNamesDist(){ + return g_showNamesDist; + } + void setShowNamesRatio( int ratio ){ + g_showNamesRatio = ratio; + } + int getShowNamesRatio(){ + return g_showNamesRatio; + } + void setShowTargetNames( bool showNames ){ + g_showTargetNames = showNames; + } + bool getShowTargetNames(){ + return g_showTargetNames; + } + void setShowAngles( bool showAngles ){ + g_showAngles = showAngles; + } + bool getShowAngles(){ + return g_showAngles; } - SceneChangeNotify(); -} -void setLightRadii( bool lightRadii ){ - g_lightRadii = lightRadii; -} -bool getLightRadii(){ - return g_lightRadii; -} -void setShowNames( bool showNames ){ - g_showNames = showNames; -} -bool getShowNames(){ - return g_showNames; -} -void setShowBboxes( bool showBboxes ){ - g_showBboxes = showBboxes; -} -bool getShowBboxes(){ - return g_showBboxes; -} -void setShowConnections( bool showConnections ){ - g_showConnections = showConnections; -} -bool getShowConnections(){ - return g_showConnections; -} -void setShowNamesDist( int dist ){ - g_showNamesDist = dist; -} -int getShowNamesDist(){ - return g_showNamesDist; -} -void setShowNamesRatio( int ratio ){ - g_showNamesRatio = ratio; -} -int getShowNamesRatio(){ - return g_showNamesRatio; -} -void setShowTargetNames( bool showNames ){ - g_showTargetNames = showNames; -} -bool getShowTargetNames(){ - return g_showTargetNames; -} -void setShowAngles( bool showAngles ){ - g_showAngles = showAngles; -} -bool getShowAngles(){ - return g_showAngles; -} -void printStatistics() const { - StringPool_analyse( EntityKeyValues::getPool() ); -} + void printStatistics() const { + StringPool_analyse( EntityKeyValues::getPool() ); + } }; Quake3EntityCreator g_Quake3EntityCreator; @@ -324,25 +324,25 @@ EntityCreator& GetEntityCreator(){ class filter_entity_classname : public EntityFilter { -const char* m_classname; + const char* m_classname; public: -filter_entity_classname( const char* classname ) : m_classname( classname ){ -} -bool filter( const Entity& entity ) const { - return string_equal( entity.getKeyValue( "classname" ), m_classname ); -} + filter_entity_classname( const char* classname ) : m_classname( classname ){ + } + bool filter( const Entity& entity ) const { + return string_equal( entity.getKeyValue( "classname" ), m_classname ); + } }; class filter_entity_classgroup : public EntityFilter { -const char* m_classgroup; -std::size_t m_length; + const char* m_classgroup; + std::size_t m_length; public: -filter_entity_classgroup( const char* classgroup ) : m_classgroup( classgroup ), m_length( string_length( m_classgroup ) ){ -} -bool filter( const Entity& entity ) const { - return string_equal_n( entity.getKeyValue( "classname" ), m_classgroup, m_length ); -} + filter_entity_classgroup( const char* classgroup ) : m_classgroup( classgroup ), m_length( string_length( m_classgroup ) ){ + } + bool filter( const Entity& entity ) const { + return string_equal_n( entity.getKeyValue( "classname" ), m_classgroup, m_length ); + } }; filter_entity_classname g_filter_entity_func_group( "func_group" ); @@ -354,19 +354,19 @@ filter_entity_classgroup g_filter_entity_path( "path_" ); class filter_entity_misc_model : public EntityFilter { public: -bool filter( const Entity& entity ) const { - return entity.getEntityClass().miscmodel_is; -} + bool filter( const Entity& entity ) const { + return entity.getEntityClass().miscmodel_is; + } }; filter_entity_misc_model g_filter_entity_misc_model; class filter_entity_doom3model : public EntityFilter { public: -bool filter( const Entity& entity ) const { - return string_equal( entity.getKeyValue( "classname" ), "func_static" ) - && !string_equal( entity.getKeyValue( "model" ), entity.getKeyValue( "name" ) ); -} + bool filter( const Entity& entity ) const { + return string_equal( entity.getKeyValue( "classname" ), "func_static" ) + && !string_equal( entity.getKeyValue( "model" ), entity.getKeyValue( "name" ) ); + } }; filter_entity_doom3model g_filter_entity_doom3model; @@ -375,10 +375,10 @@ filter_entity_doom3model g_filter_entity_doom3model; class filter_entity_not_func_detail : public EntityFilter { public: -bool filter( const Entity& entity ) const { - return entity.isContainer() - && !string_equal_n( entity.getKeyValue( "classname" ), "func_detail", 11 ); -} + bool filter( const Entity& entity ) const { + return entity.isContainer() + && !string_equal_n( entity.getKeyValue( "classname" ), "func_detail", 11 ); + } }; filter_entity_not_func_detail g_filter_entity_not_func_detail; @@ -386,12 +386,12 @@ filter_entity_not_func_detail g_filter_entity_not_func_detail; class filter_entity_world : public EntityFilter { public: -bool filter( const Entity& entity ) const { - const char* value = entity.getKeyValue( "classname" ); - return string_equal( value, "worldspawn" ) - || string_equal( value, "func_group" ) - || string_equal_n( value, "func_detail", 11 ); -} + bool filter( const Entity& entity ) const { + const char* value = entity.getKeyValue( "classname" ); + return string_equal( value, "worldspawn" ) + || string_equal( value, "func_group" ) + || string_equal_n( value, "func_detail", 11 ); + } }; filter_entity_world g_filter_entity_world; @@ -399,11 +399,11 @@ filter_entity_world g_filter_entity_world; class filter_entity_point : public EntityFilter { public: -bool filter( const Entity& entity ) const { - return !entity.isContainer() - && !entity.getEntityClass().miscmodel_is - && !string_equal_prefix( entity.getEntityClass().name(), "light" ); -} + bool filter( const Entity& entity ) const { + return !entity.isContainer() + && !entity.getEntityClass().miscmodel_is + && !string_equal_prefix( entity.getEntityClass().name(), "light" ); + } }; filter_entity_point g_filter_entity_point; diff --git a/plugins/entity/filters.cpp b/plugins/entity/filters.cpp index d18b3097..0db78e0b 100644 --- a/plugins/entity/filters.cpp +++ b/plugins/entity/filters.cpp @@ -27,21 +27,21 @@ class EntityFilterWrapper : public Filter { -bool m_active; -bool m_invert; -EntityFilter& m_filter; + bool m_active; + bool m_invert; + EntityFilter& m_filter; public: -EntityFilterWrapper( EntityFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ -} -void setActive( bool active ){ - m_active = active; -} -bool active(){ - return m_active; -} -bool filter( const Entity& entity ){ - return m_invert ^ m_filter.filter( entity ); -} + EntityFilterWrapper( EntityFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ + } + void setActive( bool active ){ + m_active = active; + } + bool active(){ + return m_active; + } + bool filter( const Entity& entity ){ + return m_invert ^ m_filter.filter( entity ); + } }; diff --git a/plugins/entity/filters.h b/plugins/entity/filters.h index d903e28c..774d15cb 100644 --- a/plugins/entity/filters.h +++ b/plugins/entity/filters.h @@ -32,7 +32,7 @@ class Entity; class EntityFilter { public: -virtual bool filter( const Entity& entity ) const = 0; + virtual bool filter( const Entity& entity ) const = 0; }; bool entity_filtered( Entity& entity ); @@ -40,36 +40,36 @@ void add_entity_filter( EntityFilter& filter, int mask, bool invert = false ); class ClassnameFilter : public Filterable { -scene::Node& m_node; + scene::Node& m_node; public: -Entity& m_entity; + Entity& m_entity; -ClassnameFilter( Entity& entity, scene::Node& node ) : m_node( node ), m_entity( entity ){ -} -~ClassnameFilter(){ -} - -void instanceAttach(){ - GlobalFilterSystem().registerFilterable( *this ); -} -void instanceDetach(){ - GlobalFilterSystem().unregisterFilterable( *this ); -} - -void updateFiltered(){ - if ( entity_filtered( m_entity ) ) { - m_node.enable( scene::Node::eFiltered ); + ClassnameFilter( Entity& entity, scene::Node& node ) : m_node( node ), m_entity( entity ){ } - else - { - m_node.disable( scene::Node::eFiltered ); + ~ClassnameFilter(){ } -} -void classnameChanged( const char* value ){ - updateFiltered(); -} -typedef MemberCaller1 ClassnameChangedCaller; + void instanceAttach(){ + GlobalFilterSystem().registerFilterable( *this ); + } + void instanceDetach(){ + GlobalFilterSystem().unregisterFilterable( *this ); + } + + void updateFiltered(){ + if ( entity_filtered( m_entity ) ) { + m_node.enable( scene::Node::eFiltered ); + } + else + { + m_node.disable( scene::Node::eFiltered ); + } + } + + void classnameChanged( const char* value ){ + updateFiltered(); + } + typedef MemberCaller1 ClassnameChangedCaller; }; #endif diff --git a/plugins/entity/generic.cpp b/plugins/entity/generic.cpp index 9e61b163..3c0ff85a 100644 --- a/plugins/entity/generic.cpp +++ b/plugins/entity/generic.cpp @@ -61,199 +61,199 @@ class GenericEntity : public Bounded, public Snappable { -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; -MatrixTransform m_transform; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; + MatrixTransform m_transform; -OriginKey m_originKey; -Vector3 m_origin; -AnglesKey m_anglesKey; -Vector3 m_angles; + OriginKey m_originKey; + Vector3 m_origin; + AnglesKey m_anglesKey; + Vector3 m_angles; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; -AABB m_aabb_local; + AABB m_aabb_local; -RenderableArrow m_arrow; -RenderableSolidAABB m_aabb_solid; -RenderableWireframeAABB m_aabb_wire; -RenderableNamedEntity m_renderName; + RenderableArrow m_arrow; + RenderableSolidAABB m_aabb_solid; + RenderableWireframeAABB m_aabb_wire; + RenderableNamedEntity m_renderName; -Callback m_transformChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_evaluateTransform; -void construct(){ - read_aabb( m_aabb_local, m_entity.getEntityClass() ); + void construct(){ + read_aabb( m_aabb_local, m_entity.getEntityClass() ); - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - m_keyObservers.insert( "angle", AnglesKey::AngleChangedCaller( m_anglesKey ) ); - m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); -} + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + m_keyObservers.insert( "angle", AnglesKey::AngleChangedCaller( m_anglesKey ) ); + m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); + } // vc 2k5 compiler fix #if _MSC_VER >= 1400 public: #endif -void updateTransform(){ - m_transform.localToParent() = g_matrix4_identity; - matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); - m_transformChanged(); -} -typedef MemberCaller UpdateTransformCaller; -void originChanged(){ - m_origin = m_originKey.m_origin; - updateTransform(); -} -typedef MemberCaller OriginChangedCaller; -void anglesChanged(){ - m_angles = m_anglesKey.m_angles; - updateTransform(); -} -typedef MemberCaller AnglesChangedCaller; + void updateTransform(){ + m_transform.localToParent() = g_matrix4_identity; + matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); + m_transformChanged(); + } + typedef MemberCaller UpdateTransformCaller; + void originChanged(){ + m_origin = m_originKey.m_origin; + updateTransform(); + } + typedef MemberCaller OriginChangedCaller; + void anglesChanged(){ + m_angles = m_anglesKey.m_angles; + updateTransform(); + } + typedef MemberCaller AnglesChangedCaller; public: -GenericEntity( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_anglesKey( AnglesChangedCaller( *this ) ), - m_angles( ANGLESKEY_IDENTITY ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_arrow( m_aabb_local.origin, m_angles ), - m_aabb_solid( m_aabb_local ), - m_aabb_wire( m_aabb_local ), - m_renderName( m_named, g_vector3_identity ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -GenericEntity( const GenericEntity& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_anglesKey( AnglesChangedCaller( *this ) ), - m_angles( ANGLESKEY_IDENTITY ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_arrow( m_aabb_local.origin, m_angles ), - m_aabb_solid( m_aabb_local ), - m_aabb_wire( m_aabb_local ), - m_renderName( m_named, g_vector3_identity ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.attach( m_keyObservers ); + GenericEntity( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_anglesKey( AnglesChangedCaller( *this ) ), + m_angles( ANGLESKEY_IDENTITY ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_arrow( m_aabb_local.origin, m_angles ), + m_aabb_solid( m_aabb_local ), + m_aabb_wire( m_aabb_local ), + m_renderName( m_named, g_vector3_identity ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_entity.detach( m_keyObservers ); - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); + GenericEntity( const GenericEntity& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_anglesKey( AnglesChangedCaller( *this ) ), + m_angles( ANGLESKEY_IDENTITY ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_arrow( m_aabb_local.origin, m_angles ), + m_aabb_solid( m_aabb_local ), + m_aabb_wire( m_aabb_local ), + m_renderName( m_named, g_vector3_identity ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} - -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} - -const AABB& localAABB() const { - return m_aabb_local; -} - -VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { - return volume.TestAABB( localAABB(), localToWorld ); -} - -void renderArrow( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - if ( g_showAngles ) { - renderer.addRenderable( m_arrow, localToWorld ); + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.attach( m_keyObservers ); + } } -} -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); - renderer.addRenderable( m_aabb_solid, localToWorld ); - renderArrow( renderer, volume, localToWorld ); - if ( g_showNames || selected ) { - m_renderName.render( renderer, volume, localToWorld, selected ); + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_entity.detach( m_keyObservers ); + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); + } } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - renderer.addRenderable( m_aabb_wire, localToWorld ); - renderArrow( renderer, volume, localToWorld ); - if ( selected || ( g_showNames && aabb_fits_view( m_aabb_local, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) { - m_renderName.render( renderer, volume, localToWorld, selected ); + + EntityKeyValues& getEntity(){ + return m_entity; + } + const EntityKeyValues& getEntity() const { + return m_entity; + } + + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } + + const AABB& localAABB() const { + return m_aabb_local; + } + + VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { + return volume.TestAABB( localAABB(), localToWorld ); + } + + void renderArrow( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + if ( g_showAngles ) { + renderer.addRenderable( m_arrow, localToWorld ); + } + } + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); + renderer.addRenderable( m_aabb_solid, localToWorld ); + renderArrow( renderer, volume, localToWorld ); + if ( g_showNames || selected ) { + m_renderName.render( renderer, volume, localToWorld, selected ); + } + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + renderer.addRenderable( m_aabb_wire, localToWorld ); + renderArrow( renderer, volume, localToWorld ); + if ( selected || ( g_showNames && aabb_fits_view( m_aabb_local, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) { + m_renderName.render( renderer, volume, localToWorld, selected ); + } } -} -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - test.BeginMesh( localToWorld ); + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + test.BeginMesh( localToWorld ); - SelectionIntersection best; - aabb_testselect( m_aabb_local, test, best ); - if ( best.valid() ) { - selector.addIntersection( best ); + SelectionIntersection best; + aabb_testselect( m_aabb_local, test, best ); + if ( best.valid() ) { + selector.addIntersection( best ); + } } -} -void translate( const Vector3& translation ){ - m_origin = origin_translated( m_origin, translation ); -} -void rotate( const Quaternion& rotation ){ - m_angles = angles_rotated( m_angles, rotation ); -} -void snapto( float snap ){ - m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); - m_originKey.write( &m_entity ); -} -void revertTransform(){ - m_origin = m_originKey.m_origin; - m_angles = m_anglesKey.m_angles; -} -void freezeTransform(){ - m_originKey.m_origin = m_origin; - m_originKey.write( &m_entity ); - if( m_anglesKey.m_angles != m_angles ){ - m_anglesKey.m_angles = m_angles; - m_anglesKey.write( &m_entity ); + void translate( const Vector3& translation ){ + m_origin = origin_translated( m_origin, translation ); } -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateTransform(); -} -typedef MemberCaller TransformChangedCaller; + void rotate( const Quaternion& rotation ){ + m_angles = angles_rotated( m_angles, rotation ); + } + void snapto( float snap ){ + m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); + m_originKey.write( &m_entity ); + } + void revertTransform(){ + m_origin = m_originKey.m_origin; + m_angles = m_anglesKey.m_angles; + } + void freezeTransform(){ + m_originKey.m_origin = m_origin; + m_originKey.write( &m_entity ); + if( m_anglesKey.m_angles != m_angles ){ + m_anglesKey.m_angles = m_angles; + m_anglesKey.write( &m_entity ); + } + } + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateTransform(); + } + typedef MemberCaller TransformChangedCaller; }; class GenericEntityInstance : @@ -262,78 +262,78 @@ class GenericEntityInstance : public Renderable, public SelectionTestable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -GenericEntity& m_contained; -mutable AABB m_bounds; + GenericEntity& m_contained; + mutable AABB m_bounds; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Bounded& get( NullType){ - return m_contained; -} -Cullable& get( NullType){ - return m_contained; -} + Bounded& get( NullType){ + return m_contained; + } + Cullable& get( NullType){ + return m_contained; + } -STRING_CONSTANT( Name, "GenericEntityInstance" ); + STRING_CONSTANT( Name, "GenericEntityInstance" ); -GenericEntityInstance( const scene::Path& path, scene::Instance* parent, GenericEntity& contained ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), - TransformModifier( GenericEntity::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), - m_contained( contained ){ - m_contained.instanceAttach( Instance::path() ); + GenericEntityInstance( const scene::Path& path, scene::Instance* parent, GenericEntity& contained ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), + TransformModifier( GenericEntity::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), + m_contained( contained ){ + m_contained.instanceAttach( Instance::path() ); - StaticRenderableConnectionLines::instance().attach( *this ); -} -~GenericEntityInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); + StaticRenderableConnectionLines::instance().attach( *this ); + } + ~GenericEntityInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); - m_contained.instanceDetach( Instance::path() ); -} + m_contained.instanceDetach( Instance::path() ); + } -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } -void testSelect( Selector& selector, SelectionTest& test ){ - m_contained.testSelect( selector, test, Instance::localToWorld() ); -} + void testSelect( Selector& selector, SelectionTest& test ){ + m_contained.testSelect( selector, test, Instance::localToWorld() ); + } -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); - if( getRotation() != c_quaternion_identity ){ - m_contained.rotate( getRotation() ); + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + if( getRotation() != c_quaternion_identity ){ + m_contained.rotate( getRotation() ); + } } } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; }; class GenericEntityNode : @@ -341,83 +341,83 @@ class GenericEntityNode : public scene::Instantiable, public scene::Cloneable { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -InstanceSet m_instances; + InstanceSet m_instances; -scene::Node m_node; -GenericEntity m_contained; + scene::Node m_node; + GenericEntity m_contained; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Snappable& get( NullType){ - return m_contained; -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} + Snappable& get( NullType){ + return m_contained; + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); + } -GenericEntityNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ -} -GenericEntityNode( const GenericEntityNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + GenericEntityNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + } + GenericEntityNode( const GenericEntityNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Node& clone() const { - return ( new GenericEntityNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new GenericEntityNode( *this ) )->node(); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new GenericEntityInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new GenericEntityInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; scene::Node& New_GenericEntity( EntityClass* eclass ){ diff --git a/plugins/entity/group.cpp b/plugins/entity/group.cpp index 7711df2a..5d5afb01 100644 --- a/plugins/entity/group.cpp +++ b/plugins/entity/group.cpp @@ -53,251 +53,251 @@ const char EXCLUDE_NAME[] = "worldspawn"; class Group { -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; -MatrixTransform m_transform; -TraversableNodeSet m_traverse; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; + MatrixTransform m_transform; + TraversableNodeSet m_traverse; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; -OriginKey m_originKey; -Vector3 m_origin; + OriginKey m_originKey; + Vector3 m_origin; -mutable Vector3 m_name_origin; -RenderableNamedEntity m_renderName; + mutable Vector3 m_name_origin; + RenderableNamedEntity m_renderName; -AnglesKey m_anglesKey; -RenderableArrow m_arrow; -bool m_anglesDraw; -void updateAnglesDraw(){ - m_anglesDraw = m_entity.getEntityClass().has_angles || !string_empty( m_entity.getKeyValue( "angle" ) ) || !string_empty( m_entity.getKeyValue( "angles" ) ); - SceneChangeNotify(); -} -typedef MemberCaller UpdateAnglesDrawCaller; + AnglesKey m_anglesKey; + RenderableArrow m_arrow; + bool m_anglesDraw; + void updateAnglesDraw(){ + m_anglesDraw = m_entity.getEntityClass().has_angles || !string_empty( m_entity.getKeyValue( "angle" ) ) || !string_empty( m_entity.getKeyValue( "angles" ) ); + SceneChangeNotify(); + } + typedef MemberCaller UpdateAnglesDrawCaller; -Callback m_transformChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_evaluateTransform; -void construct(){ - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); - m_keyObservers.insert( "angle", AnglesKey::GroupAngleChangedCaller( m_anglesKey ) ); - m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); - updateAnglesDraw(); -} + void construct(){ + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); + m_keyObservers.insert( "angle", AnglesKey::GroupAngleChangedCaller( m_anglesKey ) ); + m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); + updateAnglesDraw(); + } public: -Group( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_name_origin( g_vector3_identity ), - m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), - m_anglesKey( UpdateAnglesDrawCaller( *this ) ), - m_arrow( m_name_origin, m_anglesKey.m_angles ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -Group( const Group& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_name_origin( g_vector3_identity ), - m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), - m_anglesKey( UpdateAnglesDrawCaller( *this ) ), - m_arrow( m_name_origin, m_anglesKey.m_angles ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.attach( m_keyObservers ); + Group( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_name_origin( g_vector3_identity ), + m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), + m_anglesKey( UpdateAnglesDrawCaller( *this ) ), + m_arrow( m_name_origin, m_anglesKey.m_angles ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_entity.detach( m_keyObservers ); - m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); + Group( const Group& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_name_origin( g_vector3_identity ), + m_renderName( m_named, m_name_origin, EXCLUDE_NAME ), + m_anglesKey( UpdateAnglesDrawCaller( *this ) ), + m_arrow( m_name_origin, m_anglesKey.m_angles ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.attach( m_keyObservers ); + } + } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_entity.detach( m_keyObservers ); + m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); + } + } -scene::Traversable& getTraversable(){ - return m_traverse; -} -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} + EntityKeyValues& getEntity(){ + return m_entity; + } + const EntityKeyValues& getEntity() const { + return m_entity; + } -void attach( scene::Traversable::Observer* observer ){ - m_traverse.attach( observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_traverse.detach( observer ); -} + scene::Traversable& getTraversable(){ + return m_traverse; + } + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { - if ( m_renderName.excluded_not() ) { - // place name in the middle of the "children cloud" - m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); + void attach( scene::Traversable::Observer* observer ){ + m_traverse.attach( observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_traverse.detach( observer ); + } - if ( selected || childSelected || g_showNames ) - m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); - if ( m_anglesDraw && g_showAngles ) { - if( selected || childSelected ){ - renderer.PushState(); - renderer.Highlight( Renderer::ePrimitive ); - renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); - renderer.addRenderable( m_arrow, localToWorld ); - renderer.PopState(); - } - else{ - renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); - renderer.addRenderable( m_arrow, localToWorld ); + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { + if ( m_renderName.excluded_not() ) { + // place name in the middle of the "children cloud" + m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); + + if ( selected || childSelected || g_showNames ) + m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); + if ( m_anglesDraw && g_showAngles ) { + if( selected || childSelected ){ + renderer.PushState(); + renderer.Highlight( Renderer::ePrimitive ); + renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); + renderer.addRenderable( m_arrow, localToWorld ); + renderer.PopState(); + } + else{ + renderer.SetState( m_entity.getEntityClass().m_state_fill, Renderer::eFullMaterials ); + renderer.addRenderable( m_arrow, localToWorld ); + } } } } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected, bool childSelected, const AABB& childBounds ) const { + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); // don't draw the name for worldspawn // if ( !strcmp( m_entity.getEntityClass().name(), "worldspawn" ) ) { // return; // } - if ( m_renderName.excluded_not() ) { - // place name in the middle of the "children cloud" - m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); + if ( m_renderName.excluded_not() ) { + // place name in the middle of the "children cloud" + m_name_origin = extents_valid( childBounds.extents.x() )? childBounds.origin : vector4_to_vector3( localToWorld.t() ); - if ( selected || childSelected || ( g_showNames && aabb_fits_view( childBounds, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) - m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); - if ( m_anglesDraw && g_showAngles ) { - if( selected || childSelected ){ - renderer.PushState(); - renderer.Highlight( Renderer::ePrimitive ); - renderer.addRenderable( m_arrow, localToWorld ); - renderer.PopState(); - } - else{ - renderer.addRenderable( m_arrow, localToWorld ); + if ( selected || childSelected || ( g_showNames && aabb_fits_view( childBounds, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) + m_renderName.render( renderer, volume, g_matrix4_identity, selected, childSelected ); + if ( m_anglesDraw && g_showAngles ) { + if( selected || childSelected ){ + renderer.PushState(); + renderer.Highlight( Renderer::ePrimitive ); + renderer.addRenderable( m_arrow, localToWorld ); + renderer.PopState(); + } + else{ + renderer.addRenderable( m_arrow, localToWorld ); + } } } } -} -void updateTransform(){ - m_transform.localToParent() = g_matrix4_identity; - matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); - m_transformChanged(); -} -typedef MemberCaller UpdateTransformCaller; -void originChanged(){ - m_origin = m_originKey.m_origin; - updateTransform(); -} -typedef MemberCaller OriginChangedCaller; + void updateTransform(){ + m_transform.localToParent() = g_matrix4_identity; + matrix4_translate_by_vec3( m_transform.localToParent(), m_origin ); + m_transformChanged(); + } + typedef MemberCaller UpdateTransformCaller; + void originChanged(){ + m_origin = m_originKey.m_origin; + updateTransform(); + } + typedef MemberCaller OriginChangedCaller; -void translate( const Vector3& translation ){ - m_origin = origin_translated( m_origin, translation ); -} + void translate( const Vector3& translation ){ + m_origin = origin_translated( m_origin, translation ); + } -void revertTransform(){ - m_origin = m_originKey.m_origin; -} -void freezeTransform(){ - m_originKey.m_origin = m_origin; - m_originKey.write( &m_entity ); -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateTransform(); -} -typedef MemberCaller TransformChangedCaller; + void revertTransform(){ + m_origin = m_originKey.m_origin; + } + void freezeTransform(){ + m_originKey.m_origin = m_origin; + m_originKey.write( &m_entity ); + } + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateTransform(); + } + typedef MemberCaller TransformChangedCaller; }; #if 0 class TransformableSetTranslation { -Translation m_value; + Translation m_value; public: -TransformableSetTranslation( const Translation& value ) : m_value( value ){ -} -void operator()( Transformable& transformable ) const { - transformable.setTranslation( m_value ); -} + TransformableSetTranslation( const Translation& value ) : m_value( value ){ + } + void operator()( Transformable& transformable ) const { + transformable.setTranslation( m_value ); + } }; class TransformableSetRotation { -Rotation m_value; + Rotation m_value; public: -TransformableSetRotation( const Rotation& value ) : m_value( value ){ -} -void operator()( Transformable& transformable ) const { - transformable.setRotation( m_value ); -} + TransformableSetRotation( const Rotation& value ) : m_value( value ){ + } + void operator()( Transformable& transformable ) const { + transformable.setRotation( m_value ); + } }; class TransformableSetScale { -Scale m_value; + Scale m_value; public: -TransformableSetScale( const Scale& value ) : m_value( value ){ -} -void operator()( Transformable& transformable ) const { - transformable.setScale( m_value ); -} + TransformableSetScale( const Scale& value ) : m_value( value ){ + } + void operator()( Transformable& transformable ) const { + transformable.setScale( m_value ); + } }; class TransformableSetType { -TransformModifierType m_value; + TransformModifierType m_value; public: -TransformableSetType( const TransformModifierType& value ) : m_value( value ){ -} -void operator()( Transformable& transformable ) const { - transformable.setType( m_value ); -} + TransformableSetType( const TransformModifierType& value ) : m_value( value ){ + } + void operator()( Transformable& transformable ) const { + transformable.setType( m_value ); + } }; class TransformableFreezeTransform { -TransformModifierType m_value; + TransformModifierType m_value; public: -void operator()( Transformable& transformable ) const { - transformable.freezeTransform(); -} + void operator()( Transformable& transformable ) const { + transformable.freezeTransform(); + } }; template @@ -314,78 +314,78 @@ class GroupInstance : #endif public Renderable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceStaticCast::install( m_casts ); + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceStaticCast::install( m_casts ); #if 0 - InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); #endif -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -Group& m_contained; + Group& m_contained; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -GroupInstance( const scene::Path& path, scene::Instance* parent, Group& group ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), group.getEntity(), *this ), - TransformModifier( Group::TransformChangedCaller( group ), ApplyTransformCaller( *this ) ), - m_contained( group ){ - m_contained.instanceAttach( Instance::path() ); - StaticRenderableConnectionLines::instance().attach( *this ); -} -~GroupInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); - m_contained.instanceDetach( Instance::path() ); -} -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); -} - -STRING_CONSTANT( Name, "GroupInstance" ); - -#if 0 -void setType( TransformModifierType type ){ - Scene_forEachChildTransformable( TransformableSetType( type ), Instance::path() ); -} -void setTranslation( const Translation& value ){ - Scene_forEachChildTransformable( TransformableSetTranslation( value ), Instance::path() ); -} -void setRotation( const Rotation& value ){ - Scene_forEachChildTransformable( TransformableSetRotation( value ), Instance::path() ); -} -void setScale( const Scale& value ){ - Scene_forEachChildTransformable( TransformableSetScale( value ), Instance::path() ); -} -void freezeTransform(){ - Scene_forEachChildTransformable( TransformableFreezeTransform(), Instance::path() ); -} - -void evaluateTransform(){ -} -#endif - -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); + GroupInstance( const scene::Path& path, scene::Instance* parent, Group& group ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), group.getEntity(), *this ), + TransformModifier( Group::TransformChangedCaller( group ), ApplyTransformCaller( *this ) ), + m_contained( group ){ + m_contained.instanceAttach( Instance::path() ); + StaticRenderableConnectionLines::instance().attach( *this ); } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; + ~GroupInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); + m_contained.instanceDetach( Instance::path() ); + } + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected(), Instance::childSelected(), Instance::childBounds() ); + } + + STRING_CONSTANT( Name, "GroupInstance" ); + +#if 0 + void setType( TransformModifierType type ){ + Scene_forEachChildTransformable( TransformableSetType( type ), Instance::path() ); + } + void setTranslation( const Translation& value ){ + Scene_forEachChildTransformable( TransformableSetTranslation( value ), Instance::path() ); + } + void setRotation( const Rotation& value ){ + Scene_forEachChildTransformable( TransformableSetRotation( value ), Instance::path() ); + } + void setScale( const Scale& value ){ + Scene_forEachChildTransformable( TransformableSetScale( value ), Instance::path() ); + } + void freezeTransform(){ + Scene_forEachChildTransformable( TransformableFreezeTransform(), Instance::path() ); + } + + void evaluateTransform(){ + } +#endif + + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + } + } + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; }; class GroupNode : @@ -394,104 +394,104 @@ class GroupNode : public scene::Cloneable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -Group m_contained; + scene::Node m_node; + InstanceSet m_instances; + Group m_contained; -void construct(){ - m_contained.attach( this ); -} -void destroy(){ - m_contained.detach( this ); -} + void construct(){ + m_contained.attach( this ); + } + void destroy(){ + m_contained.detach( this ); + } public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_contained.getTraversable(); -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} + scene::Traversable& get( NullType){ + return m_contained.getTraversable(); + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); + } -GroupNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -GroupNode( const GroupNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -~GroupNode(){ - destroy(); -} + GroupNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + GroupNode( const GroupNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + ~GroupNode(){ + destroy(); + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Node& clone() const { - return ( new GroupNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new GroupNode( *this ) )->node(); + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new GroupInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new GroupInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; scene::Node& New_Group( EntityClass* eclass ){ diff --git a/plugins/entity/keyobservers.h b/plugins/entity/keyobservers.h index b57a0e32..0cef953d 100644 --- a/plugins/entity/keyobservers.h +++ b/plugins/entity/keyobservers.h @@ -27,24 +27,24 @@ class KeyObserverMap : public Entity::Observer { -typedef std::multimap KeyObservers; -KeyObservers m_keyObservers; + typedef std::multimap KeyObservers; + KeyObservers m_keyObservers; public: -void insert( const char* key, const KeyObserver& observer ){ - m_keyObservers.insert( KeyObservers::value_type( key, observer ) ); -} -void insert( const char* key, EntityKeyValue& value ){ - for ( KeyObservers::const_iterator i = m_keyObservers.find( key ); i != m_keyObservers.end() && string_equal( ( *i ).first, key ); ++i ) - { - value.attach( ( *i ).second ); + void insert( const char* key, const KeyObserver& observer ){ + m_keyObservers.insert( KeyObservers::value_type( key, observer ) ); } -} -void erase( const char* key, EntityKeyValue& value ){ - for ( KeyObservers::const_iterator i = m_keyObservers.find( key ); i != m_keyObservers.end() && string_equal( ( *i ).first, key ); ++i ) - { - value.detach( ( *i ).second ); + void insert( const char* key, EntityKeyValue& value ){ + for ( KeyObservers::const_iterator i = m_keyObservers.find( key ); i != m_keyObservers.end() && string_equal( ( *i ).first, key ); ++i ) + { + value.attach( ( *i ).second ); + } + } + void erase( const char* key, EntityKeyValue& value ){ + for ( KeyObservers::const_iterator i = m_keyObservers.find( key ); i != m_keyObservers.end() && string_equal( ( *i ).first, key ); ++i ) + { + value.detach( ( *i ).second ); + } } -} }; #endif diff --git a/plugins/entity/light.cpp b/plugins/entity/light.cpp index f55db3a0..35e2c863 100644 --- a/plugins/entity/light.cpp +++ b/plugins/entity/light.cpp @@ -345,10 +345,10 @@ void sphere_draw_wire( const Vector3& origin, float radius, int sides ){ double dc = cos( ( i * 2 * c_pi ) / sides ); glVertex3f( - static_cast( origin[0] + radius * dc ), - static_cast( origin[1] + radius * ds ), - origin[2] - ); + static_cast( origin[0] + radius * dc ), + static_cast( origin[1] + radius * ds ), + origin[2] + ); } glEnd(); @@ -363,10 +363,10 @@ void sphere_draw_wire( const Vector3& origin, float radius, int sides ){ double dc = cos( ( i * 2 * c_pi ) / sides ); glVertex3f( - static_cast( origin[0] + radius * dc ), - origin[1], - static_cast( origin[2] + radius * ds ) - ); + static_cast( origin[0] + radius * dc ), + origin[1], + static_cast( origin[2] + radius * ds ) + ); } glEnd(); @@ -381,10 +381,10 @@ void sphere_draw_wire( const Vector3& origin, float radius, int sides ){ double dc = cos( ( i * 2 * c_pi ) / sides ); glVertex3f( - origin[0], - static_cast( origin[1] + radius * dc ), - static_cast( origin[2] + radius * ds ) - ); + origin[0], + static_cast( origin[1] + radius * dc ), + static_cast( origin[2] + radius * ds ) + ); } glEnd(); @@ -417,11 +417,11 @@ void sphere_construct_wire( Vector3 radiiPoints[SPHERE_WIRE_POINTS] ){ double dc = cos( ( i * 2 * c_pi ) / SPHERE_WIRE_SIDES ); radiiPoints[k++] = - Vector3( - static_cast( dc ), - static_cast( ds ), - 0.f - ); + Vector3( + static_cast( dc ), + static_cast( ds ), + 0.f + ); } for ( int i = 0; i < SPHERE_WIRE_SIDES; i++ ) @@ -430,11 +430,11 @@ void sphere_construct_wire( Vector3 radiiPoints[SPHERE_WIRE_POINTS] ){ double dc = cos( ( i * 2 * c_pi ) / SPHERE_WIRE_SIDES ); radiiPoints[k++] = - Vector3( - static_cast( dc ), - 0.f, - static_cast( ds ) - ); + Vector3( + static_cast( dc ), + 0.f, + static_cast( ds ) + ); } for ( int i = 0; i < SPHERE_WIRE_SIDES; i++ ) @@ -443,11 +443,11 @@ void sphere_construct_wire( Vector3 radiiPoints[SPHERE_WIRE_POINTS] ){ double dc = cos( ( i * 2 * c_pi ) / SPHERE_WIRE_SIDES ); radiiPoints[k++] = - Vector3( - 0.f, - static_cast( dc ), - static_cast( ds ) - ); + Vector3( + 0.f, + static_cast( dc ), + static_cast( ds ) + ); } } @@ -734,263 +734,263 @@ bool spawnflags_linear( int flags ){ class LightRadii { public: -float m_radii[3]; -float m_radii_transformed[3]; + float m_radii[3]; + float m_radii_transformed[3]; private: -float m_primaryIntensity; -float m_secondaryIntensity; -int m_flags; -float m_fade; -float m_scale; + float m_primaryIntensity; + float m_secondaryIntensity; + int m_flags; + float m_fade; + float m_scale; -void calculateRadii(){ - float intensity = 300.0f; + void calculateRadii(){ + float intensity = 300.0f; - if ( m_primaryIntensity != 0.0f ) { - intensity = m_primaryIntensity; - } - else if ( m_secondaryIntensity != 0.0f ) { - intensity = m_secondaryIntensity; - } + if ( m_primaryIntensity != 0.0f ) { + intensity = m_primaryIntensity; + } + else if ( m_secondaryIntensity != 0.0f ) { + intensity = m_secondaryIntensity; + } - intensity *= m_scale; + intensity *= m_scale; - if( intensity < 0 ){ // prevent NaN - m_radii_transformed[0] = m_radii[0] = - m_radii_transformed[1] = m_radii[1] = - m_radii_transformed[2] = m_radii[2] = 0; // indicate negative intensity + if( intensity < 0 ){ // prevent NaN + m_radii_transformed[0] = m_radii[0] = + m_radii_transformed[1] = m_radii[1] = + m_radii_transformed[2] = m_radii[2] = 0; // indicate negative intensity + } + else if ( spawnflags_linear( m_flags ) ) { + m_radii_transformed[0] = m_radii[0] = light_radius_linear( intensity, 1.0f ) / m_fade; + m_radii_transformed[1] = m_radii[1] = light_radius_linear( intensity, 48.0f ) / m_fade; + m_radii_transformed[2] = m_radii[2] = light_radius_linear( intensity, 255.0f ) / m_fade; + } + else + { + m_radii_transformed[0] = m_radii[0] = light_radius( intensity, 1.0f ); + m_radii_transformed[1] = m_radii[1] = light_radius( intensity, 48.0f ); + m_radii_transformed[2] = m_radii[2] = light_radius( intensity, 255.0f ); + } } - else if ( spawnflags_linear( m_flags ) ) { - m_radii_transformed[0] = m_radii[0] = light_radius_linear( intensity, 1.0f ) / m_fade; - m_radii_transformed[1] = m_radii[1] = light_radius_linear( intensity, 48.0f ) / m_fade; - m_radii_transformed[2] = m_radii[2] = light_radius_linear( intensity, 255.0f ) / m_fade; - } - else - { - m_radii_transformed[0] = m_radii[0] = light_radius( intensity, 1.0f ); - m_radii_transformed[1] = m_radii[1] = light_radius( intensity, 48.0f ); - m_radii_transformed[2] = m_radii[2] = light_radius( intensity, 255.0f ); - } -} public: -LightRadii() : m_primaryIntensity( 0 ), m_secondaryIntensity( 0 ), m_flags( 0 ), m_fade( 1 ), m_scale( 1 ){ - calculateRadii(); -} - - -void primaryIntensityChanged( const char* value ){ - m_primaryIntensity = string_read_float( value ); - calculateRadii(); -} -typedef MemberCaller1 PrimaryIntensityChangedCaller; -void secondaryIntensityChanged( const char* value ){ - m_secondaryIntensity = string_read_float( value ); - calculateRadii(); -} -typedef MemberCaller1 SecondaryIntensityChangedCaller; -void scaleChanged( const char* value ){ - m_scale = string_read_float( value ); - if ( m_scale <= 0.0f ) { - m_scale = 1.0f; + LightRadii() : m_primaryIntensity( 0 ), m_secondaryIntensity( 0 ), m_flags( 0 ), m_fade( 1 ), m_scale( 1 ){ + calculateRadii(); } - calculateRadii(); -} -typedef MemberCaller1 ScaleChangedCaller; -void fadeChanged( const char* value ){ - m_fade = string_read_float( value ); - if ( m_fade <= 0.0f ) { - m_fade = 1.0f; + + + void primaryIntensityChanged( const char* value ){ + m_primaryIntensity = string_read_float( value ); + calculateRadii(); } - calculateRadii(); -} -typedef MemberCaller1 FadeChangedCaller; -void flagsChanged( const char* value ){ - m_flags = string_read_int( value ); - calculateRadii(); -} -typedef MemberCaller1 FlagsChangedCaller; - -void transformRadii( float offset ){ - const float radius = m_radii[1] + offset; - - float (&r)[3] = m_radii_transformed; - - if ( spawnflags_linear( m_flags ) ) { - r[0] = radius + 47.0f / m_fade; - if( r[0] <= 1.f ){ - r[0] = 1.f; - r[1] = r[2] = 1.f - 47.0f / m_fade; // this is called once again after minimizing already minimal radii, so calculate correct r[1] - return; + typedef MemberCaller1 PrimaryIntensityChangedCaller; + void secondaryIntensityChanged( const char* value ){ + m_secondaryIntensity = string_read_float( value ); + calculateRadii(); + } + typedef MemberCaller1 SecondaryIntensityChangedCaller; + void scaleChanged( const char* value ){ + m_scale = string_read_float( value ); + if ( m_scale <= 0.0f ) { + m_scale = 1.0f; } - r[1] = radius; - r[2] = radius - 207.0f / m_fade;; + calculateRadii(); } - else - { - r[0] = radius * sqrt( 48.f ); - if( r[0] <= 1.f ){ - r[0] = 1.f; - r[1] = r[2] = 0; - return; + typedef MemberCaller1 ScaleChangedCaller; + void fadeChanged( const char* value ){ + m_fade = string_read_float( value ); + if ( m_fade <= 0.0f ) { + m_fade = 1.0f; } - r[1] = radius; - r[2] = r[0] / sqrt( 255.f ); + calculateRadii(); + } + typedef MemberCaller1 FadeChangedCaller; + void flagsChanged( const char* value ){ + m_flags = string_read_int( value ); + calculateRadii(); + } + typedef MemberCaller1 FlagsChangedCaller; + + void transformRadii( float offset ){ + const float radius = m_radii[1] + offset; + + float (&r)[3] = m_radii_transformed; + + if ( spawnflags_linear( m_flags ) ) { + r[0] = radius + 47.0f / m_fade; + if( r[0] <= 1.f ){ + r[0] = 1.f; + r[1] = r[2] = 1.f - 47.0f / m_fade; // this is called once again after minimizing already minimal radii, so calculate correct r[1] + return; + } + r[1] = radius; + r[2] = radius - 207.0f / m_fade;; + } + else + { + r[0] = radius * sqrt( 48.f ); + if( r[0] <= 1.f ){ + r[0] = 1.f; + r[1] = r[2] = 0; + return; + } + r[1] = radius; + r[2] = r[0] / sqrt( 255.f ); + } +// globalOutputStream() << r[0] << " " << r[1] << " " << r[2] << " m_radii_transformed\n"; + } + float calculateIntensityFromRadii(){ + if( m_radii_transformed[0] == 0 ) // negative intensity + return m_primaryIntensity != 0? m_primaryIntensity : m_secondaryIntensity; + else if ( spawnflags_linear( m_flags ) ) + return ( m_radii_transformed[0] * m_fade + 1.f ) / ( fPointScale * fLinearScale ) / m_scale; + else + return m_radii_transformed[0] * m_radii_transformed[0] * 1.f / fPointScale / m_scale; } -// globalOutputStream() << r[0] << " " << r[1] << " " << r[2] << " m_radii_transformed\n"; -} -float calculateIntensityFromRadii(){ - if( m_radii_transformed[0] == 0 ) // negative intensity - return m_primaryIntensity != 0? m_primaryIntensity : m_secondaryIntensity; - else if ( spawnflags_linear( m_flags ) ) - return ( m_radii_transformed[0] * m_fade + 1.f ) / ( fPointScale * fLinearScale ) / m_scale; - else - return m_radii_transformed[0] * m_radii_transformed[0] * 1.f / fPointScale / m_scale; -} }; class Doom3LightRadius { public: -Vector3 m_defaultRadius; -Vector3 m_radius; -Vector3 m_radiusTransformed; -Vector3 m_center; -Callback m_changed; -bool m_useCenterKey; + Vector3 m_defaultRadius; + Vector3 m_radius; + Vector3 m_radiusTransformed; + Vector3 m_center; + Callback m_changed; + bool m_useCenterKey; -Doom3LightRadius( const char* defaultRadius ) : m_defaultRadius( 300, 300, 300 ), m_center( 0, 0, 0 ), m_useCenterKey( false ){ - if ( g_lightType == LIGHTTYPE_DOOM3 ){ - if ( !string_parse_vector3( defaultRadius, m_defaultRadius ) ) { - globalErrorStream() << "Doom3LightRadius: failed to parse default light radius\n"; + Doom3LightRadius( const char* defaultRadius ) : m_defaultRadius( 300, 300, 300 ), m_center( 0, 0, 0 ), m_useCenterKey( false ){ + if ( g_lightType == LIGHTTYPE_DOOM3 ){ + if ( !string_parse_vector3( defaultRadius, m_defaultRadius ) ) { + globalErrorStream() << "Doom3LightRadius: failed to parse default light radius\n"; + } + m_radius = m_defaultRadius; } - m_radius = m_defaultRadius; } -} -void lightRadiusChanged( const char* value ){ - if ( !string_parse_vector3( value, m_radius ) ) { - m_radius = m_defaultRadius; + void lightRadiusChanged( const char* value ){ + if ( !string_parse_vector3( value, m_radius ) ) { + m_radius = m_defaultRadius; + } + m_radiusTransformed = m_radius; + m_changed(); + SceneChangeNotify(); } - m_radiusTransformed = m_radius; - m_changed(); - SceneChangeNotify(); -} -typedef MemberCaller1 LightRadiusChangedCaller; + typedef MemberCaller1 LightRadiusChangedCaller; -void lightCenterChanged( const char* value ){ - m_useCenterKey = string_parse_vector3( value, m_center ); - if ( !m_useCenterKey ) { - m_center = Vector3( 0, 0, 0 ); + void lightCenterChanged( const char* value ){ + m_useCenterKey = string_parse_vector3( value, m_center ); + if ( !m_useCenterKey ) { + m_center = Vector3( 0, 0, 0 ); + } + SceneChangeNotify(); } - SceneChangeNotify(); -} -typedef MemberCaller1 LightCenterChangedCaller; + typedef MemberCaller1 LightCenterChangedCaller; }; class RenderLightRadiiWire : public OpenGLRenderable { -LightRadii& m_radii; -const Vector3& m_origin; + LightRadii& m_radii; + const Vector3& m_origin; public: -static Vector3 m_radiiPoints[SPHERE_WIRE_POINTS]; + static Vector3 m_radiiPoints[SPHERE_WIRE_POINTS]; -RenderLightRadiiWire( LightRadii& radii, const Vector3& origin ) : m_radii( radii ), m_origin( origin ){ -} -void render( RenderStateFlags state ) const { - //light_draw_radius_wire( m_origin, m_radii.m_radii ); - light_draw_radius_wire( m_origin, m_radii.m_radii_transformed, m_radiiPoints ); -} + RenderLightRadiiWire( LightRadii& radii, const Vector3& origin ) : m_radii( radii ), m_origin( origin ){ + } + void render( RenderStateFlags state ) const { + //light_draw_radius_wire( m_origin, m_radii.m_radii ); + light_draw_radius_wire( m_origin, m_radii.m_radii_transformed, m_radiiPoints ); + } }; Vector3 RenderLightRadiiWire::m_radiiPoints[SPHERE_WIRE_POINTS] = {g_vector3_identity}; class RenderLightRadiiFill : public OpenGLRenderable { -LightRadii& m_radii; -const Vector3& m_origin; + LightRadii& m_radii; + const Vector3& m_origin; public: -//static Shader* m_state; -static Vector3 m_radiiPoints[SPHERE_FILL_POINTS]; + //static Shader* m_state; + static Vector3 m_radiiPoints[SPHERE_FILL_POINTS]; -RenderLightRadiiFill( LightRadii& radii, const Vector3& origin ) : m_radii( radii ), m_origin( origin ){ -} -void render( RenderStateFlags state ) const { - //light_draw_radius_fill( m_origin, m_radii.m_radii ); - light_draw_radius_fill( m_origin, m_radii.m_radii_transformed, m_radiiPoints ); -} + RenderLightRadiiFill( LightRadii& radii, const Vector3& origin ) : m_radii( radii ), m_origin( origin ){ + } + void render( RenderStateFlags state ) const { + //light_draw_radius_fill( m_origin, m_radii.m_radii ); + light_draw_radius_fill( m_origin, m_radii.m_radii_transformed, m_radiiPoints ); + } }; //Shader* RenderLightRadiiFill::m_state = 0; Vector3 RenderLightRadiiFill::m_radiiPoints[SPHERE_FILL_POINTS] = {g_vector3_identity}; class RenderLightRadiiBox : public OpenGLRenderable { -const Vector3& m_origin; + const Vector3& m_origin; public: -mutable Vector3 m_points[8]; -//static Shader* m_state; + mutable Vector3 m_points[8]; + //static Shader* m_state; -RenderLightRadiiBox( const Vector3& origin ) : m_origin( origin ){ -} -void render( RenderStateFlags state ) const { - //draw the bounding box of light based on light_radius key - if ( ( state & RENDER_FILL ) != 0 ) { - aabb_draw_flatshade( m_points ); - } - else - { - aabb_draw_wire( m_points ); + RenderLightRadiiBox( const Vector3& origin ) : m_origin( origin ){ } + void render( RenderStateFlags state ) const { + //draw the bounding box of light based on light_radius key + if ( ( state & RENDER_FILL ) != 0 ) { + aabb_draw_flatshade( m_points ); + } + else + { + aabb_draw_wire( m_points ); + } - #if 1 //disable if you dont want lines going from the center of the light bbox to the corners - light_draw_box_lines( m_origin, m_points ); - #endif -} +#if 1 //disable if you dont want lines going from the center of the light bbox to the corners + light_draw_box_lines( m_origin, m_points ); +#endif + } }; class RenderLightCenter : public OpenGLRenderable { -const Vector3& m_center; -EntityClass& m_eclass; + const Vector3& m_center; + EntityClass& m_eclass; public: -static Shader* m_state; + static Shader* m_state; -RenderLightCenter( const Vector3& center, EntityClass& eclass ) : m_center( center ), m_eclass( eclass ){ -} -void render( RenderStateFlags state ) const { - glBegin( GL_POINTS ); - glColor3fv( vector3_to_array( m_eclass.color ) ); - glVertex3fv( vector3_to_array( m_center ) ); - glEnd(); -} + RenderLightCenter( const Vector3& center, EntityClass& eclass ) : m_center( center ), m_eclass( eclass ){ + } + void render( RenderStateFlags state ) const { + glBegin( GL_POINTS ); + glColor3fv( vector3_to_array( m_eclass.color ) ); + glVertex3fv( vector3_to_array( m_center ) ); + glEnd(); + } }; Shader* RenderLightCenter::m_state = 0; class RenderLightProjection : public OpenGLRenderable { -const Matrix4& m_projection; + const Matrix4& m_projection; public: -RenderLightProjection( const Matrix4& projection ) : m_projection( projection ){ -} -void render( RenderStateFlags state ) const { - Matrix4 unproject( matrix4_full_inverse( m_projection ) ); - Vector3 points[8]; - aabb_corners( AABB( Vector3( 0.5f, 0.5f, 0.5f ), Vector3( 0.5f, 0.5f, 0.5f ) ), points ); - points[0] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[0], 1 ) ) ); - points[1] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[1], 1 ) ) ); - points[2] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[2], 1 ) ) ); - points[3] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[3], 1 ) ) ); - points[4] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[4], 1 ) ) ); - points[5] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[5], 1 ) ) ); - points[6] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[6], 1 ) ) ); - points[7] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[7], 1 ) ) ); - //Vector4 test1 = matrix4_transformed_vector4( unproject, Vector4( 0.5f, 0.5f, 0.5f, 1 ) ); - //Vector3 test2 = vector4_projected( test1 ); - aabb_draw_wire( points ); -} + RenderLightProjection( const Matrix4& projection ) : m_projection( projection ){ + } + void render( RenderStateFlags state ) const { + Matrix4 unproject( matrix4_full_inverse( m_projection ) ); + Vector3 points[8]; + aabb_corners( AABB( Vector3( 0.5f, 0.5f, 0.5f ), Vector3( 0.5f, 0.5f, 0.5f ) ), points ); + points[0] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[0], 1 ) ) ); + points[1] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[1], 1 ) ) ); + points[2] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[2], 1 ) ) ); + points[3] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[3], 1 ) ) ); + points[4] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[4], 1 ) ) ); + points[5] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[5], 1 ) ) ); + points[6] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[6], 1 ) ) ); + points[7] = vector4_projected( matrix4_transformed_vector4( unproject, Vector4( points[7], 1 ) ) ); + //Vector4 test1 = matrix4_transformed_vector4( unproject, Vector4( 0.5f, 0.5f, 0.5f, 1 ) ); + //Vector3 test2 = vector4_projected( test1 ); + aabb_draw_wire( points ); + } }; /* inline void default_extents( Vector3& extents ){ @@ -999,58 +999,58 @@ inline void default_extents( Vector3& extents ){ */ class ShaderRef { -CopiedString m_name; -Shader* m_shader; -void capture(){ - m_shader = GlobalShaderCache().capture( m_name.c_str() ); -} -void release(){ - GlobalShaderCache().release( m_name.c_str() ); -} + CopiedString m_name; + Shader* m_shader; + void capture(){ + m_shader = GlobalShaderCache().capture( m_name.c_str() ); + } + void release(){ + GlobalShaderCache().release( m_name.c_str() ); + } public: -ShaderRef(){ - capture(); -} -~ShaderRef(){ - release(); -} -void setName( const char* name ){ - release(); - m_name = name; - capture(); -} -Shader* get() const { - return m_shader; -} + ShaderRef(){ + capture(); + } + ~ShaderRef(){ + release(); + } + void setName( const char* name ){ + release(); + m_name = name; + capture(); + } + Shader* get() const { + return m_shader; + } }; class LightShader { -ShaderRef m_shader; -void setDefault(){ - m_shader.setName( m_defaultShader ); -} + ShaderRef m_shader; + void setDefault(){ + m_shader.setName( m_defaultShader ); + } public: -static const char* m_defaultShader; + static const char* m_defaultShader; -LightShader(){ - setDefault(); -} -void valueChanged( const char* value ){ - if ( string_empty( value ) ) { + LightShader(){ setDefault(); } - else - { - m_shader.setName( value ); + void valueChanged( const char* value ){ + if ( string_empty( value ) ) { + setDefault(); + } + else + { + m_shader.setName( value ); + } + SceneChangeNotify(); } - SceneChangeNotify(); -} -typedef MemberCaller1 ValueChangedCaller; + typedef MemberCaller1 ValueChangedCaller; -Shader* get() const { - return m_shader.get(); -} + Shader* get() const { + return m_shader.get(); + } }; const char* LightShader::m_defaultShader = ""; @@ -1065,23 +1065,23 @@ inline BasicVector4& plane3_to_vector4( Plane3& self ){ inline Matrix4 matrix4_from_planes( const Plane3& left, const Plane3& right, const Plane3& bottom, const Plane3& top, const Plane3& front, const Plane3& back ){ return Matrix4( - ( right.a - left.a ) / 2, - ( top.a - bottom.a ) / 2, - ( back.a - front.a ) / 2, - right.a - ( right.a - left.a ) / 2, - ( right.b - left.b ) / 2, - ( top.b - bottom.b ) / 2, - ( back.b - front.b ) / 2, - right.b - ( right.b - left.b ) / 2, - ( right.c - left.c ) / 2, - ( top.c - bottom.c ) / 2, - ( back.c - front.c ) / 2, - right.c - ( right.c - left.c ) / 2, - ( right.d - left.d ) / 2, - ( top.d - bottom.d ) / 2, - ( back.d - front.d ) / 2, - right.d - ( right.d - left.d ) / 2 - ); + ( right.a - left.a ) / 2, + ( top.a - bottom.a ) / 2, + ( back.a - front.a ) / 2, + right.a - ( right.a - left.a ) / 2, + ( right.b - left.b ) / 2, + ( top.b - bottom.b ) / 2, + ( back.b - front.b ) / 2, + right.b - ( right.b - left.b ) / 2, + ( right.c - left.c ) / 2, + ( top.c - bottom.c ) / 2, + ( back.c - front.c ) / 2, + right.c - ( right.c - left.c ) / 2, + ( right.d - left.d ) / 2, + ( top.d - bottom.d ) / 2, + ( back.d - front.d ) / 2, + right.d - ( right.d - left.d ) / 2 + ); } const char EXCLUDE_NAME[] = "light"; @@ -1093,694 +1093,694 @@ class Light : public Editable, public Snappable { -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; -TraversableNodeSet m_traverse; -IdentityTransform m_transform; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; + TraversableNodeSet m_traverse; + IdentityTransform m_transform; -OriginKey m_originKey; -RotationKey m_rotationKey; -Float9 m_rotation; -Colour m_colour; + OriginKey m_originKey; + RotationKey m_rotationKey; + Float9 m_rotation; + Colour m_colour; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; -TraversableObserverPairRelay m_traverseObservers; -Doom3GroupOrigin m_funcStaticOrigin; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; + TraversableObserverPairRelay m_traverseObservers; + Doom3GroupOrigin m_funcStaticOrigin; -LightRadii m_radii; -Doom3LightRadius m_doom3Radius; + LightRadii m_radii; + Doom3LightRadius m_doom3Radius; -AABB m_aabb_light; + AABB m_aabb_light; -RenderLightRadiiWire m_radii_wire; -RenderLightRadiiFill m_radii_fill; -RenderLightRadiiBox m_radii_box; -RenderLightCenter m_render_center; -RenderableNamedEntity m_renderName; + RenderLightRadiiWire m_radii_wire; + RenderLightRadiiFill m_radii_fill; + RenderLightRadiiBox m_radii_box; + RenderLightCenter m_render_center; + RenderableNamedEntity m_renderName; -Vector3 m_lightOrigin; -bool m_useLightOrigin; -Float9 m_lightRotation; -bool m_useLightRotation; + Vector3 m_lightOrigin; + bool m_useLightOrigin; + Float9 m_lightRotation; + bool m_useLightRotation; -Vector3 m_lightTarget; -bool m_useLightTarget; -Vector3 m_lightUp; -bool m_useLightUp; -Vector3 m_lightRight; -bool m_useLightRight; -Vector3 m_lightStart; -bool m_useLightStart; -Vector3 m_lightEnd; -bool m_useLightEnd; + Vector3 m_lightTarget; + bool m_useLightTarget; + Vector3 m_lightUp; + bool m_useLightUp; + Vector3 m_lightRight; + bool m_useLightRight; + Vector3 m_lightStart; + bool m_useLightStart; + Vector3 m_lightEnd; + bool m_useLightEnd; -mutable AABB m_doom3AABB; -mutable Matrix4 m_doom3Rotation; -mutable Matrix4 m_doom3Projection; -mutable Frustum m_doom3Frustum; -mutable bool m_doom3ProjectionChanged; + mutable AABB m_doom3AABB; + mutable Matrix4 m_doom3Rotation; + mutable Matrix4 m_doom3Projection; + mutable Frustum m_doom3Frustum; + mutable bool m_doom3ProjectionChanged; -RenderLightProjection m_renderProjection; + RenderLightProjection m_renderProjection; -LightShader m_shader; + LightShader m_shader; -Callback m_transformChanged; -Callback m_boundsChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_boundsChanged; + Callback m_evaluateTransform; -void construct(){ - default_rotation( m_rotation ); - //m_aabb_light.origin = Vector3( 0, 0, 0 ); - //default_extents( m_aabb_light.extents ); + void construct(){ + default_rotation( m_rotation ); + //m_aabb_light.origin = Vector3( 0, 0, 0 ); + //default_extents( m_aabb_light.extents ); - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - m_keyObservers.insert( "_color", Colour::ColourChangedCaller( m_colour ) ); - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); - m_keyObservers.insert( "_light", LightRadii::PrimaryIntensityChangedCaller( m_radii ) ); - m_keyObservers.insert( "light", LightRadii::SecondaryIntensityChangedCaller( m_radii ) ); - m_keyObservers.insert( "fade", LightRadii::FadeChangedCaller( m_radii ) ); - m_keyObservers.insert( "scale", LightRadii::ScaleChangedCaller( m_radii ) ); - m_keyObservers.insert( "spawnflags", LightRadii::FlagsChangedCaller( m_radii ) ); + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + m_keyObservers.insert( "_color", Colour::ColourChangedCaller( m_colour ) ); + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); + m_keyObservers.insert( "_light", LightRadii::PrimaryIntensityChangedCaller( m_radii ) ); + m_keyObservers.insert( "light", LightRadii::SecondaryIntensityChangedCaller( m_radii ) ); + m_keyObservers.insert( "fade", LightRadii::FadeChangedCaller( m_radii ) ); + m_keyObservers.insert( "scale", LightRadii::ScaleChangedCaller( m_radii ) ); + m_keyObservers.insert( "spawnflags", LightRadii::FlagsChangedCaller( m_radii ) ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); - m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); - m_keyObservers.insert( "light_radius", Doom3LightRadius::LightRadiusChangedCaller( m_doom3Radius ) ); - m_keyObservers.insert( "light_center", Doom3LightRadius::LightCenterChangedCaller( m_doom3Radius ) ); - m_keyObservers.insert( "light_origin", Light::LightOriginChangedCaller( *this ) ); - m_keyObservers.insert( "light_rotation", Light::LightRotationChangedCaller( *this ) ); - m_keyObservers.insert( "light_target", Light::LightTargetChangedCaller( *this ) ); - m_keyObservers.insert( "light_up", Light::LightUpChangedCaller( *this ) ); - m_keyObservers.insert( "light_right", Light::LightRightChangedCaller( *this ) ); - m_keyObservers.insert( "light_start", Light::LightStartChangedCaller( *this ) ); - m_keyObservers.insert( "light_end", Light::LightEndChangedCaller( *this ) ); - m_keyObservers.insert( "texture", LightShader::ValueChangedCaller( m_shader ) ); - m_useLightTarget = m_useLightUp = m_useLightRight = m_useLightStart = m_useLightEnd = false; - m_doom3ProjectionChanged = true; + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_keyObservers.insert( "angle", RotationKey::AngleChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "rotation", RotationKey::RotationChangedCaller( m_rotationKey ) ); + m_keyObservers.insert( "light_radius", Doom3LightRadius::LightRadiusChangedCaller( m_doom3Radius ) ); + m_keyObservers.insert( "light_center", Doom3LightRadius::LightCenterChangedCaller( m_doom3Radius ) ); + m_keyObservers.insert( "light_origin", Light::LightOriginChangedCaller( *this ) ); + m_keyObservers.insert( "light_rotation", Light::LightRotationChangedCaller( *this ) ); + m_keyObservers.insert( "light_target", Light::LightTargetChangedCaller( *this ) ); + m_keyObservers.insert( "light_up", Light::LightUpChangedCaller( *this ) ); + m_keyObservers.insert( "light_right", Light::LightRightChangedCaller( *this ) ); + m_keyObservers.insert( "light_start", Light::LightStartChangedCaller( *this ) ); + m_keyObservers.insert( "light_end", Light::LightEndChangedCaller( *this ) ); + m_keyObservers.insert( "texture", LightShader::ValueChangedCaller( m_shader ) ); + m_useLightTarget = m_useLightUp = m_useLightRight = m_useLightStart = m_useLightEnd = false; + m_doom3ProjectionChanged = true; + } + + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_traverse.attach( &m_traverseObservers ); + m_traverseObservers.attach( m_funcStaticOrigin ); + + m_entity.m_isContainer = true; + } } - - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_traverse.attach( &m_traverseObservers ); - m_traverseObservers.attach( m_funcStaticOrigin ); - - m_entity.m_isContainer = true; + void destroy(){ + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_traverseObservers.detach( m_funcStaticOrigin ); + m_traverse.detach( &m_traverseObservers ); + } } -} -void destroy(){ - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_traverseObservers.detach( m_funcStaticOrigin ); - m_traverse.detach( &m_traverseObservers ); - } -} // vc 2k5 compiler fix #if _MSC_VER >= 1400 public: #endif -void updateOrigin(){ - m_boundsChanged(); + void updateOrigin(){ + m_boundsChanged(); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_funcStaticOrigin.originChanged(); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_funcStaticOrigin.originChanged(); + } + + m_doom3Radius.m_changed(); + + GlobalSelectionSystem().pivotChanged(); } - m_doom3Radius.m_changed(); - - GlobalSelectionSystem().pivotChanged(); -} - -void originChanged(){ - m_aabb_light.origin = m_useLightOrigin ? m_lightOrigin : m_originKey.m_origin; - updateOrigin(); -} -typedef MemberCaller OriginChangedCaller; - -void lightOriginChanged( const char* value ){ - m_useLightOrigin = !string_empty( value ); - if ( m_useLightOrigin ) { - read_origin( m_lightOrigin, value ); + void originChanged(){ + m_aabb_light.origin = m_useLightOrigin ? m_lightOrigin : m_originKey.m_origin; + updateOrigin(); } - originChanged(); -} -typedef MemberCaller1 LightOriginChangedCaller; + typedef MemberCaller OriginChangedCaller; -void lightTargetChanged( const char* value ){ - m_useLightTarget = !string_empty( value ); - if ( m_useLightTarget ) { - read_origin( m_lightTarget, value ); + void lightOriginChanged( const char* value ){ + m_useLightOrigin = !string_empty( value ); + if ( m_useLightOrigin ) { + read_origin( m_lightOrigin, value ); + } + originChanged(); } - projectionChanged(); -} -typedef MemberCaller1 LightTargetChangedCaller; -void lightUpChanged( const char* value ){ - m_useLightUp = !string_empty( value ); - if ( m_useLightUp ) { - read_origin( m_lightUp, value ); - } - projectionChanged(); -} -typedef MemberCaller1 LightUpChangedCaller; -void lightRightChanged( const char* value ){ - m_useLightRight = !string_empty( value ); - if ( m_useLightRight ) { - read_origin( m_lightRight, value ); - } - projectionChanged(); -} -typedef MemberCaller1 LightRightChangedCaller; -void lightStartChanged( const char* value ){ - m_useLightStart = !string_empty( value ); - if ( m_useLightStart ) { - read_origin( m_lightStart, value ); - } - projectionChanged(); -} -typedef MemberCaller1 LightStartChangedCaller; -void lightEndChanged( const char* value ){ - m_useLightEnd = !string_empty( value ); - if ( m_useLightEnd ) { - read_origin( m_lightEnd, value ); - } - projectionChanged(); -} -typedef MemberCaller1 LightEndChangedCaller; + typedef MemberCaller1 LightOriginChangedCaller; -void writeLightOrigin(){ - write_origin( m_lightOrigin, &m_entity, "light_origin" ); -} - -void updateLightRadiiBox() const { - const Matrix4& rotation = rotation_toMatrix( m_rotation ); - aabb_corners( AABB( Vector3( 0, 0, 0 ), m_doom3Radius.m_radiusTransformed ), m_radii_box.m_points ); - matrix4_transform_point( rotation, m_radii_box.m_points[0] ); - vector3_add( m_radii_box.m_points[0], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[1] ); - vector3_add( m_radii_box.m_points[1], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[2] ); - vector3_add( m_radii_box.m_points[2], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[3] ); - vector3_add( m_radii_box.m_points[3], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[4] ); - vector3_add( m_radii_box.m_points[4], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[5] ); - vector3_add( m_radii_box.m_points[5], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[6] ); - vector3_add( m_radii_box.m_points[6], m_aabb_light.origin ); - matrix4_transform_point( rotation, m_radii_box.m_points[7] ); - vector3_add( m_radii_box.m_points[7], m_aabb_light.origin ); -} - -void rotationChanged(){ - rotation_assign( m_rotation, m_useLightRotation ? m_lightRotation : m_rotationKey.m_rotation ); - GlobalSelectionSystem().pivotChanged(); -} -typedef MemberCaller RotationChangedCaller; - -void lightRotationChanged( const char* value ){ - m_useLightRotation = !string_empty( value ); - if ( m_useLightRotation ) { - read_rotation( m_lightRotation, value ); + void lightTargetChanged( const char* value ){ + m_useLightTarget = !string_empty( value ); + if ( m_useLightTarget ) { + read_origin( m_lightTarget, value ); + } + projectionChanged(); } - rotationChanged(); -} -typedef MemberCaller1 LightRotationChangedCaller; + typedef MemberCaller1 LightTargetChangedCaller; + void lightUpChanged( const char* value ){ + m_useLightUp = !string_empty( value ); + if ( m_useLightUp ) { + read_origin( m_lightUp, value ); + } + projectionChanged(); + } + typedef MemberCaller1 LightUpChangedCaller; + void lightRightChanged( const char* value ){ + m_useLightRight = !string_empty( value ); + if ( m_useLightRight ) { + read_origin( m_lightRight, value ); + } + projectionChanged(); + } + typedef MemberCaller1 LightRightChangedCaller; + void lightStartChanged( const char* value ){ + m_useLightStart = !string_empty( value ); + if ( m_useLightStart ) { + read_origin( m_lightStart, value ); + } + projectionChanged(); + } + typedef MemberCaller1 LightStartChangedCaller; + void lightEndChanged( const char* value ){ + m_useLightEnd = !string_empty( value ); + if ( m_useLightEnd ) { + read_origin( m_lightEnd, value ); + } + projectionChanged(); + } + typedef MemberCaller1 LightEndChangedCaller; + + void writeLightOrigin(){ + write_origin( m_lightOrigin, &m_entity, "light_origin" ); + } + + void updateLightRadiiBox() const { + const Matrix4& rotation = rotation_toMatrix( m_rotation ); + aabb_corners( AABB( Vector3( 0, 0, 0 ), m_doom3Radius.m_radiusTransformed ), m_radii_box.m_points ); + matrix4_transform_point( rotation, m_radii_box.m_points[0] ); + vector3_add( m_radii_box.m_points[0], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[1] ); + vector3_add( m_radii_box.m_points[1], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[2] ); + vector3_add( m_radii_box.m_points[2], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[3] ); + vector3_add( m_radii_box.m_points[3], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[4] ); + vector3_add( m_radii_box.m_points[4], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[5] ); + vector3_add( m_radii_box.m_points[5], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[6] ); + vector3_add( m_radii_box.m_points[6], m_aabb_light.origin ); + matrix4_transform_point( rotation, m_radii_box.m_points[7] ); + vector3_add( m_radii_box.m_points[7], m_aabb_light.origin ); + } + + void rotationChanged(){ + rotation_assign( m_rotation, m_useLightRotation ? m_lightRotation : m_rotationKey.m_rotation ); + GlobalSelectionSystem().pivotChanged(); + } + typedef MemberCaller RotationChangedCaller; + + void lightRotationChanged( const char* value ){ + m_useLightRotation = !string_empty( value ); + if ( m_useLightRotation ) { + read_rotation( m_lightRotation, value ); + } + rotationChanged(); + } + typedef MemberCaller1 LightRotationChangedCaller; public: -Light( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_originKey( OriginChangedCaller( *this ) ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_colour( Callback() ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_funcStaticOrigin( m_traverse, m_originKey.m_origin ), - m_doom3Radius( EntityClass_valueForKey( m_entity.getEntityClass(), "light_radius" ) ), - m_aabb_light( Vector3( 0, 0, 0 ), Vector3( 12, 12, 12 ) ), - m_radii_wire( m_radii, m_aabb_light.origin ), - m_radii_fill( m_radii, m_aabb_light.origin ), - m_radii_box( m_aabb_light.origin ), - m_render_center( m_doom3Radius.m_center, m_entity.getEntityClass() ), - m_renderName( m_named, m_aabb_light.origin, EXCLUDE_NAME ), - m_useLightOrigin( false ), - m_useLightRotation( false ), - m_renderProjection( m_doom3Projection ), - m_transformChanged( transformChanged ), - m_boundsChanged( boundsChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -Light( const Light& other, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_originKey( OriginChangedCaller( *this ) ), - m_rotationKey( RotationChangedCaller( *this ) ), - m_colour( Callback() ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_funcStaticOrigin( m_traverse, m_originKey.m_origin ), - m_doom3Radius( EntityClass_valueForKey( m_entity.getEntityClass(), "light_radius" ) ), - m_aabb_light( Vector3( 0, 0, 0 ), Vector3( 12, 12, 12 ) ), - m_radii_wire( m_radii, m_aabb_light.origin ), - m_radii_fill( m_radii, m_aabb_light.origin ), - m_radii_box( m_aabb_light.origin ), - m_render_center( m_doom3Radius.m_center, m_entity.getEntityClass() ), - m_renderName( m_named, m_aabb_light.origin, EXCLUDE_NAME ), - m_useLightOrigin( false ), - m_useLightRotation( false ), - m_renderProjection( m_doom3Projection ), - m_transformChanged( transformChanged ), - m_boundsChanged( boundsChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -~Light(){ - destroy(); -} + Light( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_originKey( OriginChangedCaller( *this ) ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_colour( Callback() ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_funcStaticOrigin( m_traverse, m_originKey.m_origin ), + m_doom3Radius( EntityClass_valueForKey( m_entity.getEntityClass(), "light_radius" ) ), + m_aabb_light( Vector3( 0, 0, 0 ), Vector3( 12, 12, 12 ) ), + m_radii_wire( m_radii, m_aabb_light.origin ), + m_radii_fill( m_radii, m_aabb_light.origin ), + m_radii_box( m_aabb_light.origin ), + m_render_center( m_doom3Radius.m_center, m_entity.getEntityClass() ), + m_renderName( m_named, m_aabb_light.origin, EXCLUDE_NAME ), + m_useLightOrigin( false ), + m_useLightRotation( false ), + m_renderProjection( m_doom3Projection ), + m_transformChanged( transformChanged ), + m_boundsChanged( boundsChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); + } + Light( const Light& other, scene::Node& node, const Callback& transformChanged, const Callback& boundsChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_originKey( OriginChangedCaller( *this ) ), + m_rotationKey( RotationChangedCaller( *this ) ), + m_colour( Callback() ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_funcStaticOrigin( m_traverse, m_originKey.m_origin ), + m_doom3Radius( EntityClass_valueForKey( m_entity.getEntityClass(), "light_radius" ) ), + m_aabb_light( Vector3( 0, 0, 0 ), Vector3( 12, 12, 12 ) ), + m_radii_wire( m_radii, m_aabb_light.origin ), + m_radii_fill( m_radii, m_aabb_light.origin ), + m_radii_box( m_aabb_light.origin ), + m_render_center( m_doom3Radius.m_center, m_entity.getEntityClass() ), + m_renderName( m_named, m_aabb_light.origin, EXCLUDE_NAME ), + m_useLightOrigin( false ), + m_useLightRotation( false ), + m_renderProjection( m_doom3Projection ), + m_transformChanged( transformChanged ), + m_boundsChanged( boundsChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); + } + ~Light(){ + destroy(); + } -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - } - m_entity.attach( m_keyObservers ); + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + } + m_entity.attach( m_keyObservers ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_funcStaticOrigin.enable(); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_funcStaticOrigin.enable(); + } } } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_funcStaticOrigin.disable(); - } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_funcStaticOrigin.disable(); + } - m_entity.detach( m_keyObservers ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.detach( m_keyObservers ); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + } + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); } - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); } -} -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} + EntityKeyValues& getEntity(){ + return m_entity; + } + const EntityKeyValues& getEntity() const { + return m_entity; + } -scene::Traversable& getTraversable(){ - return m_traverse; -} -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} + scene::Traversable& getTraversable(){ + return m_traverse; + } + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } -void attach( scene::Traversable::Observer* observer ){ - m_traverseObservers.attach( *observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_traverseObservers.detach( *observer ); -} + void attach( scene::Traversable::Observer* observer ){ + m_traverseObservers.attach( *observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_traverseObservers.detach( *observer ); + } -void render( RenderStateFlags state ) const { - light_draw( m_aabb_light, state ); -} + void render( RenderStateFlags state ) const { + light_draw( m_aabb_light, state ); + } -VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { - return volume.TestAABB( m_aabb_light, localToWorld ); -} + VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { + return volume.TestAABB( m_aabb_light, localToWorld ); + } // cache -const AABB& localAABB() const { - return m_aabb_light; -} + const AABB& localAABB() const { + return m_aabb_light; + } -mutable Matrix4 m_projectionOrientation; + mutable Matrix4 m_projectionOrientation; -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderer.SetState( m_colour.state(), Renderer::eWireframeOnly ); - renderer.SetState( m_colour.state(), Renderer::eFullMaterials ); - renderer.addRenderable( *this, localToWorld ); + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderer.SetState( m_colour.state(), Renderer::eWireframeOnly ); + renderer.SetState( m_colour.state(), Renderer::eFullMaterials ); + renderer.addRenderable( *this, localToWorld ); - if( selected ){ - if ( g_lightType != LIGHTTYPE_DOOM3 ) { - if ( g_lightRadii && string_empty( m_entity.getKeyValue( "target" ) ) ) { - if ( renderer.getStyle() == Renderer::eFullMaterials ) { - renderer.SetState( m_colour.state_additive(), Renderer::eFullMaterials ); - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.Highlight( Renderer::eFace, false ); - renderer.addRenderable( m_radii_fill, localToWorld ); + if( selected ){ + if ( g_lightType != LIGHTTYPE_DOOM3 ) { + if ( g_lightRadii && string_empty( m_entity.getKeyValue( "target" ) ) ) { + if ( renderer.getStyle() == Renderer::eFullMaterials ) { + renderer.SetState( m_colour.state_additive(), Renderer::eFullMaterials ); + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.Highlight( Renderer::eFace, false ); + renderer.addRenderable( m_radii_fill, localToWorld ); + } + else + { + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.addRenderable( m_radii_wire, localToWorld ); + } + } + } + else{ + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); + if ( isProjected() ) { + projection(); + m_projectionOrientation = rotation(); + vector4_to_vector3( m_projectionOrientation.t() ) = localAABB().origin; + renderer.addRenderable( m_renderProjection, m_projectionOrientation ); } else { + updateLightRadiiBox(); + renderer.addRenderable( m_radii_box, localToWorld ); + } + + //draw the center of the light + if ( m_doom3Radius.m_useCenterKey ) { renderer.Highlight( Renderer::ePrimitive, false ); - renderer.addRenderable( m_radii_wire, localToWorld ); + renderer.Highlight( Renderer::eFace, false ); + renderer.SetState( m_render_center.m_state, Renderer::eFullMaterials ); + renderer.SetState( m_render_center.m_state, Renderer::eWireframeOnly ); + renderer.addRenderable( m_render_center, localToWorld ); } } } + + if ( m_renderName.excluded_not() + && ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( m_aabb_light, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { + m_renderName.render( renderer, volume, localToWorld, selected ); + } + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderSolid( renderer, volume, localToWorld, selected ); + } + + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + test.BeginMesh( localToWorld ); + + SelectionIntersection best; + light_testselect( m_aabb_light, test, best ); + if ( best.valid() ) { + selector.addIntersection( best ); + } + } + + void translate( const Vector3& translation ){ + m_aabb_light.origin = origin_translated( m_aabb_light.origin, translation ); + } + void rotate( const Quaternion& rotation ){ + rotation_rotate( m_rotation, rotation ); + } + void snapto( float snap ){ + if ( g_lightType == LIGHTTYPE_DOOM3 && !m_useLightOrigin && !m_traverse.empty() ) { + m_useLightOrigin = true; + m_lightOrigin = m_originKey.m_origin; + } + + if ( m_useLightOrigin ) { + m_lightOrigin = origin_snapped( m_lightOrigin, snap ); + writeLightOrigin(); + } + else + { + m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); + m_originKey.write( &m_entity ); + } + } + void transformLightRadii( float offset ){ + m_radii.transformRadii( offset ); + } + void setLightRadius( const AABB& aabb ){ + m_aabb_light.origin = aabb.origin; + m_doom3Radius.m_radiusTransformed = aabb.extents; + } + void transformLightRadius( const Matrix4& transform ){ + matrix4_transform_point( transform, m_aabb_light.origin ); + } + void revertTransform(){ + m_aabb_light.origin = m_useLightOrigin ? m_lightOrigin : m_originKey.m_origin; + rotation_assign( m_rotation, m_useLightRotation ? m_lightRotation : m_rotationKey.m_rotation ); + m_doom3Radius.m_radiusTransformed = m_doom3Radius.m_radius; + m_radii.m_radii_transformed[0] = m_radii.m_radii[0]; + m_radii.m_radii_transformed[1] = m_radii.m_radii[1]; + m_radii.m_radii_transformed[2] = m_radii.m_radii[2]; + } + void freezeTransform(){ + if ( g_lightType == LIGHTTYPE_DOOM3 && !m_useLightOrigin && !m_traverse.empty() ) { + m_useLightOrigin = true; + } + + if ( m_useLightOrigin ) { + m_lightOrigin = m_aabb_light.origin; + writeLightOrigin(); + } + else + { + m_originKey.m_origin = m_aabb_light.origin; + m_originKey.write( &m_entity ); + } + + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + if ( !m_useLightRotation && !m_traverse.empty() ) { + m_useLightRotation = true; + } + + if ( m_useLightRotation ) { + rotation_assign( m_lightRotation, m_rotation ); + write_rotation( m_lightRotation, &m_entity, "light_rotation" ); + } + + rotation_assign( m_rotationKey.m_rotation, m_rotation ); + write_rotation( m_rotationKey.m_rotation, &m_entity ); + + m_doom3Radius.m_radius = m_doom3Radius.m_radiusTransformed; + write_origin( m_doom3Radius.m_radius, &m_entity, "light_radius" ); + } else{ - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); - if ( isProjected() ) { - projection(); - m_projectionOrientation = rotation(); - vector4_to_vector3( m_projectionOrientation.t() ) = localAABB().origin; - renderer.addRenderable( m_renderProjection, m_projectionOrientation ); - } - else - { - updateLightRadiiBox(); - renderer.addRenderable( m_radii_box, localToWorld ); - } - - //draw the center of the light - if ( m_doom3Radius.m_useCenterKey ) { - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.Highlight( Renderer::eFace, false ); - renderer.SetState( m_render_center.m_state, Renderer::eFullMaterials ); - renderer.SetState( m_render_center.m_state, Renderer::eWireframeOnly ); - renderer.addRenderable( m_render_center, localToWorld ); - } + write_intensity( m_radii.calculateIntensityFromRadii(), &m_entity ); + m_radii.m_radii[0] = m_radii.m_radii_transformed[0]; + m_radii.m_radii[1] = m_radii.m_radii_transformed[1]; + m_radii.m_radii[2] = m_radii.m_radii_transformed[2]; } } - - if ( m_renderName.excluded_not() - && ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( m_aabb_light, volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { - m_renderName.render( renderer, volume, localToWorld, selected ); + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateOrigin(); } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderSolid( renderer, volume, localToWorld, selected ); -} + typedef MemberCaller TransformChangedCaller; -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - test.BeginMesh( localToWorld ); - - SelectionIntersection best; - light_testselect( m_aabb_light, test, best ); - if ( best.valid() ) { - selector.addIntersection( best ); - } -} - -void translate( const Vector3& translation ){ - m_aabb_light.origin = origin_translated( m_aabb_light.origin, translation ); -} -void rotate( const Quaternion& rotation ){ - rotation_rotate( m_rotation, rotation ); -} -void snapto( float snap ){ - if ( g_lightType == LIGHTTYPE_DOOM3 && !m_useLightOrigin && !m_traverse.empty() ) { - m_useLightOrigin = true; - m_lightOrigin = m_originKey.m_origin; + mutable Matrix4 m_localPivot; + const Matrix4& getLocalPivot() const { + m_localPivot = rotation_toMatrix( m_rotation ); + vector4_to_vector3( m_localPivot.t() ) = m_aabb_light.origin; + return m_localPivot; } - if ( m_useLightOrigin ) { - m_lightOrigin = origin_snapped( m_lightOrigin, snap ); - writeLightOrigin(); - } - else - { - m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); - m_originKey.write( &m_entity ); - } -} -void transformLightRadii( float offset ){ - m_radii.transformRadii( offset ); -} -void setLightRadius( const AABB& aabb ){ - m_aabb_light.origin = aabb.origin; - m_doom3Radius.m_radiusTransformed = aabb.extents; -} -void transformLightRadius( const Matrix4& transform ){ - matrix4_transform_point( transform, m_aabb_light.origin ); -} -void revertTransform(){ - m_aabb_light.origin = m_useLightOrigin ? m_lightOrigin : m_originKey.m_origin; - rotation_assign( m_rotation, m_useLightRotation ? m_lightRotation : m_rotationKey.m_rotation ); - m_doom3Radius.m_radiusTransformed = m_doom3Radius.m_radius; - m_radii.m_radii_transformed[0] = m_radii.m_radii[0]; - m_radii.m_radii_transformed[1] = m_radii.m_radii[1]; - m_radii.m_radii_transformed[2] = m_radii.m_radii[2]; -} -void freezeTransform(){ - if ( g_lightType == LIGHTTYPE_DOOM3 && !m_useLightOrigin && !m_traverse.empty() ) { - m_useLightOrigin = true; + void setLightChangedCallback( const Callback& callback ){ + m_doom3Radius.m_changed = callback; } - if ( m_useLightOrigin ) { - m_lightOrigin = m_aabb_light.origin; - writeLightOrigin(); + const AABB& aabb() const { + m_doom3AABB = AABB( m_aabb_light.origin, m_doom3Radius.m_radiusTransformed ); + return m_doom3AABB; } - else - { - m_originKey.m_origin = m_aabb_light.origin; - m_originKey.write( &m_entity ); - } - - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - if ( !m_useLightRotation && !m_traverse.empty() ) { - m_useLightRotation = true; + bool testAABB( const AABB& other ) const { + if ( isProjected() ) { + Matrix4 transform = rotation(); + vector4_to_vector3( transform.t() ) = localAABB().origin; + projection(); + Frustum frustum( frustum_transformed( m_doom3Frustum, transform ) ); + return frustum_test_aabb( frustum, other ) != c_volumeOutside; } + // test against an AABB which contains the rotated bounds of this light. + const AABB& bounds = aabb(); + return aabb_intersects_aabb( other, AABB( + bounds.origin, + Vector3( + static_cast( fabs( m_rotation[0] * bounds.extents[0] ) + + fabs( m_rotation[3] * bounds.extents[1] ) + + fabs( m_rotation[6] * bounds.extents[2] ) ), + static_cast( fabs( m_rotation[1] * bounds.extents[0] ) + + fabs( m_rotation[4] * bounds.extents[1] ) + + fabs( m_rotation[7] * bounds.extents[2] ) ), + static_cast( fabs( m_rotation[2] * bounds.extents[0] ) + + fabs( m_rotation[5] * bounds.extents[1] ) + + fabs( m_rotation[8] * bounds.extents[2] ) ) + ) + ) ); + } - if ( m_useLightRotation ) { - rotation_assign( m_lightRotation, m_rotation ); - write_rotation( m_lightRotation, &m_entity, "light_rotation" ); + const Matrix4& rotation() const { + m_doom3Rotation = rotation_toMatrix( m_rotation ); + return m_doom3Rotation; + } + const Vector3& offset() const { + return m_doom3Radius.m_center; + } + const Vector3& colour() const { + return m_colour.m_colour; + } + + bool isProjected() const { + return m_useLightTarget && m_useLightUp && m_useLightRight; + } + void projectionChanged(){ + m_doom3ProjectionChanged = true; + m_doom3Radius.m_changed(); + SceneChangeNotify(); + } + + const Matrix4& projection() const { + if ( !m_doom3ProjectionChanged ) { + return m_doom3Projection; } - - rotation_assign( m_rotationKey.m_rotation, m_rotation ); - write_rotation( m_rotationKey.m_rotation, &m_entity ); - - m_doom3Radius.m_radius = m_doom3Radius.m_radiusTransformed; - write_origin( m_doom3Radius.m_radius, &m_entity, "light_radius" ); - } - else{ - write_intensity( m_radii.calculateIntensityFromRadii(), &m_entity ); - m_radii.m_radii[0] = m_radii.m_radii_transformed[0]; - m_radii.m_radii[1] = m_radii.m_radii_transformed[1]; - m_radii.m_radii[2] = m_radii.m_radii_transformed[2]; - } -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateOrigin(); -} -typedef MemberCaller TransformChangedCaller; - -mutable Matrix4 m_localPivot; -const Matrix4& getLocalPivot() const { - m_localPivot = rotation_toMatrix( m_rotation ); - vector4_to_vector3( m_localPivot.t() ) = m_aabb_light.origin; - return m_localPivot; -} - -void setLightChangedCallback( const Callback& callback ){ - m_doom3Radius.m_changed = callback; -} - -const AABB& aabb() const { - m_doom3AABB = AABB( m_aabb_light.origin, m_doom3Radius.m_radiusTransformed ); - return m_doom3AABB; -} -bool testAABB( const AABB& other ) const { - if ( isProjected() ) { - Matrix4 transform = rotation(); - vector4_to_vector3( transform.t() ) = localAABB().origin; - projection(); - Frustum frustum( frustum_transformed( m_doom3Frustum, transform ) ); - return frustum_test_aabb( frustum, other ) != c_volumeOutside; - } - // test against an AABB which contains the rotated bounds of this light. - const AABB& bounds = aabb(); - return aabb_intersects_aabb( other, AABB( - bounds.origin, - Vector3( - static_cast( fabs( m_rotation[0] * bounds.extents[0] ) - + fabs( m_rotation[3] * bounds.extents[1] ) - + fabs( m_rotation[6] * bounds.extents[2] ) ), - static_cast( fabs( m_rotation[1] * bounds.extents[0] ) - + fabs( m_rotation[4] * bounds.extents[1] ) - + fabs( m_rotation[7] * bounds.extents[2] ) ), - static_cast( fabs( m_rotation[2] * bounds.extents[0] ) - + fabs( m_rotation[5] * bounds.extents[1] ) - + fabs( m_rotation[8] * bounds.extents[2] ) ) - ) - ) ); -} - -const Matrix4& rotation() const { - m_doom3Rotation = rotation_toMatrix( m_rotation ); - return m_doom3Rotation; -} -const Vector3& offset() const { - return m_doom3Radius.m_center; -} -const Vector3& colour() const { - return m_colour.m_colour; -} - -bool isProjected() const { - return m_useLightTarget && m_useLightUp && m_useLightRight; -} -void projectionChanged(){ - m_doom3ProjectionChanged = true; - m_doom3Radius.m_changed(); - SceneChangeNotify(); -} - -const Matrix4& projection() const { - if ( !m_doom3ProjectionChanged ) { - return m_doom3Projection; - } - m_doom3ProjectionChanged = false; - m_doom3Projection = g_matrix4_identity; - matrix4_translate_by_vec3( m_doom3Projection, Vector3( 0.5f, 0.5f, 0 ) ); - matrix4_scale_by_vec3( m_doom3Projection, Vector3( 0.5f, 0.5f, 1 ) ); + m_doom3ProjectionChanged = false; + m_doom3Projection = g_matrix4_identity; + matrix4_translate_by_vec3( m_doom3Projection, Vector3( 0.5f, 0.5f, 0 ) ); + matrix4_scale_by_vec3( m_doom3Projection, Vector3( 0.5f, 0.5f, 1 ) ); #if 0 - Vector3 right = vector3_cross( m_lightUp, vector3_normalised( m_lightTarget ) ); - Vector3 up = vector3_cross( vector3_normalised( m_lightTarget ), m_lightRight ); - Vector3 target = m_lightTarget; - Matrix4 test( - -right.x(), -right.y(), -right.z(), 0, - -up.x(), -up.y(), -up.z(), 0, - -target.x(), -target.y(), -target.z(), 0, - 0, 0, 0, 1 + Vector3 right = vector3_cross( m_lightUp, vector3_normalised( m_lightTarget ) ); + Vector3 up = vector3_cross( vector3_normalised( m_lightTarget ), m_lightRight ); + Vector3 target = m_lightTarget; + Matrix4 test( + -right.x(), -right.y(), -right.z(), 0, + -up.x(), -up.y(), -up.z(), 0, + -target.x(), -target.y(), -target.z(), 0, + 0, 0, 0, 1 ); - Matrix4 frustum = matrix4_frustum( -0.01, 0.01, -0.01, 0.01, 0.01, 1.0 ); - test = matrix4_full_inverse( test ); - matrix4_premultiply_by_matrix4( test, frustum ); - matrix4_multiply_by_matrix4( m_doom3Projection, test ); + Matrix4 frustum = matrix4_frustum( -0.01, 0.01, -0.01, 0.01, 0.01, 1.0 ); + test = matrix4_full_inverse( test ); + matrix4_premultiply_by_matrix4( test, frustum ); + matrix4_multiply_by_matrix4( m_doom3Projection, test ); #elif 0 - const float nearFar = 1 / 49.5f; - Vector3 right = vector3_cross( m_lightUp, vector3_normalised( m_lightTarget + m_lightRight ) ); - Vector3 up = vector3_cross( vector3_normalised( m_lightTarget + m_lightUp ), m_lightRight ); - Vector3 target = vector3_negated( m_lightTarget * ( 1 + nearFar ) ); - float scale = -1 / vector3_length( m_lightTarget ); - Matrix4 test( - -inverse( right.x() ), -inverse( up.x() ), -inverse( target.x() ), 0, - -inverse( right.y() ), -inverse( up.y() ), -inverse( target.y() ), 0, - -inverse( right.z() ), -inverse( up.z() ), -inverse( target.z() ), scale, - 0, 0, -nearFar, 0 + const float nearFar = 1 / 49.5f; + Vector3 right = vector3_cross( m_lightUp, vector3_normalised( m_lightTarget + m_lightRight ) ); + Vector3 up = vector3_cross( vector3_normalised( m_lightTarget + m_lightUp ), m_lightRight ); + Vector3 target = vector3_negated( m_lightTarget * ( 1 + nearFar ) ); + float scale = -1 / vector3_length( m_lightTarget ); + Matrix4 test( + -inverse( right.x() ), -inverse( up.x() ), -inverse( target.x() ), 0, + -inverse( right.y() ), -inverse( up.y() ), -inverse( target.y() ), 0, + -inverse( right.z() ), -inverse( up.z() ), -inverse( target.z() ), scale, + 0, 0, -nearFar, 0 ); - matrix4_multiply_by_matrix4( m_doom3Projection, test ); + matrix4_multiply_by_matrix4( m_doom3Projection, test ); #elif 0 - Vector3 leftA( m_lightTarget - m_lightRight ); - Vector3 leftB( m_lightRight + m_lightUp ); - Plane3 left( vector3_normalised( vector3_cross( leftA, leftB ) ) * ( 1.0 / 128 ), 0 ); - Vector3 rightA( m_lightTarget + m_lightRight ); - Vector3 rightB( vector3_cross( rightA, m_lightTarget ) ); - Plane3 right( vector3_normalised( vector3_cross( rightA, rightB ) ) * ( 1.0 / 128 ), 0 ); - Vector3 bottomA( m_lightTarget - m_lightUp ); - Vector3 bottomB( vector3_cross( bottomA, m_lightTarget ) ); - Plane3 bottom( vector3_normalised( vector3_cross( bottomA, bottomB ) ) * ( 1.0 / 128 ), 0 ); - Vector3 topA( m_lightTarget + m_lightUp ); - Vector3 topB( vector3_cross( topA, m_lightTarget ) ); - Plane3 top( vector3_normalised( vector3_cross( topA, topB ) ) * ( 1.0 / 128 ), 0 ); - Plane3 front( vector3_normalised( m_lightTarget ) * ( 1.0 / 128 ), 1 ); - Plane3 back( vector3_normalised( vector3_negated( m_lightTarget ) ) * ( 1.0 / 128 ), 0 ); - Matrix4 test( matrix4_from_planes( plane3_flipped( left ), plane3_flipped( right ), plane3_flipped( bottom ), plane3_flipped( top ), plane3_flipped( front ), plane3_flipped( back ) ) ); - matrix4_multiply_by_matrix4( m_doom3Projection, test ); + Vector3 leftA( m_lightTarget - m_lightRight ); + Vector3 leftB( m_lightRight + m_lightUp ); + Plane3 left( vector3_normalised( vector3_cross( leftA, leftB ) ) * ( 1.0 / 128 ), 0 ); + Vector3 rightA( m_lightTarget + m_lightRight ); + Vector3 rightB( vector3_cross( rightA, m_lightTarget ) ); + Plane3 right( vector3_normalised( vector3_cross( rightA, rightB ) ) * ( 1.0 / 128 ), 0 ); + Vector3 bottomA( m_lightTarget - m_lightUp ); + Vector3 bottomB( vector3_cross( bottomA, m_lightTarget ) ); + Plane3 bottom( vector3_normalised( vector3_cross( bottomA, bottomB ) ) * ( 1.0 / 128 ), 0 ); + Vector3 topA( m_lightTarget + m_lightUp ); + Vector3 topB( vector3_cross( topA, m_lightTarget ) ); + Plane3 top( vector3_normalised( vector3_cross( topA, topB ) ) * ( 1.0 / 128 ), 0 ); + Plane3 front( vector3_normalised( m_lightTarget ) * ( 1.0 / 128 ), 1 ); + Plane3 back( vector3_normalised( vector3_negated( m_lightTarget ) ) * ( 1.0 / 128 ), 0 ); + Matrix4 test( matrix4_from_planes( plane3_flipped( left ), plane3_flipped( right ), plane3_flipped( bottom ), plane3_flipped( top ), plane3_flipped( front ), plane3_flipped( back ) ) ); + matrix4_multiply_by_matrix4( m_doom3Projection, test ); #else - Plane3 lightProject[4]; + Plane3 lightProject[4]; - Vector3 start = m_useLightStart && m_useLightEnd ? m_lightStart : vector3_normalised( m_lightTarget ); - Vector3 stop = m_useLightStart && m_useLightEnd ? m_lightEnd : m_lightTarget; + Vector3 start = m_useLightStart && m_useLightEnd ? m_lightStart : vector3_normalised( m_lightTarget ); + Vector3 stop = m_useLightStart && m_useLightEnd ? m_lightEnd : m_lightTarget; - float rLen = vector3_length( m_lightRight ); - Vector3 right = vector3_divided( m_lightRight, rLen ); - float uLen = vector3_length( m_lightUp ); - Vector3 up = vector3_divided( m_lightUp, uLen ); - Vector3 normal = vector3_normalised( vector3_cross( up, right ) ); + float rLen = vector3_length( m_lightRight ); + Vector3 right = vector3_divided( m_lightRight, rLen ); + float uLen = vector3_length( m_lightUp ); + Vector3 up = vector3_divided( m_lightUp, uLen ); + Vector3 normal = vector3_normalised( vector3_cross( up, right ) ); - float dist = vector3_dot( m_lightTarget, normal ); - if ( dist < 0 ) { - dist = -dist; - normal = vector3_negated( normal ); - } + float dist = vector3_dot( m_lightTarget, normal ); + if ( dist < 0 ) { + dist = -dist; + normal = vector3_negated( normal ); + } - right *= ( 0.5f * dist ) / rLen; - up *= -( 0.5f * dist ) / uLen; + right *= ( 0.5f * dist ) / rLen; + up *= -( 0.5f * dist ) / uLen; - lightProject[2] = Plane3( normal, 0 ); - lightProject[0] = Plane3( right, 0 ); - lightProject[1] = Plane3( up, 0 ); + lightProject[2] = Plane3( normal, 0 ); + lightProject[0] = Plane3( right, 0 ); + lightProject[1] = Plane3( up, 0 ); - // now offset to center - Vector4 targetGlobal( m_lightTarget, 1 ); - { - float a = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[0] ) ); - float b = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[2] ) ); - float ofs = 0.5f - a / b; - plane3_to_vector4( lightProject[0] ) += plane3_to_vector4( lightProject[2] ) * ofs; - } - { - float a = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[1] ) ); - float b = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[2] ) ); - float ofs = 0.5f - a / b; - plane3_to_vector4( lightProject[1] ) += plane3_to_vector4( lightProject[2] ) * ofs; - } + // now offset to center + Vector4 targetGlobal( m_lightTarget, 1 ); + { + float a = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[0] ) ); + float b = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[2] ) ); + float ofs = 0.5f - a / b; + plane3_to_vector4( lightProject[0] ) += plane3_to_vector4( lightProject[2] ) * ofs; + } + { + float a = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[1] ) ); + float b = vector4_dot( targetGlobal, plane3_to_vector4( lightProject[2] ) ); + float ofs = 0.5f - a / b; + plane3_to_vector4( lightProject[1] ) += plane3_to_vector4( lightProject[2] ) * ofs; + } - // set the falloff vector - Vector3 falloff = stop - start; - float length = vector3_length( falloff ); - falloff = vector3_divided( falloff, length ); - if ( length <= 0 ) { - length = 1; - } - falloff *= ( 1.0f / length ); - lightProject[3] = Plane3( falloff, -vector3_dot( start, falloff ) ); + // set the falloff vector + Vector3 falloff = stop - start; + float length = vector3_length( falloff ); + falloff = vector3_divided( falloff, length ); + if ( length <= 0 ) { + length = 1; + } + falloff *= ( 1.0f / length ); + lightProject[3] = Plane3( falloff, -vector3_dot( start, falloff ) ); - // we want the planes of s=0, s=q, t=0, and t=q - m_doom3Frustum.left = lightProject[0]; - m_doom3Frustum.bottom = lightProject[1]; - m_doom3Frustum.right = Plane3( lightProject[2].normal() - lightProject[0].normal(), lightProject[2].dist() - lightProject[0].dist() ); - m_doom3Frustum.top = Plane3( lightProject[2].normal() - lightProject[1].normal(), lightProject[2].dist() - lightProject[1].dist() ); + // we want the planes of s=0, s=q, t=0, and t=q + m_doom3Frustum.left = lightProject[0]; + m_doom3Frustum.bottom = lightProject[1]; + m_doom3Frustum.right = Plane3( lightProject[2].normal() - lightProject[0].normal(), lightProject[2].dist() - lightProject[0].dist() ); + m_doom3Frustum.top = Plane3( lightProject[2].normal() - lightProject[1].normal(), lightProject[2].dist() - lightProject[1].dist() ); - // we want the planes of s=0 and s=1 for front and rear clipping planes - m_doom3Frustum.front = lightProject[3]; + // we want the planes of s=0 and s=1 for front and rear clipping planes + m_doom3Frustum.front = lightProject[3]; - m_doom3Frustum.back = lightProject[3]; - m_doom3Frustum.back.dist() -= 1.0f; - m_doom3Frustum.back = plane3_flipped( m_doom3Frustum.back ); + m_doom3Frustum.back = lightProject[3]; + m_doom3Frustum.back.dist() -= 1.0f; + m_doom3Frustum.back = plane3_flipped( m_doom3Frustum.back ); - Matrix4 test( matrix4_from_planes( m_doom3Frustum.left, m_doom3Frustum.right, m_doom3Frustum.bottom, m_doom3Frustum.top, m_doom3Frustum.front, m_doom3Frustum.back ) ); - matrix4_multiply_by_matrix4( m_doom3Projection, test ); + Matrix4 test( matrix4_from_planes( m_doom3Frustum.left, m_doom3Frustum.right, m_doom3Frustum.bottom, m_doom3Frustum.top, m_doom3Frustum.front, m_doom3Frustum.back ) ); + matrix4_multiply_by_matrix4( m_doom3Projection, test ); - m_doom3Frustum.left = plane3_normalised( m_doom3Frustum.left ); - m_doom3Frustum.right = plane3_normalised( m_doom3Frustum.right ); - m_doom3Frustum.bottom = plane3_normalised( m_doom3Frustum.bottom ); - m_doom3Frustum.top = plane3_normalised( m_doom3Frustum.top ); - m_doom3Frustum.back = plane3_normalised( m_doom3Frustum.back ); - m_doom3Frustum.front = plane3_normalised( m_doom3Frustum.front ); + m_doom3Frustum.left = plane3_normalised( m_doom3Frustum.left ); + m_doom3Frustum.right = plane3_normalised( m_doom3Frustum.right ); + m_doom3Frustum.bottom = plane3_normalised( m_doom3Frustum.bottom ); + m_doom3Frustum.top = plane3_normalised( m_doom3Frustum.top ); + m_doom3Frustum.back = plane3_normalised( m_doom3Frustum.back ); + m_doom3Frustum.front = plane3_normalised( m_doom3Frustum.front ); #endif - //matrix4_scale_by_vec3(m_doom3Projection, Vector3(1.0 / 128, 1.0 / 128, 1.0 / 128)); - return m_doom3Projection; -} + //matrix4_scale_by_vec3(m_doom3Projection, Vector3(1.0 / 128, 1.0 / 128, 1.0 / 128)); + return m_doom3Projection; + } -Shader* getShader() const { - return m_shader.get(); -} + Shader* getShader() const { + return m_shader.get(); + } }; class LightInstance : @@ -1792,195 +1792,195 @@ class LightInstance : public PlaneSelectable, public ComponentSelectionTestable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceContainedCast::install( m_casts ); - //InstanceContainedCast::install(m_casts); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - -Light& m_contained; -DragPlanes m_dragPlanes; // dragplanes for lightresizing using mousedrag -ScaleRadius m_scaleRadius; -public: -typedef LazyStatic StaticTypeCasts; - -Bounded& get( NullType){ - return m_contained; -} - -STRING_CONSTANT( Name, "LightInstance" ); - -LightInstance( const scene::Path& path, scene::Instance* parent, Light& contained ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), - TransformModifier( Light::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), - m_contained( contained ), - m_dragPlanes( SelectedChangedComponentCaller( *this ) ), - m_scaleRadius( SelectedChangedComponentCaller( *this ) ){ - m_contained.instanceAttach( Instance::path() ); - - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - GlobalShaderCache().attach( *this ); - m_contained.setLightChangedCallback( LightChangedCaller( *this ) ); - } - - StaticRenderableConnectionLines::instance().attach( *this ); -} -~LightInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); - - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_contained.setLightChangedCallback( Callback() ); - GlobalShaderCache().detach( *this ); - } - - m_contained.instanceDetach( Instance::path() ); -} -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void testSelect( Selector& selector, SelectionTest& test ){ - m_contained.testSelect( selector, test, Instance::localToWorld() ); -} - -void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ - test.BeginMesh( localToWorld() ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.selectPlanes( m_contained.aabb(), selector, test, selectedPlaneCallback, rotation() ); - } - else if( g_lightRadii ){ // only scale radius while it is displayed - m_scaleRadius.selectPlanes( selector, test, selectedPlaneCallback ); - } -} -void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.selectReversedPlanes( m_contained.aabb(), selector, selectedPlanes, rotation() ); - } -} - -void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - test.BeginMesh( localToWorld() ); - m_dragPlanes.bestPlaneDirect( m_contained.aabb(), test, plane, intersection, rotation() ); - } -} -void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - test.BeginMesh( localToWorld() ); - m_dragPlanes.bestPlaneIndirect( m_contained.aabb(), test, plane, intersection, dist, rotation() ); - } -} -void selectByPlane( const Plane3& plane ){ - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.selectByPlane( m_contained.aabb(), plane, rotation() ); - } -} -void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.gatherPolygonsByPlane( m_contained.aabb(), plane, polygons, rotation() ); - } -} - - -bool isSelectedComponents() const { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - return m_dragPlanes.isSelected(); - } - else{ - return m_scaleRadius.isSelected(); - } -} -void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ - if ( mode == SelectionSystem::eFace ) { - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.setSelected( false ); - } - else{ - m_scaleRadius.setSelected( false ); - } - } -} -void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { -} - -void selectedChangedComponent( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); - GlobalSelectionSystem().onComponentSelection( *this, selectable ); -} -typedef MemberCaller1 SelectedChangedComponentCaller; - -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); - m_contained.rotate( getRotation() ); - } - else + class TypeCasts { - //globalOutputStream() << getTranslation() << "\n"; - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_dragPlanes.m_bounds = m_contained.aabb(); - m_contained.setLightRadius( m_dragPlanes.evaluateResize( getTranslation(), rotation() ) ); + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceContainedCast::install( m_casts ); + //InstanceContainedCast::install(m_casts); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); } - else{ - m_contained.transformLightRadii( m_scaleRadius.evaluateResize( getTranslation() ) ); + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + + Light& m_contained; + DragPlanes m_dragPlanes; // dragplanes for lightresizing using mousedrag + ScaleRadius m_scaleRadius; +public: + typedef LazyStatic StaticTypeCasts; + + Bounded& get( NullType){ + return m_contained; + } + + STRING_CONSTANT( Name, "LightInstance" ); + + LightInstance( const scene::Path& path, scene::Instance* parent, Light& contained ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), contained.getEntity(), *this ), + TransformModifier( Light::TransformChangedCaller( contained ), ApplyTransformCaller( *this ) ), + m_contained( contained ), + m_dragPlanes( SelectedChangedComponentCaller( *this ) ), + m_scaleRadius( SelectedChangedComponentCaller( *this ) ){ + m_contained.instanceAttach( Instance::path() ); + + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + GlobalShaderCache().attach( *this ); + m_contained.setLightChangedCallback( LightChangedCaller( *this ) ); + } + + StaticRenderableConnectionLines::instance().attach( *this ); + } + ~LightInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); + + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_contained.setLightChangedCallback( Callback() ); + GlobalShaderCache().detach( *this ); + } + + m_contained.instanceDetach( Instance::path() ); + } + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void testSelect( Selector& selector, SelectionTest& test ){ + m_contained.testSelect( selector, test, Instance::localToWorld() ); + } + + void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ + test.BeginMesh( localToWorld() ); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.selectPlanes( m_contained.aabb(), selector, test, selectedPlaneCallback, rotation() ); + } + else if( g_lightRadii ){ // only scale radius while it is displayed + m_scaleRadius.selectPlanes( selector, test, selectedPlaneCallback ); + } + } + void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.selectReversedPlanes( m_contained.aabb(), selector, selectedPlanes, rotation() ); } } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; -void lightChanged(){ - GlobalShaderCache().changed( *this ); -} -typedef MemberCaller LightChangedCaller; + void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + test.BeginMesh( localToWorld() ); + m_dragPlanes.bestPlaneDirect( m_contained.aabb(), test, plane, intersection, rotation() ); + } + } + void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + test.BeginMesh( localToWorld() ); + m_dragPlanes.bestPlaneIndirect( m_contained.aabb(), test, plane, intersection, dist, rotation() ); + } + } + void selectByPlane( const Plane3& plane ){ + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.selectByPlane( m_contained.aabb(), plane, rotation() ); + } + } + void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.gatherPolygonsByPlane( m_contained.aabb(), plane, polygons, rotation() ); + } + } -Shader* getShader() const { - return m_contained.getShader(); -} -const AABB& aabb() const { - return m_contained.aabb(); -} -bool testAABB( const AABB& other ) const { - return m_contained.testAABB( other ); -} -const Matrix4& rotation() const { - return m_contained.rotation(); -} -const Vector3& offset() const { - return m_contained.offset(); -} -const Vector3& colour() const { - return m_contained.colour(); -} -bool isProjected() const { - return m_contained.isProjected(); -} -const Matrix4& projection() const { - return m_contained.projection(); -} + bool isSelectedComponents() const { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + return m_dragPlanes.isSelected(); + } + else{ + return m_scaleRadius.isSelected(); + } + } + void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ + if ( mode == SelectionSystem::eFace ) { + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.setSelected( false ); + } + else{ + m_scaleRadius.setSelected( false ); + } + } + } + void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { + } + + void selectedChangedComponent( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); + GlobalSelectionSystem().onComponentSelection( *this, selectable ); + } + typedef MemberCaller1 SelectedChangedComponentCaller; + + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + m_contained.rotate( getRotation() ); + } + else + { + //globalOutputStream() << getTranslation() << "\n"; + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_dragPlanes.m_bounds = m_contained.aabb(); + m_contained.setLightRadius( m_dragPlanes.evaluateResize( getTranslation(), rotation() ) ); + } + else{ + m_contained.transformLightRadii( m_scaleRadius.evaluateResize( getTranslation() ) ); + } + } + } + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; + + void lightChanged(){ + GlobalShaderCache().changed( *this ); + } + typedef MemberCaller LightChangedCaller; + + Shader* getShader() const { + return m_contained.getShader(); + } + const AABB& aabb() const { + return m_contained.aabb(); + } + bool testAABB( const AABB& other ) const { + return m_contained.testAABB( other ); + } + const Matrix4& rotation() const { + return m_contained.rotation(); + } + const Vector3& offset() const { + return m_contained.offset(); + } + const Vector3& colour() const { + return m_contained.colour(); + } + + bool isProjected() const { + return m_contained.isProjected(); + } + const Matrix4& projection() const { + return m_contained.projection(); + } }; class LightNode : @@ -1989,116 +1989,116 @@ class LightNode : public scene::Cloneable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + NodeContainedCast::install( m_casts ); + } + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; + + + scene::Node m_node; + InstanceSet m_instances; + Light m_contained; + + void construct(){ + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_contained.attach( this ); + } + } + void destroy(){ + if ( g_lightType == LIGHTTYPE_DOOM3 ) { + m_contained.detach( this ); + } + } public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - NodeContainedCast::install( m_casts ); + typedef LazyStatic StaticTypeCasts; + + scene::Traversable& get( NullType){ + return m_contained.getTraversable(); } - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; - - -scene::Node m_node; -InstanceSet m_instances; -Light m_contained; - -void construct(){ - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_contained.attach( this ); + Editable& get( NullType){ + return m_contained; } -} -void destroy(){ - if ( g_lightType == LIGHTTYPE_DOOM3 ) { - m_contained.detach( this ); + Snappable& get( NullType){ + return m_contained; + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); } -} -public: -typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_contained.getTraversable(); -} -Editable& get( NullType){ - return m_contained; -} -Snappable& get( NullType){ - return m_contained; -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} + LightNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + LightNode( const LightNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + ~LightNode(){ + destroy(); + } -LightNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -LightNode( const LightNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -~LightNode(){ - destroy(); -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + scene::Node& clone() const { + return ( new LightNode( *this ) )->node(); + } -scene::Node& clone() const { - return ( new LightNode( *this ) )->node(); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} - -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new LightInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new LightInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; void Light_Construct( LightType lightType ){ diff --git a/plugins/entity/miscmodel.cpp b/plugins/entity/miscmodel.cpp index 91848ab7..477fc5b7 100644 --- a/plugins/entity/miscmodel.cpp +++ b/plugins/entity/miscmodel.cpp @@ -58,7 +58,7 @@ class RemapKeysObserver : public Entity::Observer, public ModelSkin class RemapKey { const Callback& m_skinChangedCallback; - public: + public: CopiedString m_from; CopiedString m_to; RemapKey( const Callback& skinChangedCallback ) : m_skinChangedCallback( skinChangedCallback ){ @@ -88,44 +88,44 @@ public: RemapKeysObserver( const Callback& skinChangedCallback ) : m_skinChangedCallback( skinChangedCallback ){ } -void insert( const char* key, EntityKeyValue& value ) override { - if( string_equal_prefix( key, "_remap" ) ){ - value.attach( RemapKey::remapKeyChangedCaller( m_remapKeys.emplace( key, m_skinChangedCallback )->second ) ); - } -} -void erase( const char* key, EntityKeyValue& value ) override { - if( string_equal_prefix( key, "_remap" ) ){ - for( RemapKeys::iterator i = m_remapKeys.find( key ); i != m_remapKeys.end() && string_equal( ( *i ).first.c_str(), key ); ){ - value.detach( RemapKey::remapKeyChangedCaller( i->second ) ); - i = m_remapKeys.erase( i ); + void insert( const char* key, EntityKeyValue& value ) override { + if( string_equal_prefix( key, "_remap" ) ){ + value.attach( RemapKey::remapKeyChangedCaller( m_remapKeys.emplace( key, m_skinChangedCallback )->second ) ); + } + } + void erase( const char* key, EntityKeyValue& value ) override { + if( string_equal_prefix( key, "_remap" ) ){ + for( RemapKeys::iterator i = m_remapKeys.find( key ); i != m_remapKeys.end() && string_equal( ( *i ).first.c_str(), key ); ){ + value.detach( RemapKey::remapKeyChangedCaller( i->second ) ); + i = m_remapKeys.erase( i ); + } } } -} -void attach( ModuleObserver& observer ) override { -} -void detach( ModuleObserver& observer ) override { -} -bool realised() const override { - return true; -} -const char* getRemap( const char* name ) const override { // this logic is supposed to respect one in q3map2 - const char* to = ""; - std::size_t fromlen = 0; - for( const auto& pair : m_remapKeys ){ - const RemapKey& remapKey = pair.second; - if( remapKey.m_from == "*" && fromlen == 0 ){ // only globbing, if no respective match - to = remapKey.m_to.c_str(); - } - else if( string_equal_suffix_nocase( name, remapKey.m_from.c_str() ) && strlen( remapKey.m_from.c_str() ) > fromlen ){ // longer match has priority - to = remapKey.m_to.c_str(); - fromlen = strlen( remapKey.m_from.c_str() ); - } + void attach( ModuleObserver& observer ) override { + } + void detach( ModuleObserver& observer ) override { + } + bool realised() const override { + return true; + } + const char* getRemap( const char* name ) const override { // this logic is supposed to respect one in q3map2 + const char* to = ""; + std::size_t fromlen = 0; + for( const auto& pair : m_remapKeys ){ + const RemapKey& remapKey = pair.second; + if( remapKey.m_from == "*" && fromlen == 0 ){ // only globbing, if no respective match + to = remapKey.m_to.c_str(); + } + else if( string_equal_suffix_nocase( name, remapKey.m_from.c_str() ) && strlen( remapKey.m_from.c_str() ) > fromlen ){ // longer match has priority + to = remapKey.m_to.c_str(); + fromlen = strlen( remapKey.m_from.c_str() ); + } + } + return to; + } + void forEachRemap( const SkinRemapCallback& callback ) const override { } - return to; -} -void forEachRemap( const SkinRemapCallback& callback ) const override { -} }; @@ -134,275 +134,275 @@ const char EXCLUDE_NAME[] = "misc_model"; class MiscModel : public Snappable { -EntityKeyValues m_entity; -KeyObserverMap m_keyObservers; -RemapKeysObserver m_remapKeysObserver; -MatrixTransform m_transform; + EntityKeyValues m_entity; + KeyObserverMap m_keyObservers; + RemapKeysObserver m_remapKeysObserver; + MatrixTransform m_transform; -OriginKey m_originKey; -Vector3 m_origin; -AnglesKey m_anglesKey; -Vector3 m_angles; -ScaleKey m_scaleKey; -Vector3 m_scale; + OriginKey m_originKey; + Vector3 m_origin; + AnglesKey m_anglesKey; + Vector3 m_angles; + ScaleKey m_scaleKey; + Vector3 m_scale; -SingletonModel m_model; + SingletonModel m_model; -ClassnameFilter m_filter; -NamedEntity m_named; -NameKeys m_nameKeys; -RenderablePivot m_renderOrigin; -RenderableNamedEntity m_renderName; + ClassnameFilter m_filter; + NamedEntity m_named; + NameKeys m_nameKeys; + RenderablePivot m_renderOrigin; + RenderableNamedEntity m_renderName; -Callback m_transformChanged; -Callback m_evaluateTransform; + Callback m_transformChanged; + Callback m_evaluateTransform; -void construct(){ - m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); - m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); - m_keyObservers.insert( m_entity.getEntityClass().miscmodel_key(), SingletonModel::ModelChangedCaller( m_model ) ); - m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); - m_keyObservers.insert( "angle", AnglesKey::AngleChangedCaller( m_anglesKey ) ); - m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); - m_keyObservers.insert( "modelscale", ScaleKey::UniformScaleChangedCaller( m_scaleKey ) ); - m_keyObservers.insert( "modelscale_vec", ScaleKey::ScaleChangedCaller( m_scaleKey ) ); -} + void construct(){ + m_keyObservers.insert( "classname", ClassnameFilter::ClassnameChangedCaller( m_filter ) ); + m_keyObservers.insert( Static::instance().m_nameKey, NamedEntity::IdentifierChangedCaller( m_named ) ); + m_keyObservers.insert( m_entity.getEntityClass().miscmodel_key(), SingletonModel::ModelChangedCaller( m_model ) ); + m_keyObservers.insert( "origin", OriginKey::OriginChangedCaller( m_originKey ) ); + m_keyObservers.insert( "angle", AnglesKey::AngleChangedCaller( m_anglesKey ) ); + m_keyObservers.insert( "angles", AnglesKey::AnglesChangedCaller( m_anglesKey ) ); + m_keyObservers.insert( "modelscale", ScaleKey::UniformScaleChangedCaller( m_scaleKey ) ); + m_keyObservers.insert( "modelscale_vec", ScaleKey::ScaleChangedCaller( m_scaleKey ) ); + } -void updateTransform(){ - m_transform.localToParent() = g_matrix4_identity; - matrix4_transform_by_euler_xyz_degrees( m_transform.localToParent(), m_origin, m_angles, m_scale ); - m_transformChanged(); -} + void updateTransform(){ + m_transform.localToParent() = g_matrix4_identity; + matrix4_transform_by_euler_xyz_degrees( m_transform.localToParent(), m_origin, m_angles, m_scale ); + m_transformChanged(); + } // vc 2k5 compiler fix #if _MSC_VER >= 1400 public: #endif -void originChanged(){ - m_origin = m_originKey.m_origin; - updateTransform(); -} -typedef MemberCaller OriginChangedCaller; -void anglesChanged(){ - m_angles = m_anglesKey.m_angles; - updateTransform(); -} -typedef MemberCaller AnglesChangedCaller; -void scaleChanged(){ - m_scale = m_scaleKey.m_scale; - updateTransform(); -} -typedef MemberCaller ScaleChangedCaller; - -void skinChanged(){ - scene::Node* node = m_model.getNode(); - if ( node != 0 ) { - Node_modelSkinChanged( *node ); + void originChanged(){ + m_origin = m_originKey.m_origin; + updateTransform(); } -} -typedef MemberCaller SkinChangedCaller; + typedef MemberCaller OriginChangedCaller; + void anglesChanged(){ + m_angles = m_anglesKey.m_angles; + updateTransform(); + } + typedef MemberCaller AnglesChangedCaller; + void scaleChanged(){ + m_scale = m_scaleKey.m_scale; + updateTransform(); + } + typedef MemberCaller ScaleChangedCaller; + + void skinChanged(){ + scene::Node* node = m_model.getNode(); + if ( node != 0 ) { + Node_modelSkinChanged( *node ); + } + } + typedef MemberCaller SkinChangedCaller; public: -MiscModel( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( eclass ), - m_remapKeysObserver( SkinChangedCaller( *this ) ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_anglesKey( AnglesChangedCaller( *this ) ), - m_angles( ANGLESKEY_IDENTITY ), - m_scaleKey( ScaleChangedCaller( *this ) ), - m_scale( SCALEKEY_IDENTITY ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_renderName( m_named, g_vector3_identity, EXCLUDE_NAME ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} -MiscModel( const MiscModel& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : - m_entity( other.m_entity ), - m_remapKeysObserver( SkinChangedCaller( *this ) ), - m_originKey( OriginChangedCaller( *this ) ), - m_origin( ORIGINKEY_IDENTITY ), - m_anglesKey( AnglesChangedCaller( *this ) ), - m_angles( ANGLESKEY_IDENTITY ), - m_scaleKey( ScaleChangedCaller( *this ) ), - m_scale( SCALEKEY_IDENTITY ), - m_filter( m_entity, node ), - m_named( m_entity ), - m_nameKeys( m_entity ), - m_renderName( m_named, g_vector3_identity, EXCLUDE_NAME ), - m_transformChanged( transformChanged ), - m_evaluateTransform( evaluateTransform ){ - construct(); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_filter.instanceAttach(); - m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - m_entity.attach( m_keyObservers ); - m_entity.attach( m_remapKeysObserver ); + MiscModel( EntityClass* eclass, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( eclass ), + m_remapKeysObserver( SkinChangedCaller( *this ) ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_anglesKey( AnglesChangedCaller( *this ) ), + m_angles( ANGLESKEY_IDENTITY ), + m_scaleKey( ScaleChangedCaller( *this ) ), + m_scale( SCALEKEY_IDENTITY ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_renderName( m_named, g_vector3_identity, EXCLUDE_NAME ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_entity.detach( m_remapKeysObserver ); - m_entity.detach( m_keyObservers ); - m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - m_filter.instanceDetach(); + MiscModel( const MiscModel& other, scene::Node& node, const Callback& transformChanged, const Callback& evaluateTransform ) : + m_entity( other.m_entity ), + m_remapKeysObserver( SkinChangedCaller( *this ) ), + m_originKey( OriginChangedCaller( *this ) ), + m_origin( ORIGINKEY_IDENTITY ), + m_anglesKey( AnglesChangedCaller( *this ) ), + m_angles( ANGLESKEY_IDENTITY ), + m_scaleKey( ScaleChangedCaller( *this ) ), + m_scale( SCALEKEY_IDENTITY ), + m_filter( m_entity, node ), + m_named( m_entity ), + m_nameKeys( m_entity ), + m_renderName( m_named, g_vector3_identity, EXCLUDE_NAME ), + m_transformChanged( transformChanged ), + m_evaluateTransform( evaluateTransform ){ + construct(); } -} -EntityKeyValues& getEntity(){ - return m_entity; -} -const EntityKeyValues& getEntity() const { - return m_entity; -} - -scene::Traversable& getTraversable(){ - return m_model.getTraversable(); -} -Namespaced& getNamespaced(){ - return m_nameKeys; -} -Nameable& getNameable(){ - return m_named; -} -TransformNode& getTransformNode(){ - return m_transform; -} -ModelSkin& getModelSkin(){ - return m_remapKeysObserver; -} - -void attach( scene::Traversable::Observer* observer ){ - m_model.attach( observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_model.detach( observer ); -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - if ( selected ) { - m_renderOrigin.render( renderer, volume, localToWorld ); + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_filter.instanceAttach(); + m_entity.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + m_entity.attach( m_keyObservers ); + m_entity.attach( m_remapKeysObserver ); + } } - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - if ( m_renderName.excluded_not() - && ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( AABB( Vector3( 0, 0, 0 ), Vector3( 32, 32, 32 ) ), volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { - m_renderName.render( renderer, volume, localToWorld, selected ); + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_entity.detach( m_remapKeysObserver ); + m_entity.detach( m_keyObservers ); + m_entity.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + m_filter.instanceDetach(); + } } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { - renderSolid( renderer, volume, localToWorld, selected ); -} -void translate( const Vector3& translation ){ - m_origin = origin_translated( m_origin, translation ); -} -void rotate( const Quaternion& rotation ){ - //m_angles = angles_rotated_for_rotated_pivot( m_angles, rotation ); - m_angles = angles_rotated( m_angles, rotation ); -} -void scale( const Vector3& scaling ){ - //m_scale = scale_scaled( m_scale, scaling ); - - Matrix4 mat( matrix4_scale_for_vec3( scaling ) ); - matrix4_multiply_by_matrix4( mat, matrix4_rotation_for_euler_xyz_degrees( m_anglesKey.m_angles ) ); - matrix4_scale_by_vec3( mat, m_scale ); - - m_scale = matrix4_get_scale_vec3( mat ); - //m_angles = angles_snapped_to_zero( matrix4_get_rotation_euler_xyz_degrees( mat ) ); -} -void snapto( float snap ){ - m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); - m_originKey.write( &m_entity ); -} -void revertTransform(){ - m_origin = m_originKey.m_origin; - m_angles = m_anglesKey.m_angles; - m_scale = m_scaleKey.m_scale; -} -void freezeTransform(){ - m_originKey.m_origin = m_origin; - m_originKey.write( &m_entity ); - if( m_anglesKey.m_angles != m_angles ){ - m_anglesKey.m_angles = m_angles; - m_anglesKey.write( &m_entity ); + EntityKeyValues& getEntity(){ + return m_entity; } - m_scaleKey.m_scale = m_scale; - m_scaleKey.write( &m_entity ); -} -void transformChanged(){ - revertTransform(); - m_evaluateTransform(); - updateTransform(); -} -typedef MemberCaller TransformChangedCaller; + const EntityKeyValues& getEntity() const { + return m_entity; + } + + scene::Traversable& getTraversable(){ + return m_model.getTraversable(); + } + Namespaced& getNamespaced(){ + return m_nameKeys; + } + Nameable& getNameable(){ + return m_named; + } + TransformNode& getTransformNode(){ + return m_transform; + } + ModelSkin& getModelSkin(){ + return m_remapKeysObserver; + } + + void attach( scene::Traversable::Observer* observer ){ + m_model.attach( observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_model.detach( observer ); + } + + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + if ( selected ) { + m_renderOrigin.render( renderer, volume, localToWorld ); + } + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + if ( m_renderName.excluded_not() + && ( selected || ( g_showNames && ( volume.fill() || aabb_fits_view( AABB( Vector3( 0, 0, 0 ), Vector3( 32, 32, 32 ) ), volume.GetModelview(), volume.GetViewport(), g_showNamesRatio ) ) ) ) ) { + m_renderName.render( renderer, volume, localToWorld, selected ); + } + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, bool selected ) const { + renderSolid( renderer, volume, localToWorld, selected ); + } + + void translate( const Vector3& translation ){ + m_origin = origin_translated( m_origin, translation ); + } + void rotate( const Quaternion& rotation ){ + //m_angles = angles_rotated_for_rotated_pivot( m_angles, rotation ); + m_angles = angles_rotated( m_angles, rotation ); + } + void scale( const Vector3& scaling ){ + //m_scale = scale_scaled( m_scale, scaling ); + + Matrix4 mat( matrix4_scale_for_vec3( scaling ) ); + matrix4_multiply_by_matrix4( mat, matrix4_rotation_for_euler_xyz_degrees( m_anglesKey.m_angles ) ); + matrix4_scale_by_vec3( mat, m_scale ); + + m_scale = matrix4_get_scale_vec3( mat ); + //m_angles = angles_snapped_to_zero( matrix4_get_rotation_euler_xyz_degrees( mat ) ); + } + void snapto( float snap ){ + m_originKey.m_origin = origin_snapped( m_originKey.m_origin, snap ); + m_originKey.write( &m_entity ); + } + void revertTransform(){ + m_origin = m_originKey.m_origin; + m_angles = m_anglesKey.m_angles; + m_scale = m_scaleKey.m_scale; + } + void freezeTransform(){ + m_originKey.m_origin = m_origin; + m_originKey.write( &m_entity ); + if( m_anglesKey.m_angles != m_angles ){ + m_anglesKey.m_angles = m_angles; + m_anglesKey.write( &m_entity ); + } + m_scaleKey.m_scale = m_scale; + m_scaleKey.write( &m_entity ); + } + void transformChanged(){ + revertTransform(); + m_evaluateTransform(); + updateTransform(); + } + typedef MemberCaller TransformChangedCaller; }; class MiscModelInstance : public TargetableInstance, public TransformModifier, public Renderable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - m_casts = TargetableInstance::StaticTypeCasts::instance().get(); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - -MiscModel& m_contained; -public: -typedef LazyStatic StaticTypeCasts; - -STRING_CONSTANT( Name, "MiscModelInstance" ); - -MiscModelInstance( const scene::Path& path, scene::Instance* parent, MiscModel& miscmodel ) : - TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), miscmodel.getEntity(), *this ), - TransformModifier( MiscModel::TransformChangedCaller( miscmodel ), ApplyTransformCaller( *this ) ), - m_contained( miscmodel ){ - m_contained.instanceAttach( Instance::path() ); - StaticRenderableConnectionLines::instance().attach( *this ); -} -~MiscModelInstance(){ - StaticRenderableConnectionLines::instance().detach( *this ); - m_contained.instanceDetach( Instance::path() ); -} -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); -} -void evaluateTransform(){ - if ( getType() == TRANSFORM_PRIMITIVE ) { - m_contained.translate( getTranslation() ); - if( getRotation() != c_quaternion_identity ){ - m_contained.rotate( getRotation() ); + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + m_casts = TargetableInstance::StaticTypeCasts::instance().get(); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); } - if( getScale() != c_scale_identity ){ - m_contained.scale( getScale() ); + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + + MiscModel& m_contained; +public: + typedef LazyStatic StaticTypeCasts; + + STRING_CONSTANT( Name, "MiscModelInstance" ); + + MiscModelInstance( const scene::Path& path, scene::Instance* parent, MiscModel& miscmodel ) : + TargetableInstance( path, parent, this, StaticTypeCasts::instance().get(), miscmodel.getEntity(), *this ), + TransformModifier( MiscModel::TransformChangedCaller( miscmodel ), ApplyTransformCaller( *this ) ), + m_contained( miscmodel ){ + m_contained.instanceAttach( Instance::path() ); + StaticRenderableConnectionLines::instance().attach( *this ); + } + ~MiscModelInstance(){ + StaticRenderableConnectionLines::instance().detach( *this ); + m_contained.instanceDetach( Instance::path() ); + } + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderSolid( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_contained.renderWireframe( renderer, volume, Instance::localToWorld(), getSelectable().isSelected() ); + } + void evaluateTransform(){ + if ( getType() == TRANSFORM_PRIMITIVE ) { + m_contained.translate( getTranslation() ); + if( getRotation() != c_quaternion_identity ){ + m_contained.rotate( getRotation() ); + } + if( getScale() != c_scale_identity ){ + m_contained.scale( getScale() ); + } } } -} -void applyTransform(){ - m_contained.revertTransform(); - evaluateTransform(); - m_contained.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; + void applyTransform(){ + m_contained.revertTransform(); + evaluateTransform(); + m_contained.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; }; class MiscModelNode : @@ -411,111 +411,111 @@ class MiscModelNode : public scene::Cloneable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -MiscModel m_contained; + scene::Node m_node; + InstanceSet m_instances; + MiscModel m_contained; -void construct(){ - m_contained.attach( this ); -} -void destroy(){ - m_contained.detach( this ); -} + void construct(){ + m_contained.attach( this ); + } + void destroy(){ + m_contained.detach( this ); + } public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_contained.getTraversable(); -} -Snappable& get( NullType){ - return m_contained; -} -TransformNode& get( NullType){ - return m_contained.getTransformNode(); -} -Entity& get( NullType){ - return m_contained.getEntity(); -} -Nameable& get( NullType){ - return m_contained.getNameable(); -} -Namespaced& get( NullType){ - return m_contained.getNamespaced(); -} -ModelSkin& get( NullType){ - return m_contained.getModelSkin(); -} + scene::Traversable& get( NullType){ + return m_contained.getTraversable(); + } + Snappable& get( NullType){ + return m_contained; + } + TransformNode& get( NullType){ + return m_contained.getTransformNode(); + } + Entity& get( NullType){ + return m_contained.getEntity(); + } + Nameable& get( NullType){ + return m_contained.getNameable(); + } + Namespaced& get( NullType){ + return m_contained.getNamespaced(); + } + ModelSkin& get( NullType){ + return m_contained.getModelSkin(); + } -MiscModelNode( EntityClass* eclass ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -MiscModelNode( const MiscModelNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ - construct(); -} -~MiscModelNode(){ - destroy(); -} + MiscModelNode( EntityClass* eclass ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( eclass, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + MiscModelNode( const MiscModelNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_contained( other.m_contained, m_node, InstanceSet::TransformChangedCaller( m_instances ), InstanceSetEvaluateTransform::Caller( m_instances ) ){ + construct(); + } + ~MiscModelNode(){ + destroy(); + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Node& clone() const { - return ( new MiscModelNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new MiscModelNode( *this ) )->node(); + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new MiscModelInstance( path, parent, m_contained ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new MiscModelInstance( path, parent, m_contained ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; scene::Node& New_MiscModel( EntityClass* eclass ){ diff --git a/plugins/entity/model.h b/plugins/entity/model.h index a7b395ff..75a8cab4 100644 --- a/plugins/entity/model.h +++ b/plugins/entity/model.h @@ -31,79 +31,79 @@ class EModel : public ModuleObserver { -ResourceReference m_resource; -scene::Traversable& m_traverse; -scene::Node* m_node; -Callback m_modelChanged; + ResourceReference m_resource; + scene::Traversable& m_traverse; + scene::Node* m_node; + Callback m_modelChanged; public: -EModel( scene::Traversable& traversable, const Callback& modelChanged ) - : m_resource( "" ), m_traverse( traversable ), m_node( 0 ), m_modelChanged( modelChanged ){ - m_resource.attach( *this ); -} -~EModel(){ - m_resource.detach( *this ); -} - -void realise(){ - m_resource.get()->load(); - m_node = m_resource.get()->getNode(); - if ( m_node != 0 ) { - m_traverse.insert( *m_node ); + EModel( scene::Traversable& traversable, const Callback& modelChanged ) + : m_resource( "" ), m_traverse( traversable ), m_node( 0 ), m_modelChanged( modelChanged ){ + m_resource.attach( *this ); } -} -void unrealise(){ - if ( m_node != 0 ) { - m_traverse.erase( *m_node ); + ~EModel(){ + m_resource.detach( *this ); } -} -void modelChanged( const char* value ){ - StringOutputStream cleaned( string_length( value ) ); - cleaned << PathCleaned( value ); - m_resource.detach( *this ); - m_resource.setName( cleaned.c_str() ); - m_resource.attach( *this ); - m_modelChanged(); -} -typedef MemberCaller1 ModelChangedCaller; + void realise(){ + m_resource.get()->load(); + m_node = m_resource.get()->getNode(); + if ( m_node != 0 ) { + m_traverse.insert( *m_node ); + } + } + void unrealise(){ + if ( m_node != 0 ) { + m_traverse.erase( *m_node ); + } + } -const char* getName() const { - return m_resource.getName(); -} -scene::Node* getNode() const { - return m_node; -} + void modelChanged( const char* value ){ + StringOutputStream cleaned( string_length( value ) ); + cleaned << PathCleaned( value ); + m_resource.detach( *this ); + m_resource.setName( cleaned.c_str() ); + m_resource.attach( *this ); + m_modelChanged(); + } + typedef MemberCaller1 ModelChangedCaller; + + const char* getName() const { + return m_resource.getName(); + } + scene::Node* getNode() const { + return m_node; + } }; class SingletonModel { -TraversableNode m_traverse; -EModel m_model; + TraversableNode m_traverse; + EModel m_model; public: -SingletonModel() - : m_model( m_traverse, Callback() ){ -} + SingletonModel() + : m_model( m_traverse, Callback() ){ + } -void attach( scene::Traversable::Observer* observer ){ - m_traverse.attach( observer ); -} -void detach( scene::Traversable::Observer* observer ){ - m_traverse.detach( observer ); -} + void attach( scene::Traversable::Observer* observer ){ + m_traverse.attach( observer ); + } + void detach( scene::Traversable::Observer* observer ){ + m_traverse.detach( observer ); + } -scene::Traversable& getTraversable(){ - return m_traverse; -} + scene::Traversable& getTraversable(){ + return m_traverse; + } -void modelChanged( const char* value ){ - m_model.modelChanged( value ); -} -typedef MemberCaller1 ModelChangedCaller; + void modelChanged( const char* value ){ + m_model.modelChanged( value ); + } + typedef MemberCaller1 ModelChangedCaller; -scene::Node* getNode() const { - return m_model.getNode(); -} + scene::Node* getNode() const { + return m_model.getNode(); + } }; #endif diff --git a/plugins/entity/modelskinkey.h b/plugins/entity/modelskinkey.h index e03402a1..60fd8d5d 100644 --- a/plugins/entity/modelskinkey.h +++ b/plugins/entity/modelskinkey.h @@ -36,56 +36,56 @@ inline void parseTextureName( CopiedString& name, const char* token ){ class ModelSkinKey : public ModuleObserver { -CopiedString m_name; -ModelSkin* m_skin; -Callback m_skinChangedCallback; + CopiedString m_name; + ModelSkin* m_skin; + Callback m_skinChangedCallback; -ModelSkinKey( const ModelSkinKey& ); -ModelSkinKey operator=( const ModelSkinKey& ); + ModelSkinKey( const ModelSkinKey& ); + ModelSkinKey operator=( const ModelSkinKey& ); -void construct(){ - m_skin = &GlobalModelSkinCache().capture( m_name.c_str() ); - m_skin->attach( *this ); -} -void destroy(){ - m_skin->detach( *this ); - GlobalModelSkinCache().release( m_name.c_str() ); -} + void construct(){ + m_skin = &GlobalModelSkinCache().capture( m_name.c_str() ); + m_skin->attach( *this ); + } + void destroy(){ + m_skin->detach( *this ); + GlobalModelSkinCache().release( m_name.c_str() ); + } public: -ModelSkinKey( const Callback& skinChangedCallback ) : m_skinChangedCallback( skinChangedCallback ){ - construct(); -} -~ModelSkinKey(){ - destroy(); -} -ModelSkin& get() const { - return *m_skin; -} -void skinChanged( const char* value ){ - destroy(); - parseTextureName( m_name, value ); - construct(); -} -typedef MemberCaller1 SkinChangedCaller; + ModelSkinKey( const Callback& skinChangedCallback ) : m_skinChangedCallback( skinChangedCallback ){ + construct(); + } + ~ModelSkinKey(){ + destroy(); + } + ModelSkin& get() const { + return *m_skin; + } + void skinChanged( const char* value ){ + destroy(); + parseTextureName( m_name, value ); + construct(); + } + typedef MemberCaller1 SkinChangedCaller; -void realise(){ - m_skinChangedCallback(); -} -void unrealise(){ -} + void realise(){ + m_skinChangedCallback(); + } + void unrealise(){ + } }; class InstanceSkinChanged : public scene::Instantiable::Visitor { public: -void visit( scene::Instance& instance ) const { - //\todo don't do this for instances that are not children of the entity setting the skin - SkinnedModel* skinned = InstanceTypeCast::cast( instance ); - if ( skinned != 0 ) { - skinned->skinChanged(); + void visit( scene::Instance& instance ) const { + //\todo don't do this for instances that are not children of the entity setting the skin + SkinnedModel* skinned = InstanceTypeCast::cast( instance ); + if ( skinned != 0 ) { + skinned->skinChanged(); + } } -} }; inline void Node_modelSkinChanged( scene::Node& node ){ diff --git a/plugins/entity/namedentity.h b/plugins/entity/namedentity.h index 18704f84..e10939e2 100644 --- a/plugins/entity/namedentity.h +++ b/plugins/entity/namedentity.h @@ -32,61 +32,61 @@ class NameCallbackSet { -typedef std::set NameCallbacks; -NameCallbacks m_callbacks; + typedef std::set NameCallbacks; + NameCallbacks m_callbacks; public: -void insert( const NameCallback& callback ){ - m_callbacks.insert( callback ); -} -void erase( const NameCallback& callback ){ - m_callbacks.erase( callback ); -} -void changed( const char* name ) const { - for ( NameCallbacks::const_iterator i = m_callbacks.begin(); i != m_callbacks.end(); ++i ) - { - ( *i )( name ); + void insert( const NameCallback& callback ){ + m_callbacks.insert( callback ); + } + void erase( const NameCallback& callback ){ + m_callbacks.erase( callback ); + } + void changed( const char* name ) const { + for ( NameCallbacks::const_iterator i = m_callbacks.begin(); i != m_callbacks.end(); ++i ) + { + ( *i )( name ); + } } -} }; class NamedEntity : public Nameable { -EntityKeyValues& m_entity; -NameCallbackSet m_changed; -CopiedString m_name; + EntityKeyValues& m_entity; + NameCallbackSet m_changed; + CopiedString m_name; public: -NamedEntity( EntityKeyValues& entity ) : m_entity( entity ){ -} -const char* name() const { - if ( string_empty( m_name.c_str() ) ) { + NamedEntity( EntityKeyValues& entity ) : m_entity( entity ){ + } + const char* name() const { + if ( string_empty( m_name.c_str() ) ) { + return m_entity.getEntityClass().name(); + } + return m_name.c_str(); + } + const char* classname() const { return m_entity.getEntityClass().name(); } - return m_name.c_str(); -} -const char* classname() const { - return m_entity.getEntityClass().name(); -} -const Colour3& color() const { - return m_entity.getEntityClass().color; -} -void attach( const NameCallback& callback ){ - m_changed.insert( callback ); -} -void detach( const NameCallback& callback ){ - m_changed.erase( callback ); -} + const Colour3& color() const { + return m_entity.getEntityClass().color; + } + void attach( const NameCallback& callback ){ + m_changed.insert( callback ); + } + void detach( const NameCallback& callback ){ + m_changed.erase( callback ); + } -void identifierChanged( const char* value ){ - if ( string_empty( value ) ) { - m_changed.changed( m_entity.getEntityClass().name() ); + void identifierChanged( const char* value ){ + if ( string_empty( value ) ) { + m_changed.changed( m_entity.getEntityClass().name() ); + } + else + { + m_changed.changed( value ); + } + m_name = value; } - else - { - m_changed.changed( value ); - } - m_name = value; -} -typedef MemberCaller1 IdentifierChangedCaller; + typedef MemberCaller1 IdentifierChangedCaller; }; @@ -96,7 +96,7 @@ typedef MemberCaller1 class RenderableNamedEntity { - enum ENameMode{ + enum ENameMode { eNameNormal = 0, eNameSelected = 1, eNameChildSelected = 2, diff --git a/plugins/entity/namekeys.h b/plugins/entity/namekeys.h index 0e2d88b3..b5e3dc38 100644 --- a/plugins/entity/namekeys.h +++ b/plugins/entity/namekeys.h @@ -38,11 +38,11 @@ typedef bool ( *KeyIsNameFunc )( const char* key ); class KeyIsName { public: -KeyIsNameFunc m_keyIsName; -const char* m_nameKey; + KeyIsNameFunc m_keyIsName; + const char* m_nameKey; -KeyIsName(){ -} + KeyIsName(){ + } }; @@ -52,82 +52,82 @@ typedef MemberCaller1 KeyValues; -KeyValues m_keyValues; + typedef std::map KeyValues; + KeyValues m_keyValues; -void insertName( const char* key, EntityKeyValue& value ){ - if ( m_namespace != 0 && m_keyIsName( key ) ) { - //globalOutputStream() << "insert " << key << "\n"; - m_namespace->attach( KeyValueAssignCaller( value ), KeyValueAttachCaller( value ) ); + void insertName( const char* key, EntityKeyValue& value ){ + if ( m_namespace != 0 && m_keyIsName( key ) ) { + //globalOutputStream() << "insert " << key << "\n"; + m_namespace->attach( KeyValueAssignCaller( value ), KeyValueAttachCaller( value ) ); + } } -} -void eraseName( const char* key, EntityKeyValue& value ){ - if ( m_namespace != 0 && m_keyIsName( key ) ) { - //globalOutputStream() << "erase " << key << "\n"; - m_namespace->detach( KeyValueAssignCaller( value ), KeyValueDetachCaller( value ) ); + void eraseName( const char* key, EntityKeyValue& value ){ + if ( m_namespace != 0 && m_keyIsName( key ) ) { + //globalOutputStream() << "erase " << key << "\n"; + m_namespace->detach( KeyValueAssignCaller( value ), KeyValueDetachCaller( value ) ); + } } -} -void insertAll(){ - for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - insertName( ( *i ).first.c_str(), *( *i ).second ); + void insertAll(){ + for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + insertName( ( *i ).first.c_str(), *( *i ).second ); + } } -} -void eraseAll(){ - for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - eraseName( ( *i ).first.c_str(), *( *i ).second ); + void eraseAll(){ + for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + eraseName( ( *i ).first.c_str(), *( *i ).second ); + } } -} public: -NameKeys( EntityKeyValues& entity ) : m_namespace( 0 ), m_entity( entity ), m_keyIsName( Static::instance().m_keyIsName ){ - m_entity.attach( *this ); -} -~NameKeys(){ - m_entity.detach( *this ); -} -void setNamespace( Namespace& space ){ - eraseAll(); - m_namespace = &space; - insertAll(); -} -void setKeyIsName( KeyIsNameFunc keyIsName ){ - eraseAll(); - m_keyIsName = keyIsName; - insertAll(); -} -void insert( const char* key, EntityKeyValue& value ){ - m_keyValues.insert( KeyValues::value_type( key, &value ) ); - insertName( key, value ); -} -void erase( const char* key, EntityKeyValue& value ){ - eraseName( key, value ); - m_keyValues.erase( key ); -} + NameKeys( EntityKeyValues& entity ) : m_namespace( 0 ), m_entity( entity ), m_keyIsName( Static::instance().m_keyIsName ){ + m_entity.attach( *this ); + } + ~NameKeys(){ + m_entity.detach( *this ); + } + void setNamespace( Namespace& space ){ + eraseAll(); + m_namespace = &space; + insertAll(); + } + void setKeyIsName( KeyIsNameFunc keyIsName ){ + eraseAll(); + m_keyIsName = keyIsName; + insertAll(); + } + void insert( const char* key, EntityKeyValue& value ){ + m_keyValues.insert( KeyValues::value_type( key, &value ) ); + insertName( key, value ); + } + void erase( const char* key, EntityKeyValue& value ){ + eraseName( key, value ); + m_keyValues.erase( key ); + } }; inline bool keyIsNameDoom3( const char* key ){ return string_equal( key, "target" ) - || ( string_equal_n( key, "target", 6 ) && string_is_integer( key + 6 ) ) - || string_equal( key, "name" ); + || ( string_equal_n( key, "target", 6 ) && string_is_integer( key + 6 ) ) + || string_equal( key, "name" ); } inline bool keyIsNameDoom3Doom3Group( const char* key ){ return keyIsNameDoom3( key ) - || string_equal( key, "model" ); + || string_equal( key, "model" ); } inline bool keyIsNameQuake3( const char* key ){ return string_equal( key, "target" ) - || string_equal( key, "targetname" ) - || string_equal( key, "killtarget" ) - || ( string_equal_n( key, "target", 6 ) && string_is_integer( key + 6 ) ); // Nexuiz + || string_equal( key, "targetname" ) + || string_equal( key, "killtarget" ) + || ( string_equal_n( key, "target", 6 ) && string_is_integer( key + 6 ) ); // Nexuiz } #endif diff --git a/plugins/entity/origin.h b/plugins/entity/origin.h index 18efbf15..4996626e 100644 --- a/plugins/entity/origin.h +++ b/plugins/entity/origin.h @@ -46,14 +46,14 @@ inline void write_origin( const Vector3& origin, Entity* entity, const char* key inline Vector3 origin_translated( const Vector3& origin, const Vector3& translation ){ return vector3_snapped( - matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translation_for_vec3( origin ), - matrix4_translation_for_vec3( translation ) - ) - ), - 1e-4 - ); + matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translation_for_vec3( origin ), + matrix4_translation_for_vec3( translation ) + ) + ), + 1e-4 + ); } inline Vector3 origin_snapped( const Vector3& origin, float snap ){ @@ -62,25 +62,25 @@ inline Vector3 origin_snapped( const Vector3& origin, float snap ){ class OriginKey { -Callback m_originChanged; + Callback m_originChanged; public: -Vector3 m_origin; + Vector3 m_origin; -OriginKey( const Callback& originChanged ) - : m_originChanged( originChanged ), m_origin( ORIGINKEY_IDENTITY ){ -} + OriginKey( const Callback& originChanged ) + : m_originChanged( originChanged ), m_origin( ORIGINKEY_IDENTITY ){ + } -void originChanged( const char* value ){ - read_origin( m_origin, value ); - m_originChanged(); -} -typedef MemberCaller1 OriginChangedCaller; + void originChanged( const char* value ){ + read_origin( m_origin, value ); + m_originChanged(); + } + typedef MemberCaller1 OriginChangedCaller; -void write( Entity* entity ) const { - write_origin( m_origin, entity, "origin" ); -} + void write( Entity* entity ) const { + write_origin( m_origin, entity, "origin" ); + } }; @@ -99,50 +99,50 @@ inline void BrushDoom3_setDoom3GroupOrigin( scene::Node& node, const Vector3& or class SetDoom3GroupOriginWalker : public scene::Traversable::Walker { -const Vector3& m_origin; + const Vector3& m_origin; public: -SetDoom3GroupOriginWalker( const Vector3& origin ) : m_origin( origin ){ -} -bool pre( scene::Node& node ) const { - BrushDoom3_setDoom3GroupOrigin( node, m_origin ); - return true; -} + SetDoom3GroupOriginWalker( const Vector3& origin ) : m_origin( origin ){ + } + bool pre( scene::Node& node ) const { + BrushDoom3_setDoom3GroupOrigin( node, m_origin ); + return true; + } }; class Doom3GroupOrigin : public scene::Traversable::Observer { -scene::Traversable& m_set; -const Vector3& m_origin; -bool m_enabled; + scene::Traversable& m_set; + const Vector3& m_origin; + bool m_enabled; public: -Doom3GroupOrigin( scene::Traversable& set, const Vector3& origin ) : m_set( set ), m_origin( origin ), m_enabled( false ){ -} - -void enable(){ - m_enabled = true; - originChanged(); -} -void disable(){ - m_enabled = false; -} - -void originChanged(){ - if ( m_enabled ) { - m_set.traverse( SetDoom3GroupOriginWalker( m_origin ) ); + Doom3GroupOrigin( scene::Traversable& set, const Vector3& origin ) : m_set( set ), m_origin( origin ), m_enabled( false ){ } -} -void insert( scene::Node& node ){ - if ( m_enabled ) { - BrushDoom3_setDoom3GroupOrigin( node, m_origin ); + void enable(){ + m_enabled = true; + originChanged(); } -} -void erase( scene::Node& node ){ - if ( m_enabled ) { - BrushDoom3_setDoom3GroupOrigin( node, Vector3( 0, 0, 0 ) ); + void disable(){ + m_enabled = false; + } + + void originChanged(){ + if ( m_enabled ) { + m_set.traverse( SetDoom3GroupOriginWalker( m_origin ) ); + } + } + + void insert( scene::Node& node ){ + if ( m_enabled ) { + BrushDoom3_setDoom3GroupOrigin( node, m_origin ); + } + } + void erase( scene::Node& node ){ + if ( m_enabled ) { + BrushDoom3_setDoom3GroupOrigin( node, Vector3( 0, 0, 0 ) ); + } } -} }; diff --git a/plugins/entity/plugin.cpp b/plugins/entity/plugin.cpp index 37156093..5dc74116 100644 --- a/plugins/entity/plugin.cpp +++ b/plugins/entity/plugin.cpp @@ -61,24 +61,24 @@ class EntityDependencies : class EntityQ3API : public TypeSystemRef { -EntityCreator* m_entityq3; + EntityCreator* m_entityq3; public: -typedef EntityCreator Type; -STRING_CONSTANT( Name, "quake3" ); + typedef EntityCreator Type; + STRING_CONSTANT( Name, "quake3" ); -EntityQ3API(){ - Entity_Construct(); + EntityQ3API(){ + Entity_Construct(); - m_entityq3 = &GetEntityCreator(); + m_entityq3 = &GetEntityCreator(); - GlobalReferenceCache().setEntityCreator( *m_entityq3 ); -} -~EntityQ3API(){ - Entity_Destroy(); -} -EntityCreator* getTable(){ - return m_entityq3; -} + GlobalReferenceCache().setEntityCreator( *m_entityq3 ); + } + ~EntityQ3API(){ + Entity_Destroy(); + } + EntityCreator* getTable(){ + return m_entityq3; + } }; typedef SingletonModule EntityQ3Module; @@ -88,24 +88,24 @@ EntityQ3Module g_EntityQ3Module; class EntityQ1API : public TypeSystemRef { -EntityCreator* m_entityq1; + EntityCreator* m_entityq1; public: -typedef EntityCreator Type; -STRING_CONSTANT( Name, "quake" ); + typedef EntityCreator Type; + STRING_CONSTANT( Name, "quake" ); -EntityQ1API(){ - Entity_Construct( eGameTypeQuake1 ); + EntityQ1API(){ + Entity_Construct( eGameTypeQuake1 ); - m_entityq1 = &GetEntityCreator(); + m_entityq1 = &GetEntityCreator(); - GlobalReferenceCache().setEntityCreator( *m_entityq1 ); -} -~EntityQ1API(){ - Entity_Destroy(); -} -EntityCreator* getTable(){ - return m_entityq1; -} + GlobalReferenceCache().setEntityCreator( *m_entityq1 ); + } + ~EntityQ1API(){ + Entity_Destroy(); + } + EntityCreator* getTable(){ + return m_entityq1; + } }; typedef SingletonModule EntityQ1Module; @@ -115,24 +115,24 @@ EntityQ1Module g_EntityQ1Module; class EntityWolfAPI : public TypeSystemRef { -EntityCreator* m_entitywolf; + EntityCreator* m_entitywolf; public: -typedef EntityCreator Type; -STRING_CONSTANT( Name, "wolf" ); + typedef EntityCreator Type; + STRING_CONSTANT( Name, "wolf" ); -EntityWolfAPI(){ - Entity_Construct( eGameTypeRTCW ); + EntityWolfAPI(){ + Entity_Construct( eGameTypeRTCW ); - m_entitywolf = &GetEntityCreator(); + m_entitywolf = &GetEntityCreator(); - GlobalReferenceCache().setEntityCreator( *m_entitywolf ); -} -~EntityWolfAPI(){ - Entity_Destroy(); -} -EntityCreator* getTable(){ - return m_entitywolf; -} + GlobalReferenceCache().setEntityCreator( *m_entitywolf ); + } + ~EntityWolfAPI(){ + Entity_Destroy(); + } + EntityCreator* getTable(){ + return m_entitywolf; + } }; typedef SingletonModule EntityWolfModule; @@ -142,24 +142,24 @@ EntityWolfModule g_EntityWolfModule; class EntityDoom3API : public TypeSystemRef { -EntityCreator* m_entitydoom3; + EntityCreator* m_entitydoom3; public: -typedef EntityCreator Type; -STRING_CONSTANT( Name, "doom3" ); + typedef EntityCreator Type; + STRING_CONSTANT( Name, "doom3" ); -EntityDoom3API(){ - Entity_Construct( eGameTypeDoom3 ); + EntityDoom3API(){ + Entity_Construct( eGameTypeDoom3 ); - m_entitydoom3 = &GetEntityCreator(); + m_entitydoom3 = &GetEntityCreator(); - GlobalReferenceCache().setEntityCreator( *m_entitydoom3 ); -} -~EntityDoom3API(){ - Entity_Destroy(); -} -EntityCreator* getTable(){ - return m_entitydoom3; -} + GlobalReferenceCache().setEntityCreator( *m_entitydoom3 ); + } + ~EntityDoom3API(){ + Entity_Destroy(); + } + EntityCreator* getTable(){ + return m_entitydoom3; + } }; typedef SingletonModule EntityDoom3Module; diff --git a/plugins/entity/rotation.h b/plugins/entity/rotation.h index fc2c9fbe..275263f4 100644 --- a/plugins/entity/rotation.h +++ b/plugins/entity/rotation.h @@ -46,28 +46,28 @@ inline void default_rotation( Float9 rotation ){ } inline void write_rotation( const Float9 rotation, Entity* entity, const char* key = "rotation" ){ if ( rotation[0] == 1 - && rotation[1] == 0 - && rotation[2] == 0 - && rotation[3] == 0 - && rotation[4] == 1 - && rotation[5] == 0 - && rotation[6] == 0 - && rotation[7] == 0 - && rotation[8] == 1 ) { + && rotation[1] == 0 + && rotation[2] == 0 + && rotation[3] == 0 + && rotation[4] == 1 + && rotation[5] == 0 + && rotation[6] == 0 + && rotation[7] == 0 + && rotation[8] == 1 ) { entity->setKeyValue( key, "" ); } else { StringOutputStream value( 256 ); value << rotation[0] << ' ' - << rotation[1] << ' ' - << rotation[2] << ' ' - << rotation[3] << ' ' - << rotation[4] << ' ' - << rotation[5] << ' ' - << rotation[6] << ' ' - << rotation[7] << ' ' - << rotation[8]; + << rotation[1] << ' ' + << rotation[2] << ' ' + << rotation[3] << ' ' + << rotation[4] << ' ' + << rotation[5] << ' ' + << rotation[6] << ' ' + << rotation[7] << ' ' + << rotation[8]; entity->setKeyValue( key, value.c_str() ); } } @@ -79,23 +79,23 @@ inline void read_rotation( Float9 rotation, const char* value ){ inline Matrix4 rotation_toMatrix( const Float9 rotation ){ return Matrix4( - rotation[0], - rotation[1], - rotation[2], - 0, - rotation[3], - rotation[4], - rotation[5], - 0, - rotation[6], - rotation[7], - rotation[8], - 0, - 0, - 0, - 0, - 1 - ); + rotation[0], + rotation[1], + rotation[2], + 0, + rotation[3], + rotation[4], + rotation[5], + 0, + rotation[6], + rotation[7], + rotation[8], + 0, + 0, + 0, + 0, + 1 + ); } inline void rotation_fromMatrix( Float9 rotation, const Matrix4& matrix ){ @@ -124,11 +124,11 @@ inline void rotation_assign( Float9 rotation, const Float9 other ){ inline void rotation_rotate( Float9 rotation, const Quaternion& rotate ){ rotation_fromMatrix( rotation, - matrix4_multiplied_by_matrix4( - rotation_toMatrix( rotation ), - matrix4_rotation_for_quaternion_quantised( rotate ) - ) - ); + matrix4_multiplied_by_matrix4( + rotation_toMatrix( rotation ), + matrix4_rotation_for_quaternion_quantised( rotate ) + ) + ); } inline void read_angle( Float9 rotation, const char* value ){ @@ -144,40 +144,40 @@ inline void read_angle( Float9 rotation, const char* value ){ class RotationKey { -Callback m_rotationChanged; + Callback m_rotationChanged; public: -Float9 m_rotation; + Float9 m_rotation; -RotationKey( const Callback& rotationChanged ) - : m_rotationChanged( rotationChanged ){ - default_rotation( m_rotation ); -} - -void angleChanged( const char* value ){ - read_angle( m_rotation, value ); - m_rotationChanged(); -} -typedef MemberCaller1 AngleChangedCaller; - -void rotationChanged( const char* value ){ - read_rotation( m_rotation, value ); - m_rotationChanged(); -} -typedef MemberCaller1 RotationChangedCaller; - -void write( Entity* entity ) const { - Vector3 euler = matrix4_get_rotation_euler_xyz_degrees( rotation_toMatrix( m_rotation ) ); - if ( euler[0] == 0 && euler[1] == 0 ) { - entity->setKeyValue( "rotation", "" ); - write_angle( euler[2], entity ); + RotationKey( const Callback& rotationChanged ) + : m_rotationChanged( rotationChanged ){ + default_rotation( m_rotation ); } - else - { - entity->setKeyValue( "angle", "" ); - write_rotation( m_rotation, entity ); + + void angleChanged( const char* value ){ + read_angle( m_rotation, value ); + m_rotationChanged(); + } + typedef MemberCaller1 AngleChangedCaller; + + void rotationChanged( const char* value ){ + read_rotation( m_rotation, value ); + m_rotationChanged(); + } + typedef MemberCaller1 RotationChangedCaller; + + void write( Entity* entity ) const { + Vector3 euler = matrix4_get_rotation_euler_xyz_degrees( rotation_toMatrix( m_rotation ) ); + if ( euler[0] == 0 && euler[1] == 0 ) { + entity->setKeyValue( "rotation", "" ); + write_angle( euler[2], entity ); + } + else + { + entity->setKeyValue( "angle", "" ); + write_rotation( m_rotation, entity ); + } } -} }; #endif diff --git a/plugins/entity/scale.h b/plugins/entity/scale.h index c7221459..3e60bd39 100644 --- a/plugins/entity/scale.h +++ b/plugins/entity/scale.h @@ -36,7 +36,7 @@ inline void default_scale( Vector3& scale ){ inline void read_scale( Vector3& scalevec, const char* value ){ float scale; if ( !string_parse_float( value, scale ) - || scale == 0 ) { + || scale == 0 ) { default_scale( scalevec ); } else @@ -46,9 +46,9 @@ inline void read_scale( Vector3& scalevec, const char* value ){ } inline void read_scalevec( Vector3& scale, const char* value ){ if ( !string_parse_vector3( value, scale ) - || scale[0] == 0 - || scale[1] == 0 - || scale[2] == 0 ) { + || scale[0] == 0 + || scale[1] == 0 + || scale[2] == 0 ) { default_scale( scale ); } } @@ -77,39 +77,39 @@ inline void write_scale( const Vector3& scale, Entity* entity ){ inline Vector3 scale_scaled( const Vector3& scale, const Vector3& scaling ){ return matrix4_get_scale_vec3( - matrix4_multiplied_by_matrix4( - matrix4_scale_for_vec3( scale ), - matrix4_scale_for_vec3( scaling ) - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_scale_for_vec3( scale ), + matrix4_scale_for_vec3( scaling ) + ) + ); } class ScaleKey { -Callback m_scaleChanged; + Callback m_scaleChanged; public: -Vector3 m_scale; + Vector3 m_scale; -ScaleKey( const Callback& scaleChanged ) - : m_scaleChanged( scaleChanged ), m_scale( SCALEKEY_IDENTITY ){ -} + ScaleKey( const Callback& scaleChanged ) + : m_scaleChanged( scaleChanged ), m_scale( SCALEKEY_IDENTITY ){ + } -void uniformScaleChanged( const char* value ){ - read_scale( m_scale, value ); - m_scaleChanged(); -} -typedef MemberCaller1 UniformScaleChangedCaller; + void uniformScaleChanged( const char* value ){ + read_scale( m_scale, value ); + m_scaleChanged(); + } + typedef MemberCaller1 UniformScaleChangedCaller; -void scaleChanged( const char* value ){ - read_scalevec( m_scale, value ); - m_scaleChanged(); -} -typedef MemberCaller1 ScaleChangedCaller; + void scaleChanged( const char* value ){ + read_scalevec( m_scale, value ); + m_scaleChanged(); + } + typedef MemberCaller1 ScaleChangedCaller; -void write( Entity* entity ) const { - write_scale( m_scale, entity ); -} + void write( Entity* entity ) const { + write_scale( m_scale, entity ); + } }; diff --git a/plugins/entity/skincache.cpp b/plugins/entity/skincache.cpp index a608d1fa..0b55789c 100644 --- a/plugins/entity/skincache.cpp +++ b/plugins/entity/skincache.cpp @@ -43,133 +43,133 @@ void parseShaderName( CopiedString& name, const char* token ){ class Doom3ModelSkin { -typedef std::map Remaps; -Remaps m_remaps; + typedef std::map Remaps; + Remaps m_remaps; public: -bool parseTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "{" ) ); - tokeniser.nextLine(); - for (;; ) - { - const char* token = tokeniser.getToken(); - if ( token == 0 ) { - return false; - } - if ( string_equal( token, "}" ) ) { - tokeniser.nextLine(); - return true; - } - else if ( string_equal( token, "model" ) ) { - //const char* model = - tokeniser.getToken(); - } - else - { - CopiedString from, to; - parseShaderName( from, token ); - - tokeniser.nextLine(); // hack to handle badly formed skins - - parseShaderName( to, tokeniser.getToken() ); - - if ( !string_equal( from.c_str(), to.c_str() ) ) { - m_remaps.insert( Remaps::value_type( from, to ) ); - } - } + bool parseTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "{" ) ); tokeniser.nextLine(); + for (;; ) + { + const char* token = tokeniser.getToken(); + if ( token == 0 ) { + return false; + } + if ( string_equal( token, "}" ) ) { + tokeniser.nextLine(); + return true; + } + else if ( string_equal( token, "model" ) ) { + //const char* model = + tokeniser.getToken(); + } + else + { + CopiedString from, to; + parseShaderName( from, token ); + + tokeniser.nextLine(); // hack to handle badly formed skins + + parseShaderName( to, tokeniser.getToken() ); + + if ( !string_equal( from.c_str(), to.c_str() ) ) { + m_remaps.insert( Remaps::value_type( from, to ) ); + } + } + tokeniser.nextLine(); + } } -} -const char* getRemap( const char* name ) const { - Remaps::const_iterator i = m_remaps.find( name ); - if ( i != m_remaps.end() ) { - return ( *i ).second.c_str(); + const char* getRemap( const char* name ) const { + Remaps::const_iterator i = m_remaps.find( name ); + if ( i != m_remaps.end() ) { + return ( *i ).second.c_str(); + } + return ""; } - return ""; -} -void forEachRemap( const SkinRemapCallback& callback ) const { - for ( Remaps::const_iterator i = m_remaps.begin(); i != m_remaps.end(); ++i ) - { - callback( SkinRemap( ( *i ).first.c_str(), ( *i ).second.c_str() ) ); + void forEachRemap( const SkinRemapCallback& callback ) const { + for ( Remaps::const_iterator i = m_remaps.begin(); i != m_remaps.end(); ++i ) + { + callback( SkinRemap( ( *i ).first.c_str(), ( *i ).second.c_str() ) ); + } } -} }; class GlobalSkins { public: -typedef std::map SkinMap; -SkinMap m_skins; -Doom3ModelSkin g_nullSkin; + typedef std::map SkinMap; + SkinMap m_skins; + Doom3ModelSkin g_nullSkin; -Doom3ModelSkin& getSkin( const char* name ){ - SkinMap::iterator i = m_skins.find( name ); - if ( i != m_skins.end() ) { - return ( *i ).second; + Doom3ModelSkin& getSkin( const char* name ){ + SkinMap::iterator i = m_skins.find( name ); + if ( i != m_skins.end() ) { + return ( *i ).second; + } + + return g_nullSkin; } - return g_nullSkin; -} - -bool parseTokens( Tokeniser& tokeniser ){ - tokeniser.nextLine(); - for (;; ) - { - const char* token = tokeniser.getToken(); - if ( token == 0 ) { - // end of token stream - return true; - } - if ( !string_equal( token, "skin" ) ) { - Tokeniser_unexpectedError( tokeniser, token, "skin" ); - return false; - } - const char* other = tokeniser.getToken(); - if ( other == 0 ) { - Tokeniser_unexpectedError( tokeniser, token, "#string" ); - return false; - } - CopiedString name; - parseShaderName( name, other ); - Doom3ModelSkin& skin = m_skins[name]; - RETURN_FALSE_IF_FAIL( skin.parseTokens( tokeniser ) ); - } -} - -void parseFile( const char* name ){ - StringOutputStream relativeName( 64 ); - relativeName << "skins/" << name; - ArchiveTextFile* file = GlobalFileSystem().openTextFile( relativeName.c_str() ); - if ( file != 0 ) { - globalOutputStream() << "parsing skins from " << makeQuoted( name ) << "\n"; + bool parseTokens( Tokeniser& tokeniser ){ + tokeniser.nextLine(); + for (;; ) { - Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewSimpleTokeniser( file->getInputStream() ); - parseTokens( tokeniser ); - tokeniser.release(); + const char* token = tokeniser.getToken(); + if ( token == 0 ) { + // end of token stream + return true; + } + if ( !string_equal( token, "skin" ) ) { + Tokeniser_unexpectedError( tokeniser, token, "skin" ); + return false; + } + const char* other = tokeniser.getToken(); + if ( other == 0 ) { + Tokeniser_unexpectedError( tokeniser, token, "#string" ); + return false; + } + CopiedString name; + parseShaderName( name, other ); + Doom3ModelSkin& skin = m_skins[name]; + RETURN_FALSE_IF_FAIL( skin.parseTokens( tokeniser ) ); } - file->release(); } - else - { - globalErrorStream() << "failed to open " << makeQuoted( name ) << "\n"; + + void parseFile( const char* name ){ + StringOutputStream relativeName( 64 ); + relativeName << "skins/" << name; + ArchiveTextFile* file = GlobalFileSystem().openTextFile( relativeName.c_str() ); + if ( file != 0 ) { + globalOutputStream() << "parsing skins from " << makeQuoted( name ) << "\n"; + { + Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewSimpleTokeniser( file->getInputStream() ); + parseTokens( tokeniser ); + tokeniser.release(); + } + file->release(); + } + else + { + globalErrorStream() << "failed to open " << makeQuoted( name ) << "\n"; + } } -} -typedef MemberCaller1 ParseFileCaller; + typedef MemberCaller1 ParseFileCaller; -void construct(){ - GlobalFileSystem().forEachFile( "skins/", "skin", ParseFileCaller( *this ) ); -} + void construct(){ + GlobalFileSystem().forEachFile( "skins/", "skin", ParseFileCaller( *this ) ); + } -void destroy(){ - m_skins.clear(); -} + void destroy(){ + m_skins.clear(); + } -void realise(){ - construct(); -} -void unrealise(){ - destroy(); -} + void realise(){ + construct(); + } + void unrealise(){ + destroy(); + } }; GlobalSkins g_skins; @@ -177,114 +177,114 @@ GlobalSkins g_skins; class Doom3ModelSkinCacheElement final : public ModelSkin { -ModuleObservers m_observers; -Doom3ModelSkin* m_skin; + ModuleObservers m_observers; + Doom3ModelSkin* m_skin; public: -Doom3ModelSkinCacheElement() : m_skin( 0 ){ -} -void attach( ModuleObserver& observer ){ - m_observers.attach( observer ); - if ( realised() ) { - observer.realise(); + Doom3ModelSkinCacheElement() : m_skin( 0 ){ } -} -void detach( ModuleObserver& observer ){ - if ( realised() ) { - observer.unrealise(); + void attach( ModuleObserver& observer ){ + m_observers.attach( observer ); + if ( realised() ) { + observer.realise(); + } + } + void detach( ModuleObserver& observer ){ + if ( realised() ) { + observer.unrealise(); + } + m_observers.detach( observer ); + } + bool realised() const { + return m_skin != 0; + } + void realise( const char* name ){ + ASSERT_MESSAGE( !realised(), "Doom3ModelSkinCacheElement::realise: already realised" ); + m_skin = &g_skins.getSkin( name ); + m_observers.realise(); + } + void unrealise(){ + ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::unrealise: not realised" ); + m_observers.unrealise(); + m_skin = 0; + } + const char* getRemap( const char* name ) const { + ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::getRemap: not realised" ); + return m_skin->getRemap( name ); + } + void forEachRemap( const SkinRemapCallback& callback ) const { + ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::forEachRemap: not realised" ); + m_skin->forEachRemap( callback ); } - m_observers.detach( observer ); -} -bool realised() const { - return m_skin != 0; -} -void realise( const char* name ){ - ASSERT_MESSAGE( !realised(), "Doom3ModelSkinCacheElement::realise: already realised" ); - m_skin = &g_skins.getSkin( name ); - m_observers.realise(); -} -void unrealise(){ - ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::unrealise: not realised" ); - m_observers.unrealise(); - m_skin = 0; -} -const char* getRemap( const char* name ) const { - ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::getRemap: not realised" ); - return m_skin->getRemap( name ); -} -void forEachRemap( const SkinRemapCallback& callback ) const { - ASSERT_MESSAGE( realised(), "Doom3ModelSkinCacheElement::forEachRemap: not realised" ); - m_skin->forEachRemap( callback ); -} }; class Doom3ModelSkinCache final : public ModelSkinCache, public ModuleObserver { -class CreateDoom3ModelSkin -{ -Doom3ModelSkinCache& m_cache; -public: -explicit CreateDoom3ModelSkin( Doom3ModelSkinCache& cache ) - : m_cache( cache ){ -} -Doom3ModelSkinCacheElement* construct( const CopiedString& name ){ - Doom3ModelSkinCacheElement* skin = new Doom3ModelSkinCacheElement; - if ( m_cache.realised() ) { - skin->realise( name.c_str() ); - } - return skin; -} -void destroy( Doom3ModelSkinCacheElement* skin ){ - if ( m_cache.realised() ) { - skin->unrealise(); - } - delete skin; -} -}; + class CreateDoom3ModelSkin + { + Doom3ModelSkinCache& m_cache; + public: + explicit CreateDoom3ModelSkin( Doom3ModelSkinCache& cache ) + : m_cache( cache ){ + } + Doom3ModelSkinCacheElement* construct( const CopiedString& name ){ + Doom3ModelSkinCacheElement* skin = new Doom3ModelSkinCacheElement; + if ( m_cache.realised() ) { + skin->realise( name.c_str() ); + } + return skin; + } + void destroy( Doom3ModelSkinCacheElement* skin ){ + if ( m_cache.realised() ) { + skin->unrealise(); + } + delete skin; + } + }; -typedef HashedCache, CreateDoom3ModelSkin> Cache; -Cache m_cache; -bool m_realised; + typedef HashedCache, CreateDoom3ModelSkin> Cache; + Cache m_cache; + bool m_realised; public: -typedef ModelSkinCache Type; -STRING_CONSTANT( Name, "*" ); -ModelSkinCache* getTable(){ - return this; -} - -Doom3ModelSkinCache() : m_cache( CreateDoom3ModelSkin( *this ) ), m_realised( false ){ - GlobalFileSystem().attach( *this ); -} -~Doom3ModelSkinCache(){ - GlobalFileSystem().detach( *this ); -} - -ModelSkin& capture( const char* name ){ - return *m_cache.capture( name ); -} -void release( const char* name ){ - m_cache.release( name ); -} - -bool realised() const { - return m_realised; -} -void realise(){ - g_skins.realise(); - m_realised = true; - for ( Cache::iterator i = m_cache.begin(); i != m_cache.end(); ++i ) - { - ( *i ).value->realise( ( *i ).key.c_str() ); + typedef ModelSkinCache Type; + STRING_CONSTANT( Name, "*" ); + ModelSkinCache* getTable(){ + return this; } -} -void unrealise(){ - m_realised = false; - for ( Cache::iterator i = m_cache.begin(); i != m_cache.end(); ++i ) - { - ( *i ).value->unrealise(); + + Doom3ModelSkinCache() : m_cache( CreateDoom3ModelSkin( *this ) ), m_realised( false ){ + GlobalFileSystem().attach( *this ); + } + ~Doom3ModelSkinCache(){ + GlobalFileSystem().detach( *this ); + } + + ModelSkin& capture( const char* name ){ + return *m_cache.capture( name ); + } + void release( const char* name ){ + m_cache.release( name ); + } + + bool realised() const { + return m_realised; + } + void realise(){ + g_skins.realise(); + m_realised = true; + for ( Cache::iterator i = m_cache.begin(); i != m_cache.end(); ++i ) + { + ( *i ).value->realise( ( *i ).key.c_str() ); + } + } + void unrealise(){ + m_realised = false; + for ( Cache::iterator i = m_cache.begin(); i != m_cache.end(); ++i ) + { + ( *i ).value->unrealise(); + } + g_skins.unrealise(); } - g_skins.unrealise(); -} }; class Doom3ModelSkinCacheDependencies : public GlobalFileSystemModuleRef, public GlobalScripLibModuleRef diff --git a/plugins/entity/targetable.h b/plugins/entity/targetable.h index 52924e94..113abf51 100644 --- a/plugins/entity/targetable.h +++ b/plugins/entity/targetable.h @@ -39,7 +39,7 @@ class Targetable { public: -virtual const Vector3& world_position() const = 0; + virtual const Vector3& world_position() const = 0; }; typedef std::set targetables_t; @@ -51,107 +51,107 @@ targetables_t* getTargetables( const char* targetname ); class EntityConnectionLine : public OpenGLRenderable { public: -Vector3 start; -Vector3 end; + Vector3 start; + Vector3 end; -void render( RenderStateFlags state ) const { - float s1[2], s2[2]; - Vector3 dir( vector3_subtracted( end, start ) ); - double len = vector3_length( dir ); - vector3_scale( dir, 8.0 * ( 1.0 / len ) ); - s1[0] = dir[0] - dir[1]; - s1[1] = dir[0] + dir[1]; - s2[0] = dir[0] + dir[1]; - s2[1] = -dir[0] + dir[1]; + void render( RenderStateFlags state ) const { + float s1[2], s2[2]; + Vector3 dir( vector3_subtracted( end, start ) ); + double len = vector3_length( dir ); + vector3_scale( dir, 8.0 * ( 1.0 / len ) ); + s1[0] = dir[0] - dir[1]; + s1[1] = dir[0] + dir[1]; + s2[0] = dir[0] + dir[1]; + s2[1] = -dir[0] + dir[1]; - glBegin( GL_LINES ); + glBegin( GL_LINES ); - glVertex3fv( vector3_to_array( start ) ); - glVertex3fv( vector3_to_array( end ) ); + glVertex3fv( vector3_to_array( start ) ); + glVertex3fv( vector3_to_array( end ) ); - len *= 0.0625; // half / 8 + len *= 0.0625; // half / 8 - Vector3 arrow( start ); - for ( unsigned int i = 0, count = ( len < 32 ) ? 1 : static_cast( len * 0.0625 ); i < count; i++ ) - { - vector3_add( arrow, vector3_scaled( dir, ( len < 32 ) ? len : 32 ) ); - glVertex3fv( vector3_to_array( arrow ) ); - glVertex3f( arrow[0] + s1[0], arrow[1] + s1[1], arrow[2] + dir[2] ); - glVertex3fv( vector3_to_array( arrow ) ); - glVertex3f( arrow[0] + s2[0], arrow[1] + s2[1], arrow[2] + dir[2] ); + Vector3 arrow( start ); + for ( unsigned int i = 0, count = ( len < 32 ) ? 1 : static_cast( len * 0.0625 ); i < count; i++ ) + { + vector3_add( arrow, vector3_scaled( dir, ( len < 32 ) ? len : 32 ) ); + glVertex3fv( vector3_to_array( arrow ) ); + glVertex3f( arrow[0] + s1[0], arrow[1] + s1[1], arrow[2] + dir[2] ); + glVertex3fv( vector3_to_array( arrow ) ); + glVertex3f( arrow[0] + s2[0], arrow[1] + s2[1], arrow[2] + dir[2] ); + } + + glEnd(); } - - glEnd(); -} }; #endif class TargetedEntity { -Targetable& m_targetable; -targetables_t* m_targets; + Targetable& m_targetable; + targetables_t* m_targets; -void construct(){ - if ( m_targets != 0 ) { - m_targets->insert( &m_targetable ); + void construct(){ + if ( m_targets != 0 ) { + m_targets->insert( &m_targetable ); + } } -} -void destroy(){ - if ( m_targets != 0 ) { - m_targets->erase( &m_targetable ); + void destroy(){ + if ( m_targets != 0 ) { + m_targets->erase( &m_targetable ); + } } -} public: -TargetedEntity( Targetable& targetable ) - : m_targetable( targetable ), m_targets( getTargetables( "" ) ){ - construct(); -} -~TargetedEntity(){ - destroy(); -} -void targetnameChanged( const char* name ){ - destroy(); - m_targets = getTargetables( name ); - construct(); -} -typedef MemberCaller1 TargetnameChangedCaller; + TargetedEntity( Targetable& targetable ) + : m_targetable( targetable ), m_targets( getTargetables( "" ) ){ + construct(); + } + ~TargetedEntity(){ + destroy(); + } + void targetnameChanged( const char* name ){ + destroy(); + m_targets = getTargetables( name ); + construct(); + } + typedef MemberCaller1 TargetnameChangedCaller; }; class TargetingEntity { -targetables_t* m_targets; + targetables_t* m_targets; public: -TargetingEntity() : - m_targets( getTargetables( "" ) ){ -} -void targetChanged( const char* target ){ - m_targets = getTargetables( target ); -} -typedef MemberCaller1 TargetChangedCaller; + TargetingEntity() : + m_targets( getTargetables( "" ) ){ + } + void targetChanged( const char* target ){ + m_targets = getTargetables( target ); + } + typedef MemberCaller1 TargetChangedCaller; -typedef targetables_t::iterator iterator; + typedef targetables_t::iterator iterator; -iterator begin() const { - if ( m_targets == 0 ) { - return iterator(); + iterator begin() const { + if ( m_targets == 0 ) { + return iterator(); + } + return m_targets->begin(); } - return m_targets->begin(); -} -iterator end() const { - if ( m_targets == 0 ) { - return iterator(); + iterator end() const { + if ( m_targets == 0 ) { + return iterator(); + } + return m_targets->end(); } - return m_targets->end(); -} -size_t size() const { - if ( m_targets == 0 ) { - return 0; + size_t size() const { + if ( m_targets == 0 ) { + return 0; + } + return m_targets->size(); + } + bool empty() const { + return m_targets == 0 || m_targets->empty(); } - return m_targets->size(); -} -bool empty() const { - return m_targets == 0 || m_targets->empty(); -} }; @@ -176,167 +176,167 @@ void TargetingEntities_forEach( const TargetingEntities& targetingEntities, cons class TargetLinesPushBack { -RenderablePointVector& m_targetLines; -const Vector3& m_worldPosition; -const VolumeTest& m_volume; + RenderablePointVector& m_targetLines; + const Vector3& m_worldPosition; + const VolumeTest& m_volume; public: -TargetLinesPushBack( RenderablePointVector& targetLines, const Vector3& worldPosition, const VolumeTest& volume ) : - m_targetLines( targetLines ), m_worldPosition( worldPosition ), m_volume( volume ){ -} -void operator()( const Vector3& worldPosition ) const { - Vector3 dir( worldPosition - m_worldPosition );//end - start - const double len = vector3_length( dir ); - if ( len != 0 && m_volume.TestLine( segment_for_startend( m_worldPosition, worldPosition ) ) ) { - m_targetLines.push_back( PointVertex( reinterpret_cast( m_worldPosition ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( worldPosition ) ) ); + TargetLinesPushBack( RenderablePointVector& targetLines, const Vector3& worldPosition, const VolumeTest& volume ) : + m_targetLines( targetLines ), m_worldPosition( worldPosition ), m_volume( volume ){ + } + void operator()( const Vector3& worldPosition ) const { + Vector3 dir( worldPosition - m_worldPosition );//end - start + const double len = vector3_length( dir ); + if ( len != 0 && m_volume.TestLine( segment_for_startend( m_worldPosition, worldPosition ) ) ) { + m_targetLines.push_back( PointVertex( reinterpret_cast( m_worldPosition ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( worldPosition ) ) ); - const Vector3 mid( ( worldPosition + m_worldPosition ) * .5f ); - //vector3_normalise( dir ); - dir *= ( 1.0 / len ); - Vector3 hack( 0.57735f, 0.57735f, 0.57735f ); - int maxI = 0; - float max = 0; - for ( int i = 0; i < 3 ; ++i ){ - if ( dir[i] < 0 ){ - hack[i] *= -1.f; + const Vector3 mid( ( worldPosition + m_worldPosition ) * .5f ); + //vector3_normalise( dir ); + dir *= ( 1.0 / len ); + Vector3 hack( 0.57735f, 0.57735f, 0.57735f ); + int maxI = 0; + float max = 0; + for ( int i = 0; i < 3 ; ++i ){ + if ( dir[i] < 0 ){ + hack[i] *= -1.f; + } + if ( fabs( dir[i] ) > max ){ + maxI = i; + max = fabs( dir[i] ); + } } - if ( fabs( dir[i] ) > max ){ - maxI = i; - max = fabs( dir[i] ); + hack[maxI] *= -1.f; + + const Vector3 ort( vector3_cross( dir, hack ) ); + //vector3_normalise( ort ); + Vector3 wing1( mid - dir * 12.f + ort * 6.f ); + Vector3 wing2( wing1 - ort * 12.f ); + + if( len <= 512 || len > 768 ){ + m_targetLines.push_back( PointVertex( reinterpret_cast( mid ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( mid ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); + } + if( len > 512 ){ + const Vector3 wing1_delta( mid - wing1 ); + const Vector3 wing2_delta( mid - wing2 ); + Vector3 point( m_worldPosition + dir * 256.f ); + wing1 = point - wing1_delta; + wing2 = point - wing2_delta; + m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); + point = worldPosition - dir * 256.f; + wing1 = point - wing1_delta; + wing2 = point - wing2_delta; + m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); + m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); } - } - hack[maxI] *= -1.f; - - const Vector3 ort( vector3_cross( dir, hack ) ); - //vector3_normalise( ort ); - Vector3 wing1( mid - dir * 12.f + ort * 6.f ); - Vector3 wing2( wing1 - ort * 12.f ); - - if( len <= 512 || len > 768 ){ - m_targetLines.push_back( PointVertex( reinterpret_cast( mid ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( mid ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); - } - if( len > 512 ){ - const Vector3 wing1_delta( mid - wing1 ); - const Vector3 wing2_delta( mid - wing2 ); - Vector3 point( m_worldPosition + dir * 256.f ); - wing1 = point - wing1_delta; - wing2 = point - wing2_delta; - m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); - point = worldPosition - dir * 256.f; - wing1 = point - wing1_delta; - wing2 = point - wing2_delta; - m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing1 ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( point ) ) ); - m_targetLines.push_back( PointVertex( reinterpret_cast( wing2 ) ) ); } } -} }; class TargetKeys : public Entity::Observer { -TargetingEntities m_targetingEntities; -Callback m_targetsChanged; + TargetingEntities m_targetingEntities; + Callback m_targetsChanged; -bool readTargetKey( const char* key, std::size_t& index ){ - if ( string_equal_n( key, "target", 6 ) ) { - index = 0; - if ( string_empty( key + 6 ) || string_parse_size( key + 6, index ) ) { + bool readTargetKey( const char* key, std::size_t& index ){ + if ( string_equal_n( key, "target", 6 ) ) { + index = 0; + if ( string_empty( key + 6 ) || string_parse_size( key + 6, index ) ) { + return true; + } + } + if ( string_equal( key, "killtarget" ) ) { + index = -1; return true; } + return false; } - if ( string_equal( key, "killtarget" ) ) { - index = -1; - return true; - } - return false; -} public: -void setTargetsChanged( const Callback& targetsChanged ){ - m_targetsChanged = targetsChanged; -} -void targetsChanged(){ - m_targetsChanged(); -} + void setTargetsChanged( const Callback& targetsChanged ){ + m_targetsChanged = targetsChanged; + } + void targetsChanged(){ + m_targetsChanged(); + } -void insert( const char* key, EntityKeyValue& value ){ - std::size_t index; - if ( readTargetKey( key, index ) ) { - TargetingEntities::iterator i = m_targetingEntities.insert( TargetingEntities::value_type( index, TargetingEntity() ) ).first; - value.attach( TargetingEntity::TargetChangedCaller( ( *i ).second ) ); - targetsChanged(); + void insert( const char* key, EntityKeyValue& value ){ + std::size_t index; + if ( readTargetKey( key, index ) ) { + TargetingEntities::iterator i = m_targetingEntities.insert( TargetingEntities::value_type( index, TargetingEntity() ) ).first; + value.attach( TargetingEntity::TargetChangedCaller( ( *i ).second ) ); + targetsChanged(); + } } -} -void erase( const char* key, EntityKeyValue& value ){ - std::size_t index; - if ( readTargetKey( key, index ) ) { - TargetingEntities::iterator i = m_targetingEntities.find( index ); - value.detach( TargetingEntity::TargetChangedCaller( ( *i ).second ) ); - m_targetingEntities.erase( i ); - targetsChanged(); + void erase( const char* key, EntityKeyValue& value ){ + std::size_t index; + if ( readTargetKey( key, index ) ) { + TargetingEntities::iterator i = m_targetingEntities.find( index ); + value.detach( TargetingEntity::TargetChangedCaller( ( *i ).second ) ); + m_targetingEntities.erase( i ); + targetsChanged(); + } + } + const TargetingEntities& get() const { + return m_targetingEntities; } -} -const TargetingEntities& get() const { - return m_targetingEntities; -} }; #if 0 class RenderableTargetingEntity { -TargetingEntity& m_targets; -mutable RenderablePointVector m_target_lines; + TargetingEntity& m_targets; + mutable RenderablePointVector m_target_lines; public: -static Shader* m_state; + static Shader* m_state; -RenderableTargetingEntity( TargetingEntity& targets ) - : m_targets( targets ), m_target_lines( GL_LINES ){ -} -void compile( const VolumeTest& volume, const Vector3& world_position ) const { - m_target_lines.clear(); - m_target_lines.reserve( m_targets.size() * 14 ); - TargetingEntity_forEach( m_targets, TargetLinesPushBack( m_target_lines, world_position, volume ) ); -} -void render( Renderer& renderer, const VolumeTest& volume, const Vector3& world_position ) const { - if ( !m_targets.empty() ) { - compile( volume, world_position ); - if ( !m_target_lines.empty() ) { - renderer.addRenderable( m_target_lines, g_matrix4_identity ); + RenderableTargetingEntity( TargetingEntity& targets ) + : m_targets( targets ), m_target_lines( GL_LINES ){ + } + void compile( const VolumeTest& volume, const Vector3& world_position ) const { + m_target_lines.clear(); + m_target_lines.reserve( m_targets.size() * 14 ); + TargetingEntity_forEach( m_targets, TargetLinesPushBack( m_target_lines, world_position, volume ) ); + } + void render( Renderer& renderer, const VolumeTest& volume, const Vector3& world_position ) const { + if ( !m_targets.empty() ) { + compile( volume, world_position ); + if ( !m_target_lines.empty() ) { + renderer.addRenderable( m_target_lines, g_matrix4_identity ); + } } } -} }; #endif class RenderableTargetingEntities { -const TargetingEntities& m_targets; -mutable RenderablePointVector m_target_lines; + const TargetingEntities& m_targets; + mutable RenderablePointVector m_target_lines; public: //static Shader* m_state; -RenderableTargetingEntities( const TargetingEntities& targets ) - : m_targets( targets ), m_target_lines( GL_LINES ){ -} -void compile( const VolumeTest& volume, const Vector3& world_position ) const { - m_target_lines.clear(); - TargetingEntities_forEach( m_targets, TargetLinesPushBack( m_target_lines, world_position, volume ) ); -} -void render( Renderer& renderer, const VolumeTest& volume, const Vector3& world_position ) const { - if ( !m_targets.empty() ) { - compile( volume, world_position ); - if ( !m_target_lines.empty() ) { - renderer.addRenderable( m_target_lines, g_matrix4_identity ); + RenderableTargetingEntities( const TargetingEntities& targets ) + : m_targets( targets ), m_target_lines( GL_LINES ){ + } + void compile( const VolumeTest& volume, const Vector3& world_position ) const { + m_target_lines.clear(); + TargetingEntities_forEach( m_targets, TargetLinesPushBack( m_target_lines, world_position, volume ) ); + } + void render( Renderer& renderer, const VolumeTest& volume, const Vector3& world_position ) const { + if ( !m_targets.empty() ) { + compile( volume, world_position ); + if ( !m_target_lines.empty() ) { + renderer.addRenderable( m_target_lines, g_matrix4_identity ); + } } } -} }; @@ -345,106 +345,106 @@ class TargetableInstance : public Targetable, public Entity::Observer { -mutable Vertex3f m_position; -EntityKeyValues& m_entity; -TargetKeys m_targeting; -TargetedEntity m_targeted; -RenderableTargetingEntities m_renderable; + mutable Vertex3f m_position; + EntityKeyValues& m_entity; + TargetKeys m_targeting; + TargetedEntity m_targeted; + RenderableTargetingEntities m_renderable; public: -TargetableInstance( - const scene::Path& path, - scene::Instance* parent, - void* instance, - InstanceTypeCastTable& casts, - EntityKeyValues& entity, - Targetable& targetable + TargetableInstance( + const scene::Path& path, + scene::Instance* parent, + void* instance, + InstanceTypeCastTable& casts, + EntityKeyValues& entity, + Targetable& targetable ) : - SelectableInstance( path, parent, instance, casts ), - m_entity( entity ), - m_targeted( targetable ), - m_renderable( m_targeting.get() ){ - m_entity.attach( *this ); - m_entity.attach( m_targeting ); -} -~TargetableInstance(){ - m_entity.detach( m_targeting ); - m_entity.detach( *this ); -} - -void setTargetsChanged( const Callback& targetsChanged ){ - m_targeting.setTargetsChanged( targetsChanged ); -} -void targetsChanged(){ - m_targeting.targetsChanged(); -} - -void insert( const char* key, EntityKeyValue& value ){ - if ( string_equal( key, g_targetable_nameKey ) ) { - value.attach( TargetedEntity::TargetnameChangedCaller( m_targeted ) ); + SelectableInstance( path, parent, instance, casts ), + m_entity( entity ), + m_targeted( targetable ), + m_renderable( m_targeting.get() ){ + m_entity.attach( *this ); + m_entity.attach( m_targeting ); } -} -void erase( const char* key, EntityKeyValue& value ){ - if ( string_equal( key, g_targetable_nameKey ) ) { - value.detach( TargetedEntity::TargetnameChangedCaller( m_targeted ) ); + ~TargetableInstance(){ + m_entity.detach( m_targeting ); + m_entity.detach( *this ); } -} -const Vector3& world_position() const { + void setTargetsChanged( const Callback& targetsChanged ){ + m_targeting.setTargetsChanged( targetsChanged ); + } + void targetsChanged(){ + m_targeting.targetsChanged(); + } + + void insert( const char* key, EntityKeyValue& value ){ + if ( string_equal( key, g_targetable_nameKey ) ) { + value.attach( TargetedEntity::TargetnameChangedCaller( m_targeted ) ); + } + } + void erase( const char* key, EntityKeyValue& value ){ + if ( string_equal( key, g_targetable_nameKey ) ) { + value.detach( TargetedEntity::TargetnameChangedCaller( m_targeted ) ); + } + } + + const Vector3& world_position() const { #if 1 - const AABB& bounds = Instance::worldAABB(); - if ( aabb_valid( bounds ) ) { - return bounds.origin; - } + const AABB& bounds = Instance::worldAABB(); + if ( aabb_valid( bounds ) ) { + return bounds.origin; + } #else - const AABB& childBounds = Instance::childBounds(); - if ( aabb_valid( childBounds ) ) { - return childBounds.origin; - } + const AABB& childBounds = Instance::childBounds(); + if ( aabb_valid( childBounds ) ) { + return childBounds.origin; + } #endif - return vector4_to_vector3( localToWorld().t() ); -} + return vector4_to_vector3( localToWorld().t() ); + } -void render( Renderer& renderer, const VolumeTest& volume ) const { - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); - renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); - m_renderable.render( renderer, volume, world_position() ); -} + void render( Renderer& renderer, const VolumeTest& volume ) const { + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eWireframeOnly ); + renderer.SetState( m_entity.getEntityClass().m_state_wire, Renderer::eFullMaterials ); + m_renderable.render( renderer, volume, world_position() ); + } -const TargetingEntities& getTargeting() const { - return m_targeting.get(); -} + const TargetingEntities& getTargeting() const { + return m_targeting.get(); + } }; #include "entity.h" class RenderableConnectionLines : public Renderable { -typedef std::set TargetableInstances; -TargetableInstances m_instances; + typedef std::set TargetableInstances; + TargetableInstances m_instances; public: -void attach( TargetableInstance& instance ){ - const bool inserted = m_instances.insert( &instance ).second; - ASSERT_MESSAGE( inserted, "cannot attach instance" ); -} -void detach( TargetableInstance& instance ){ - const bool erased = m_instances.erase( &instance ); - ASSERT_MESSAGE( erased, "cannot detach instance" ); -} + void attach( TargetableInstance& instance ){ + const bool inserted = m_instances.insert( &instance ).second; + ASSERT_MESSAGE( inserted, "cannot attach instance" ); + } + void detach( TargetableInstance& instance ){ + const bool erased = m_instances.erase( &instance ); + ASSERT_MESSAGE( erased, "cannot detach instance" ); + } -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - if( g_showConnections ){ - for ( TargetableInstances::const_iterator i = m_instances.begin(); i != m_instances.end(); ++i ) - { - if ( ( *i )->path().top().get().visible() ) { - ( *i )->render( renderer, volume ); + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if( g_showConnections ){ + for ( TargetableInstances::const_iterator i = m_instances.begin(); i != m_instances.end(); ++i ) + { + if ( ( *i )->path().top().get().visible() ) { + ( *i )->render( renderer, volume ); + } } } } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); + } }; typedef Static StaticRenderableConnectionLines; diff --git a/plugins/image/bmp.cpp b/plugins/image/bmp.cpp index 63ce4a05..bf26ebef 100644 --- a/plugins/image/bmp.cpp +++ b/plugins/image/bmp.cpp @@ -52,57 +52,57 @@ typedef struct class ReadPixel8 { -PaletteEntry* m_palette; + PaletteEntry* m_palette; public: -ReadPixel8( PaletteEntry* palette ) : m_palette( palette ){ -} -void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { - byte palIndex; - inputStream.read( &palIndex, 1 ); - *pixbuf++ = m_palette[palIndex][2]; - *pixbuf++ = m_palette[palIndex][1]; - *pixbuf++ = m_palette[palIndex][0]; - *pixbuf++ = 0xff; -} + ReadPixel8( PaletteEntry* palette ) : m_palette( palette ){ + } + void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { + byte palIndex; + inputStream.read( &palIndex, 1 ); + *pixbuf++ = m_palette[palIndex][2]; + *pixbuf++ = m_palette[palIndex][1]; + *pixbuf++ = m_palette[palIndex][0]; + *pixbuf++ = 0xff; + } }; class ReadPixel16 { public: -void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { - unsigned short shortPixel; - inputStream.read( reinterpret_cast( &shortPixel ), sizeof( unsigned short ) ); //!\todo Is this endian safe? - *pixbuf++ = static_cast( shortPixel & ( 31 << 10 ) ) >> 7; - *pixbuf++ = static_cast( shortPixel & ( 31 << 5 ) ) >> 2; - *pixbuf++ = static_cast( shortPixel & ( 31 ) ) << 3; - *pixbuf++ = 0xff; -} + void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { + unsigned short shortPixel; + inputStream.read( reinterpret_cast( &shortPixel ), sizeof( unsigned short ) ); //!\todo Is this endian safe? + *pixbuf++ = static_cast( shortPixel & ( 31 << 10 ) ) >> 7; + *pixbuf++ = static_cast( shortPixel & ( 31 << 5 ) ) >> 2; + *pixbuf++ = static_cast( shortPixel & ( 31 ) ) << 3; + *pixbuf++ = 0xff; + } }; class ReadPixel24 { public: -void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { - byte bgr[3]; - inputStream.read( bgr, 3 ); - *pixbuf++ = bgr[2]; - *pixbuf++ = bgr[1]; - *pixbuf++ = bgr[0]; - *pixbuf++ = 255; -} + void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { + byte bgr[3]; + inputStream.read( bgr, 3 ); + *pixbuf++ = bgr[2]; + *pixbuf++ = bgr[1]; + *pixbuf++ = bgr[0]; + *pixbuf++ = 255; + } }; class ReadPixel32 { public: -void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { - byte bgra[4]; - inputStream.read( bgra, 4 ); - *pixbuf++ = bgra[2]; - *pixbuf++ = bgra[1]; - *pixbuf++ = bgra[0]; - *pixbuf++ = bgra[3]; -} + void operator()( PointerInputStream& inputStream, byte*& pixbuf ) const { + byte bgra[4]; + inputStream.read( bgra, 4 ); + *pixbuf++ = bgra[2]; + *pixbuf++ = bgra[1]; + *pixbuf++ = bgra[0]; + *pixbuf++ = bgra[3]; + } }; template diff --git a/plugins/image/image.cpp b/plugins/image/image.cpp index fcfdd018..e9639e14 100644 --- a/plugins/image/image.cpp +++ b/plugins/image/image.cpp @@ -39,17 +39,17 @@ class ImageDependencies : public GlobalFileSystemModuleRef class ImageTGAAPI { -_QERPlugImageTable m_imagetga; + _QERPlugImageTable m_imagetga; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "tga" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "tga" ); -ImageTGAAPI(){ - m_imagetga.loadImage = LoadTGA; -} -_QERPlugImageTable* getTable(){ - return &m_imagetga; -} + ImageTGAAPI(){ + m_imagetga.loadImage = LoadTGA; + } + _QERPlugImageTable* getTable(){ + return &m_imagetga; + } }; typedef SingletonModule ImageTGAModule; @@ -59,17 +59,17 @@ ImageTGAModule g_ImageTGAModule; class ImageJPGAPI { -_QERPlugImageTable m_imagejpg; + _QERPlugImageTable m_imagejpg; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "jpg" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "jpg" ); -ImageJPGAPI(){ - m_imagejpg.loadImage = LoadJPG; -} -_QERPlugImageTable* getTable(){ - return &m_imagejpg; -} + ImageJPGAPI(){ + m_imagejpg.loadImage = LoadJPG; + } + _QERPlugImageTable* getTable(){ + return &m_imagejpg; + } }; typedef SingletonModule ImageJPGModule; @@ -79,17 +79,17 @@ ImageJPGModule g_ImageJPGModule; class ImageBMPAPI { -_QERPlugImageTable m_imagebmp; + _QERPlugImageTable m_imagebmp; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "bmp" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "bmp" ); -ImageBMPAPI(){ - m_imagebmp.loadImage = LoadBMP; -} -_QERPlugImageTable* getTable(){ - return &m_imagebmp; -} + ImageBMPAPI(){ + m_imagebmp.loadImage = LoadBMP; + } + _QERPlugImageTable* getTable(){ + return &m_imagebmp; + } }; typedef SingletonModule ImageBMPModule; @@ -99,17 +99,17 @@ ImageBMPModule g_ImageBMPModule; class ImagePCXAPI { -_QERPlugImageTable m_imagepcx; + _QERPlugImageTable m_imagepcx; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "pcx" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "pcx" ); -ImagePCXAPI(){ - m_imagepcx.loadImage = LoadPCX32; -} -_QERPlugImageTable* getTable(){ - return &m_imagepcx; -} + ImagePCXAPI(){ + m_imagepcx.loadImage = LoadPCX32; + } + _QERPlugImageTable* getTable(){ + return &m_imagepcx; + } }; typedef SingletonModule ImagePCXModule; @@ -119,17 +119,17 @@ ImagePCXModule g_ImagePCXModule; class ImageDDSAPI { -_QERPlugImageTable m_imagedds; + _QERPlugImageTable m_imagedds; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "dds" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "dds" ); -ImageDDSAPI(){ - m_imagedds.loadImage = LoadDDS; -} -_QERPlugImageTable* getTable(){ - return &m_imagedds; -} + ImageDDSAPI(){ + m_imagedds.loadImage = LoadDDS; + } + _QERPlugImageTable* getTable(){ + return &m_imagedds; + } }; typedef SingletonModule ImageDDSModule; diff --git a/plugins/image/jpeg.cpp b/plugins/image/jpeg.cpp index 2ca5a380..1d1c933a 100644 --- a/plugins/image/jpeg.cpp +++ b/plugins/image/jpeg.cpp @@ -226,12 +226,12 @@ static void jpeg_buffer_src( j_decompress_ptr cinfo, void* buffer, int bufsize ) */ if ( cinfo->src == NULL ) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - sizeof( my_source_mgr ) ); + ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, + sizeof( my_source_mgr ) ); src = (my_src_ptr) cinfo->src; src->buffer = (JOCTET *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - INPUT_BUF_SIZE * sizeof( JOCTET ) ); + ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, + INPUT_BUF_SIZE * sizeof( JOCTET ) ); } src = (my_src_ptr) cinfo->src; diff --git a/plugins/image/pcx.cpp b/plugins/image/pcx.cpp index 46bffc05..02f2a041 100644 --- a/plugins/image/pcx.cpp +++ b/plugins/image/pcx.cpp @@ -111,9 +111,9 @@ void LoadPCXBuff( byte* buffer, std::size_t len, byte **pic, byte **palette, int if ( pcx.manufacturer != 0x0a - || pcx.version != 5 - || pcx.encoding != 1 - || pcx.bits_per_pixel != 8 ) { + || pcx.version != 5 + || pcx.encoding != 1 + || pcx.bits_per_pixel != 8 ) { return; } diff --git a/plugins/image/tga.cpp b/plugins/image/tga.cpp index f926f8bf..a845d5c6 100644 --- a/plugins/image/tga.cpp +++ b/plugins/image/tga.cpp @@ -162,9 +162,9 @@ template class TargaDecodePixel { public: -void operator()( PointerInputStream& istream, RGBAPixel& pixel ) const { - istream_read_pixel( istream, pixel ); -} + void operator()( PointerInputStream& istream, RGBAPixel& pixel ) const { + istream_read_pixel( istream, pixel ); + } }; template @@ -193,33 +193,33 @@ inline TargaPacketSize targa_packet_size( const TargaPacket& packet ){ template class TargaDecodePixelRLE { -TargaPacketSize m_packetSize; -RGBAPixel m_pixel; -TargaPacket m_packet; -const PixelReadFunctor& m_pixelRead; + TargaPacketSize m_packetSize; + RGBAPixel m_pixel; + TargaPacket m_packet; + const PixelReadFunctor& m_pixelRead; public: -TargaDecodePixelRLE( const PixelReadFunctor& pixelRead ) : m_packetSize( 0 ), m_pixelRead( pixelRead ){ -} -void operator()( PointerInputStream& istream, RGBAPixel& pixel ){ - if ( m_packetSize == 0 ) { - targa_packet_read_istream( m_packet, istream ); - m_packetSize = targa_packet_size( m_packet ); + TargaDecodePixelRLE( const PixelReadFunctor& pixelRead ) : m_packetSize( 0 ), m_pixelRead( pixelRead ){ + } + void operator()( PointerInputStream& istream, RGBAPixel& pixel ){ + if ( m_packetSize == 0 ) { + targa_packet_read_istream( m_packet, istream ); + m_packetSize = targa_packet_size( m_packet ); + + if ( targa_packet_is_rle( m_packet ) ) { + m_pixelRead( istream, m_pixel ); + } + } if ( targa_packet_is_rle( m_packet ) ) { - m_pixelRead( istream, m_pixel ); + pixel = m_pixel; + } + else + { + m_pixelRead( istream, pixel ); } - } - if ( targa_packet_is_rle( m_packet ) ) { - pixel = m_pixel; + --m_packetSize; } - else - { - m_pixelRead( istream, pixel ); - } - - --m_packetSize; -} }; template @@ -368,11 +368,11 @@ Image* LoadTGABuff( const byte* buffer ){ targa_header_read_istream( targa_header, istream ); if ( targa_header.image_type != 1 && - targa_header.image_type != 2 && - targa_header.image_type != 3 && - targa_header.image_type != 9 && - targa_header.image_type != 10 && - targa_header.image_type != 11 ) { + targa_header.image_type != 2 && + targa_header.image_type != 3 && + targa_header.image_type != 9 && + targa_header.image_type != 10 && + targa_header.image_type != 11 ) { globalErrorStream() << "LoadTGA: TGA type " << targa_header.image_type << " not supported\n"; globalErrorStream() << "LoadTGA: Only uncompressed types: 1 (paletted), 2 (RGB), 3 (gray) and compressed: 9 (paletted), 10 (RGB), 11 (gray) of TGA images supported\n"; return 0; @@ -390,26 +390,26 @@ Image* LoadTGABuff( const byte* buffer ){ } if ( ( ( targa_header.image_type == 2 || targa_header.image_type == 10 ) && targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) || - ( ( targa_header.image_type == 3 || targa_header.image_type == 11 ) && targa_header.pixel_size != 8 ) || - ( ( targa_header.image_type == 1 || targa_header.image_type == 9 ) && targa_header.pixel_size != 8 ) ) { + ( ( targa_header.image_type == 3 || targa_header.image_type == 11 ) && targa_header.pixel_size != 8 ) || + ( ( targa_header.image_type == 1 || targa_header.image_type == 9 ) && targa_header.pixel_size != 8 ) ) { globalErrorStream() << "LoadTGA: Only 32, 24 or 8 bit images supported\n"; return 0; } if ( !bitfield_enabled( targa_header.attributes, TGA_FLIP_HORIZONTAL ) - && !bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { + && !bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { return Targa_decodeImageData( targa_header, istream, Flip00() ); } if ( !bitfield_enabled( targa_header.attributes, TGA_FLIP_HORIZONTAL ) - && bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { + && bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { return Targa_decodeImageData( targa_header, istream, Flip01() ); } if ( bitfield_enabled( targa_header.attributes, TGA_FLIP_HORIZONTAL ) - && !bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { + && !bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { return Targa_decodeImageData( targa_header, istream, Flip10() ); } if ( bitfield_enabled( targa_header.attributes, TGA_FLIP_HORIZONTAL ) - && bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { + && bitfield_enabled( targa_header.attributes, TGA_FLIP_VERTICAL ) ) { return Targa_decodeImageData( targa_header, istream, Flip11() ); } diff --git a/plugins/imagehl/imagehl.cpp b/plugins/imagehl/imagehl.cpp index 479a0d99..396277df 100644 --- a/plugins/imagehl/imagehl.cpp +++ b/plugins/imagehl/imagehl.cpp @@ -38,17 +38,17 @@ class ImageDependencies : public GlobalFileSystemModuleRef class ImageHLWAPI { -_QERPlugImageTable m_imagehlw; + _QERPlugImageTable m_imagehlw; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "hlw" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "hlw" ); -ImageHLWAPI(){ - m_imagehlw.loadImage = LoadHLW; -} -_QERPlugImageTable* getTable(){ - return &m_imagehlw; -} + ImageHLWAPI(){ + m_imagehlw.loadImage = LoadHLW; + } + _QERPlugImageTable* getTable(){ + return &m_imagehlw; + } }; typedef SingletonModule ImageHLWModule; @@ -58,17 +58,17 @@ ImageHLWModule g_ImageHLWModule; class ImageMipAPI { -_QERPlugImageTable m_imagemip; + _QERPlugImageTable m_imagemip; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "mip" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "mip" ); -ImageMipAPI(){ - m_imagemip.loadImage = LoadMIP; -} -_QERPlugImageTable* getTable(){ - return &m_imagemip; -} + ImageMipAPI(){ + m_imagemip.loadImage = LoadMIP; + } + _QERPlugImageTable* getTable(){ + return &m_imagemip; + } }; typedef SingletonModule ImageMipModule; @@ -78,17 +78,17 @@ ImageMipModule g_ImageMipModule; class ImageSpriteAPI { -_QERPlugImageTable m_imagesprite; + _QERPlugImageTable m_imagesprite; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "spr" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "spr" ); -ImageSpriteAPI(){ - m_imagesprite.loadImage = LoadIDSP; -} -_QERPlugImageTable* getTable(){ - return &m_imagesprite; -} + ImageSpriteAPI(){ + m_imagesprite.loadImage = LoadIDSP; + } + _QERPlugImageTable* getTable(){ + return &m_imagesprite; + } }; typedef SingletonModule ImageSpriteModule; diff --git a/plugins/imagehl/sprite.cpp b/plugins/imagehl/sprite.cpp index 3811d1c4..cb82ef91 100644 --- a/plugins/imagehl/sprite.cpp +++ b/plugins/imagehl/sprite.cpp @@ -127,7 +127,7 @@ Image* LoadIDSPBuff( byte *buffer ){ version = header->version; if ( version != 1 && version != 2 ) { globalWarningStream() << "WARNING: IDSP file has wrong version number " - "(" << version << " should be 1 or 2)\n"; + "(" << version << " should be 1 or 2)\n"; return 0; } diff --git a/plugins/imagepng/plugin.cpp b/plugins/imagepng/plugin.cpp index 9551b9d4..2e0a2925 100644 --- a/plugins/imagepng/plugin.cpp +++ b/plugins/imagepng/plugin.cpp @@ -58,8 +58,8 @@ Image* LoadPNGBuff( unsigned char* fbuffer ){ // http://www.libpng.org/pub/png/libpng-manual.html png_structp png_ptr = png_create_read_struct - ( PNG_LIBPNG_VER_STRING, (png_voidp)NULL, - user_error_fn, user_warning_fn ); + ( PNG_LIBPNG_VER_STRING, (png_voidp)NULL, + user_error_fn, user_warning_fn ); if ( !png_ptr ) { globalErrorStream() << "libpng error: png_create_read_struct\n"; return 0; @@ -67,16 +67,14 @@ Image* LoadPNGBuff( unsigned char* fbuffer ){ png_infop info_ptr = png_create_info_struct( png_ptr ); if ( !info_ptr ) { - png_destroy_read_struct( &png_ptr, - (png_infopp)NULL, (png_infopp)NULL ); + png_destroy_read_struct( &png_ptr, (png_infopp)NULL, (png_infopp)NULL ); globalErrorStream() << "libpng error: png_create_info_struct (info_ptr)\n"; return 0; } png_infop end_info = png_create_info_struct( png_ptr ); if ( !end_info ) { - png_destroy_read_struct( &png_ptr, &info_ptr, - (png_infopp)NULL ); + png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp)NULL ); globalErrorStream() << "libpng error: png_create_info_struct (end_info)\n"; return 0; } @@ -85,8 +83,7 @@ Image* LoadPNGBuff( unsigned char* fbuffer ){ png_set_read_fn( png_ptr, ( png_voidp ) & p_fbuffer, ( png_rw_ptr ) & user_read_data ); if ( setjmp( png_jmpbuf(png_ptr) ) ) { - png_destroy_read_struct( &png_ptr, &info_ptr, - &end_info ); + png_destroy_read_struct( &png_ptr, &info_ptr, &end_info ); return 0; } @@ -121,11 +118,11 @@ Image* LoadPNGBuff( unsigned char* fbuffer ){ if ( png_get_bKGD( png_ptr, info_ptr, &image_background ) ) { png_set_background( png_ptr, image_background, - PNG_BACKGROUND_GAMMA_FILE, 1, 1.0 ); + PNG_BACKGROUND_GAMMA_FILE, 1, 1.0 ); } else{ png_set_background( png_ptr, &my_background, - PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0 ); + PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0 ); } // Add alpha byte after each RGB triplet @@ -181,17 +178,17 @@ class ImageDependencies : public GlobalFileSystemModuleRef class ImagePNGAPI { -_QERPlugImageTable m_imagepng; + _QERPlugImageTable m_imagepng; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "png" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "png" ); -ImagePNGAPI(){ - m_imagepng.loadImage = LoadPNG; -} -_QERPlugImageTable* getTable(){ - return &m_imagepng; -} + ImagePNGAPI(){ + m_imagepng.loadImage = LoadPNG; + } + _QERPlugImageTable* getTable(){ + return &m_imagepng; + } }; typedef SingletonModule ImagePNGModule; diff --git a/plugins/imageq2/imageq2.cpp b/plugins/imageq2/imageq2.cpp index 62101667..475205fe 100644 --- a/plugins/imageq2/imageq2.cpp +++ b/plugins/imageq2/imageq2.cpp @@ -37,17 +37,17 @@ class ImageDependencies : public GlobalFileSystemModuleRef class ImageWalAPI { -_QERPlugImageTable m_imagewal; + _QERPlugImageTable m_imagewal; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "wal" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "wal" ); -ImageWalAPI(){ - m_imagewal.loadImage = LoadWal; -} -_QERPlugImageTable* getTable(){ - return &m_imagewal; -} + ImageWalAPI(){ + m_imagewal.loadImage = LoadWal; + } + _QERPlugImageTable* getTable(){ + return &m_imagewal; + } }; typedef SingletonModule ImageWalModule; @@ -58,17 +58,17 @@ ImageWalModule g_ImageWalModule; class ImageM8API { -_QERPlugImageTable m_imagem8; + _QERPlugImageTable m_imagem8; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "m8" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "m8" ); -ImageM8API(){ - m_imagem8.loadImage = LoadM8; -} -_QERPlugImageTable* getTable(){ - return &m_imagem8; -} + ImageM8API(){ + m_imagem8.loadImage = LoadM8; + } + _QERPlugImageTable* getTable(){ + return &m_imagem8; + } }; typedef SingletonModule ImageM8Module; @@ -79,17 +79,17 @@ ImageM8Module g_ImageM8Module; class ImageM32API { -_QERPlugImageTable m_imagem32; + _QERPlugImageTable m_imagem32; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "m32" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "m32" ); -ImageM32API(){ - m_imagem32.loadImage = LoadM32; -} -_QERPlugImageTable* getTable(){ - return &m_imagem32; -} + ImageM32API(){ + m_imagem32.loadImage = LoadM32; + } + _QERPlugImageTable* getTable(){ + return &m_imagem32; + } }; typedef SingletonModule ImageM32Module; diff --git a/plugins/imageq2/wal.cpp b/plugins/imageq2/wal.cpp index 6160887b..ce63341d 100644 --- a/plugins/imageq2/wal.cpp +++ b/plugins/imageq2/wal.cpp @@ -51,9 +51,9 @@ void LoadPCXPalette( const char *filename, byte palette[768] ){ const pcx_header_t* pcx = reinterpret_cast( buffer ); if ( pcx->manufacturer != 0x0a - || pcx->version != 5 - || pcx->encoding != 1 - || pcx->bits_per_pixel != 8 ) { + || pcx->version != 5 + || pcx->encoding != 1 + || pcx->bits_per_pixel != 8 ) { return; } diff --git a/plugins/imageq2/wal32.cpp b/plugins/imageq2/wal32.cpp index b202137a..4195b759 100644 --- a/plugins/imageq2/wal32.cpp +++ b/plugins/imageq2/wal32.cpp @@ -61,10 +61,10 @@ Image* LoadM32Buff( byte* buffer ){ PointerInputStream inputStream( buffer ); inputStream.seek( 4 // version - + M32_NAME_LENGTH // name - + M32_NAME_LENGTH // altname - + M32_NAME_LENGTH // animname - + M32_NAME_LENGTH ); // damagename + + M32_NAME_LENGTH // name + + M32_NAME_LENGTH // altname + + M32_NAME_LENGTH // animname + + M32_NAME_LENGTH ); // damagename int w = istream_read_uint32_le( inputStream ); inputStream.seek( 4 * ( M32_MIPMAP_COUNT - 1 ) ); // remaining widths int h = istream_read_uint32_le( inputStream ); diff --git a/plugins/mapq3/parse.h b/plugins/mapq3/parse.h index 1523c6ad..9b6d1d2d 100644 --- a/plugins/mapq3/parse.h +++ b/plugins/mapq3/parse.h @@ -30,7 +30,7 @@ class PatchCreator; class PrimitiveParser { public: -virtual scene::Node& parsePrimitive( Tokeniser& tokeniser ) const = 0; + virtual scene::Node& parsePrimitive( Tokeniser& tokeniser ) const = 0; }; void Map_Read( scene::Node& root, Tokeniser& tokeniser, EntityCreator& entityTable, const PrimitiveParser& parser ); diff --git a/plugins/mapq3/plugin.cpp b/plugins/mapq3/plugin.cpp index 125020ca..693f3731 100644 --- a/plugins/mapq3/plugin.cpp +++ b/plugins/mapq3/plugin.cpp @@ -47,92 +47,92 @@ class MapDoom3Dependencies : public GlobalSceneGraphModuleRef, public GlobalBrushModuleRef { -PatchModuleRef m_patchDef2Doom3Module; -PatchModuleRef m_patchDoom3Module; + PatchModuleRef m_patchDef2Doom3Module; + PatchModuleRef m_patchDoom3Module; public: -MapDoom3Dependencies() : - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), - GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), - m_patchDef2Doom3Module( "def2doom3" ), - m_patchDoom3Module( "doom3" ){ -} -BrushCreator& getBrushDoom3(){ - return GlobalBrushCreator(); -} -PatchCreator& getPatchDoom3(){ - return *m_patchDoom3Module.getTable(); -} -PatchCreator& getPatchDef2Doom3(){ - return *m_patchDef2Doom3Module.getTable(); -} + MapDoom3Dependencies() : + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + m_patchDef2Doom3Module( "def2doom3" ), + m_patchDoom3Module( "doom3" ){ + } + BrushCreator& getBrushDoom3(){ + return GlobalBrushCreator(); + } + PatchCreator& getPatchDoom3(){ + return *m_patchDoom3Module.getTable(); + } + PatchCreator& getPatchDef2Doom3(){ + return *m_patchDef2Doom3Module.getTable(); + } }; class MapDoom3API final : public TypeSystemRef, public MapFormat, public PrimitiveParser { -MapDoom3Dependencies& m_dependencies; + MapDoom3Dependencies& m_dependencies; public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapdoom3" ); -INTEGER_CONSTANT( MapVersion, 2 ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapdoom3" ); + INTEGER_CONSTANT( MapVersion, 2 ); -MapDoom3API( MapDoom3Dependencies& dependencies ) : m_dependencies( dependencies ){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "doom3 maps", "*.map" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "doom3 region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} - -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if ( string_equal( primitive, "patchDef3" ) ) { - return m_dependencies.getPatchDoom3().createPatch(); - } - else if ( string_equal( primitive, "patchDef2" ) ) { - return m_dependencies.getPatchDef2Doom3().createPatch(); - } - else if ( string_equal( primitive, "brushDef3" ) ) { - return m_dependencies.getBrushDoom3().createBrush(); - } + MapDoom3API( MapDoom3Dependencies& dependencies ) : m_dependencies( dependencies ){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "doom3 maps", "*.map" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "doom3 region", "*.reg" ) ); + } + MapFormat* getTable(){ + return this; } - Tokeniser_unexpectedError( tokeniser, primitive, "#doom3-primitive" ); - return g_nullNode; -} -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - tokeniser.nextLine(); - if ( !Tokeniser_parseToken( tokeniser, "Version" ) ) { - return; + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if ( string_equal( primitive, "patchDef3" ) ) { + return m_dependencies.getPatchDoom3().createPatch(); + } + else if ( string_equal( primitive, "patchDef2" ) ) { + return m_dependencies.getPatchDef2Doom3().createPatch(); + } + else if ( string_equal( primitive, "brushDef3" ) ) { + return m_dependencies.getBrushDoom3().createBrush(); + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#doom3-primitive" ); + return g_nullNode; } - int version; - if ( !Tokeniser_getInteger( tokeniser, version ) ) { - return; + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + tokeniser.nextLine(); + if ( !Tokeniser_parseToken( tokeniser, "Version" ) ) { + return; + } + int version; + if ( !Tokeniser_getInteger( tokeniser, version ) ) { + return; + } + if ( version != MapVersion() ) { + globalErrorStream() << "Doom 3 map version " << MapVersion() << " supported, version is " << version << "\n"; + return; + } + tokeniser.nextLine(); + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); } - if ( version != MapVersion() ) { - globalErrorStream() << "Doom 3 map version " << MapVersion() << " supported, version is " << version << "\n"; - return; + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + writer.writeToken( "Version" ); + writer.writeInteger( MapVersion() ); + writer.nextLine(); + Map_Write( root, traverse, writer, false ); + writer.release(); } - tokeniser.nextLine(); - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - writer.writeToken( "Version" ); - writer.writeInteger( MapVersion() ); - writer.nextLine(); - Map_Write( root, traverse, writer, false ); - writer.release(); -} }; typedef SingletonModule< - MapDoom3API, - MapDoom3Dependencies, - DependenciesAPIConstructor - > +MapDoom3API, +MapDoom3Dependencies, +DependenciesAPIConstructor +> MapDoom3Module; MapDoom3Module g_MapDoom3Module; @@ -140,70 +140,70 @@ MapDoom3Module g_MapDoom3Module; class MapQuake4API final : public TypeSystemRef, public MapFormat, public PrimitiveParser { -MapDoom3Dependencies& m_dependencies; + MapDoom3Dependencies& m_dependencies; public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapquake4" ); -INTEGER_CONSTANT( MapVersion, 3 ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapquake4" ); + INTEGER_CONSTANT( MapVersion, 3 ); -MapQuake4API( MapDoom3Dependencies& dependencies ) : m_dependencies( dependencies ){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake4 maps", "*.map" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake4 region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} - -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if ( string_equal( primitive, "patchDef3" ) ) { - return m_dependencies.getPatchDoom3().createPatch(); - } - else if ( string_equal( primitive, "patchDef2" ) ) { - return m_dependencies.getPatchDef2Doom3().createPatch(); - } - else if ( string_equal( primitive, "brushDef3" ) ) { - return m_dependencies.getBrushDoom3().createBrush(); - } + MapQuake4API( MapDoom3Dependencies& dependencies ) : m_dependencies( dependencies ){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake4 maps", "*.map" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake4 region", "*.reg" ) ); + } + MapFormat* getTable(){ + return this; } - Tokeniser_unexpectedError( tokeniser, primitive, "#quake4-primitive" ); - return g_nullNode; -} -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - tokeniser.nextLine(); - if ( !Tokeniser_parseToken( tokeniser, "Version" ) ) { - return; + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if ( string_equal( primitive, "patchDef3" ) ) { + return m_dependencies.getPatchDoom3().createPatch(); + } + else if ( string_equal( primitive, "patchDef2" ) ) { + return m_dependencies.getPatchDef2Doom3().createPatch(); + } + else if ( string_equal( primitive, "brushDef3" ) ) { + return m_dependencies.getBrushDoom3().createBrush(); + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#quake4-primitive" ); + return g_nullNode; } - int version; - if ( !Tokeniser_getInteger( tokeniser, version ) ) { - return; + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + tokeniser.nextLine(); + if ( !Tokeniser_parseToken( tokeniser, "Version" ) ) { + return; + } + int version; + if ( !Tokeniser_getInteger( tokeniser, version ) ) { + return; + } + if ( version != MapVersion() ) { + globalErrorStream() << "Quake 4 map version " << MapVersion() << " supported, version is " << version << "\n"; + return; + } + tokeniser.nextLine(); + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); } - if ( version != MapVersion() ) { - globalErrorStream() << "Quake 4 map version " << MapVersion() << " supported, version is " << version << "\n"; - return; + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + writer.writeToken( "Version" ); + writer.writeInteger( MapVersion() ); + writer.nextLine(); + Map_Write( root, traverse, writer, false ); + writer.release(); } - tokeniser.nextLine(); - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - writer.writeToken( "Version" ); - writer.writeInteger( MapVersion() ); - writer.nextLine(); - Map_Write( root, traverse, writer, false ); - writer.release(); -} }; typedef SingletonModule< - MapQuake4API, - MapDoom3Dependencies, - DependenciesAPIConstructor - > +MapQuake4API, +MapDoom3Dependencies, +DependenciesAPIConstructor +> MapQuake4Module; MapQuake4Module g_MapQuake4Module; @@ -219,88 +219,88 @@ class MapDependencies : public GlobalSceneGraphModuleRef { public: -MapDependencies() : - GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), - GlobalPatchModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "patchtypes" ) ), - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ -} + MapDependencies() : + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + GlobalPatchModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "patchtypes" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ + } }; class MapQ3API final : public TypeSystemRef, public MapFormat, public PrimitiveParser { -mutable bool m_formatDetected; + mutable bool m_formatDetected; public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapq3" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapq3" ); -MapQ3API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 maps", "*.map", true, true, true ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 region", "*.reg", true, true, true ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 compiled maps", "*.bsp", false, true, false ) ); -} -MapFormat* getTable(){ - return this; -} - -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if ( string_equal( primitive, "patchDef2" ) ) { - return GlobalPatchModule::getTable().createPatch(); - } - if( !m_formatDetected ){ - EBrushType detectedFormat; - if ( string_equal( primitive, "brushDef" ) ) { - detectedFormat = eBrushTypeQuake3BP; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; - } - else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { - detectedFormat = eBrushTypeQuake3Valve220; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3Valve220\n"; - } - else if ( string_equal( primitive, "(" ) ) { - detectedFormat = eBrushTypeQuake3; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3\n"; - } - else{ - globalErrorStream() << "Format is not detected\n"; - Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); - return g_nullNode; - } - m_formatDetected = true; - if( detectedFormat != GlobalBrushCreator().getFormat() ){ - GlobalBrushCreator().toggleFormat( detectedFormat ); - } - } - - switch ( GlobalBrushCreator().getFormat() ) - { - case eBrushTypeQuake3: - case eBrushTypeQuake3Valve220: - tokeniser.ungetToken(); // ( - // fall through - case eBrushTypeQuake3BP: - return GlobalBrushCreator().createBrush(); - default: - break; - } + MapQ3API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 maps", "*.map", true, true, true ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 region", "*.reg", true, true, true ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake3 compiled maps", "*.bsp", false, true, false ) ); + } + MapFormat* getTable(){ + return this; } - Tokeniser_unexpectedError( tokeniser, primitive, "#quake3-primitive" ); - return g_nullNode; -} + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if ( string_equal( primitive, "patchDef2" ) ) { + return GlobalPatchModule::getTable().createPatch(); + } + if( !m_formatDetected ){ + EBrushType detectedFormat; + if ( string_equal( primitive, "brushDef" ) ) { + detectedFormat = eBrushTypeQuake3BP; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; + } + else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { + detectedFormat = eBrushTypeQuake3Valve220; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3Valve220\n"; + } + else if ( string_equal( primitive, "(" ) ) { + detectedFormat = eBrushTypeQuake3; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3\n"; + } + else{ + globalErrorStream() << "Format is not detected\n"; + Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); + return g_nullNode; + } + m_formatDetected = true; + if( detectedFormat != GlobalBrushCreator().getFormat() ){ + GlobalBrushCreator().toggleFormat( detectedFormat ); + } + } -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - m_formatDetected = false; - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - Map_Write( root, traverse, writer, false ); - writer.release(); -} + switch ( GlobalBrushCreator().getFormat() ) + { + case eBrushTypeQuake3: + case eBrushTypeQuake3Valve220: + tokeniser.ungetToken(); // ( + // fall through + case eBrushTypeQuake3BP: + return GlobalBrushCreator().createBrush(); + default: + break; + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#quake3-primitive" ); + return g_nullNode; + } + + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + m_formatDetected = false; + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + Map_Write( root, traverse, writer, false ); + writer.release(); + } }; typedef SingletonModule MapQ3Module; @@ -310,74 +310,74 @@ MapQ3Module g_MapQ3Module; class MapQ1API final : public TypeSystemRef, public MapFormat, public PrimitiveParser { -mutable bool m_formatDetected; + mutable bool m_formatDetected; public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapq1" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapq1" ); -MapQ1API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake maps", "*.map" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} - -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if( !m_formatDetected ){ - EBrushType detectedFormat; - if ( string_equal( primitive, "brushDef" ) ) { - detectedFormat = eBrushTypeQuake3BP; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; - } - else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { - detectedFormat = eBrushTypeValve220; - globalWarningStream() << "detectedFormat = eBrushTypeValve220\n"; - } - else if ( string_equal( primitive, "(" ) ) { - detectedFormat = eBrushTypeQuake; - globalWarningStream() << "detectedFormat = eBrushTypeQuake\n"; - } - else{ - globalErrorStream() << "Format is not detected\n"; - Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); - return g_nullNode; - } - m_formatDetected = true; - if( detectedFormat != GlobalBrushCreator().getFormat() ){ - GlobalBrushCreator().toggleFormat( detectedFormat ); - } - } - - switch ( GlobalBrushCreator().getFormat() ) - { - case eBrushTypeQuake: - case eBrushTypeValve220: - tokeniser.ungetToken(); // ( - // fall through - case eBrushTypeQuake3BP: - return GlobalBrushCreator().createBrush(); - default: - break; - } + MapQ1API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake maps", "*.map" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake region", "*.reg" ) ); + } + MapFormat* getTable(){ + return this; } - Tokeniser_unexpectedError( tokeniser, primitive, "#quake-primitive" ); - return g_nullNode; -} -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - m_formatDetected = false; - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - Map_Write( root, traverse, writer, true ); - writer.release(); -} + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if( !m_formatDetected ){ + EBrushType detectedFormat; + if ( string_equal( primitive, "brushDef" ) ) { + detectedFormat = eBrushTypeQuake3BP; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; + } + else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { + detectedFormat = eBrushTypeValve220; + globalWarningStream() << "detectedFormat = eBrushTypeValve220\n"; + } + else if ( string_equal( primitive, "(" ) ) { + detectedFormat = eBrushTypeQuake; + globalWarningStream() << "detectedFormat = eBrushTypeQuake\n"; + } + else{ + globalErrorStream() << "Format is not detected\n"; + Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); + return g_nullNode; + } + m_formatDetected = true; + if( detectedFormat != GlobalBrushCreator().getFormat() ){ + GlobalBrushCreator().toggleFormat( detectedFormat ); + } + } + + switch ( GlobalBrushCreator().getFormat() ) + { + case eBrushTypeQuake: + case eBrushTypeValve220: + tokeniser.ungetToken(); // ( + // fall through + case eBrushTypeQuake3BP: + return GlobalBrushCreator().createBrush(); + default: + break; + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#quake-primitive" ); + return g_nullNode; + } + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + m_formatDetected = false; + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + Map_Write( root, traverse, writer, true ); + writer.release(); + } }; typedef SingletonModule MapQ1Module; @@ -388,39 +388,39 @@ MapQ1Module g_MapQ1Module; class MapHalfLifeAPI final : public TypeSystemRef, public MapFormat, public PrimitiveParser { public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "maphl" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "maphl" ); -MapHalfLifeAPI(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "half-life maps", "*.map" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "half-life region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} - -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if ( string_equal( primitive, "(" ) ) { - tokeniser.ungetToken(); // ( - return GlobalBrushCreator().createBrush(); - } + MapHalfLifeAPI(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "half-life maps", "*.map" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "half-life region", "*.reg" ) ); + } + MapFormat* getTable(){ + return this; } - Tokeniser_unexpectedError( tokeniser, primitive, "#halflife-primitive" ); - return g_nullNode; -} -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - Map_Write( root, traverse, writer, true ); - writer.release(); -} + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if ( string_equal( primitive, "(" ) ) { + tokeniser.ungetToken(); // ( + return GlobalBrushCreator().createBrush(); + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#halflife-primitive" ); + return g_nullNode; + } + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + Map_Write( root, traverse, writer, true ); + writer.release(); + } }; typedef SingletonModule MapHalfLifeModule; @@ -430,73 +430,73 @@ MapHalfLifeModule g_MapHalfLifeModule; class MapQ2API final : public TypeSystemRef, public MapFormat, public PrimitiveParser { -mutable bool m_formatDetected; + mutable bool m_formatDetected; public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapq2" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapq2" ); -MapQ2API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake2 maps", "*.map" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake2 region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} -scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { - const char* primitive = tokeniser.getToken(); - if ( primitive != 0 ) { - if( !m_formatDetected ){ - EBrushType detectedFormat; - if ( string_equal( primitive, "brushDef" ) ) { - detectedFormat = eBrushTypeQuake3BP; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; - } - else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { - detectedFormat = eBrushTypeQuake3Valve220; - globalWarningStream() << "detectedFormat = eBrushTypeQuake3Valve220\n"; - } - else if ( string_equal( primitive, "(" ) ) { - detectedFormat = eBrushTypeQuake2; - globalWarningStream() << "detectedFormat = eBrushTypeQuake2\n"; - } - else{ - globalErrorStream() << "Format is not detected\n"; - Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); - return g_nullNode; - } - m_formatDetected = true; - if( detectedFormat != GlobalBrushCreator().getFormat() ){ - GlobalBrushCreator().toggleFormat( detectedFormat ); - } - } - - switch ( GlobalBrushCreator().getFormat() ) - { - case eBrushTypeQuake2: - case eBrushTypeQuake3Valve220: - tokeniser.ungetToken(); // ( - // fall through - case eBrushTypeQuake3BP: - return GlobalBrushCreator().createBrush(); - default: - break; - } + MapQ2API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake2 maps", "*.map" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "quake2 region", "*.reg" ) ); } + MapFormat* getTable(){ + return this; + } + scene::Node& parsePrimitive( Tokeniser& tokeniser ) const { + const char* primitive = tokeniser.getToken(); + if ( primitive != 0 ) { + if( !m_formatDetected ){ + EBrushType detectedFormat; + if ( string_equal( primitive, "brushDef" ) ) { + detectedFormat = eBrushTypeQuake3BP; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3BP\n"; + } + else if ( string_equal( primitive, "(" ) && tokeniser.bufferContains( " [ " ) && tokeniser.bufferContains( " ] " ) ) { + detectedFormat = eBrushTypeQuake3Valve220; + globalWarningStream() << "detectedFormat = eBrushTypeQuake3Valve220\n"; + } + else if ( string_equal( primitive, "(" ) ) { + detectedFormat = eBrushTypeQuake2; + globalWarningStream() << "detectedFormat = eBrushTypeQuake2\n"; + } + else{ + globalErrorStream() << "Format is not detected\n"; + Tokeniser_unexpectedError( tokeniser, primitive, "#different-brush-format" ); + return g_nullNode; + } + m_formatDetected = true; + if( detectedFormat != GlobalBrushCreator().getFormat() ){ + GlobalBrushCreator().toggleFormat( detectedFormat ); + } + } - Tokeniser_unexpectedError( tokeniser, primitive, "#quake2-primitive" ); - return g_nullNode; -} -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - m_formatDetected = false; - Map_Read( root, tokeniser, entityTable, *this ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); - Map_Write( root, traverse, writer, true ); - writer.release(); -} + switch ( GlobalBrushCreator().getFormat() ) + { + case eBrushTypeQuake2: + case eBrushTypeQuake3Valve220: + tokeniser.ungetToken(); // ( + // fall through + case eBrushTypeQuake3BP: + return GlobalBrushCreator().createBrush(); + default: + break; + } + } + + Tokeniser_unexpectedError( tokeniser, primitive, "#quake2-primitive" ); + return g_nullNode; + } + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + m_formatDetected = false; + Map_Read( root, tokeniser, entityTable, *this ); + tokeniser.release(); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream ); + Map_Write( root, traverse, writer, true ); + writer.release(); + } }; typedef SingletonModule MapQ2Module; @@ -520,22 +520,22 @@ typedef ArrayConstRange VMFBlockArrayRange; class VMFBlock { public: -const char* m_name; -VMFBlockArrayRange m_children; -typedef const VMFBlock Value; + const char* m_name; + VMFBlockArrayRange m_children; + typedef const VMFBlock Value; -VMFBlock( const char* name, VMFBlockArrayRange children = VMFBlockArrayRange( 0, 0 ) ) : m_name( name ), m_children( children ){ -} -const char* name() const { - return m_name; -} -typedef Value* const_iterator; -const_iterator begin() const { - return m_children.first; -} -const_iterator end() const { - return m_children.last; -} + VMFBlock( const char* name, VMFBlockArrayRange children = VMFBlockArrayRange( 0, 0 ) ) : m_name( name ), m_children( children ){ + } + const char* name() const { + return m_name; + } + typedef Value* const_iterator; + const_iterator begin() const { + return m_children.first; + } + const_iterator end() const { + return m_children.last; + } }; const VMFBlock c_vmfNormals( "normals" ); @@ -573,9 +573,9 @@ const VMFBlock c_vmfRoot( "", ARRAY_RANGE( c_vmfRootChildren ) ); class VMFInit { public: -VMFInit(){ - c_vmfVisGroup.m_children = VMFBlockArrayRange( &c_vmfVisGroup, &c_vmfVisGroup + 1 ); -} + VMFInit(){ + c_vmfVisGroup.m_children = VMFBlockArrayRange( &c_vmfVisGroup, &c_vmfVisGroup + 1 ); + } }; VMFInit g_VMFInit; @@ -635,24 +635,24 @@ void VMF_Read( scene::Node& root, Tokeniser& tokeniser, EntityCreator& entityTab class MapVMFAPI final : public TypeSystemRef, public MapFormat { public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "mapvmf" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "mapvmf" ); -MapVMFAPI(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "vmf maps", "*.vmf" ) ); - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "vmf region", "*.reg" ) ); -} -MapFormat* getTable(){ - return this; -} + MapVMFAPI(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "vmf maps", "*.vmf" ) ); + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "vmf region", "*.reg" ) ); + } + MapFormat* getTable(){ + return this; + } -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); - VMF_Read( root, tokeniser, entityTable ); - tokeniser.release(); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { -} + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Tokeniser& tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream ); + VMF_Read( root, tokeniser, entityTable ); + tokeniser.release(); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + } }; typedef SingletonModule MapVMFModule; diff --git a/plugins/mapq3/write.cpp b/plugins/mapq3/write.cpp index 6c427160..cab6417d 100644 --- a/plugins/mapq3/write.cpp +++ b/plugins/mapq3/write.cpp @@ -39,17 +39,17 @@ void Entity_ExportTokens( const Entity& entity, TokenWriter& writer ){ class WriteKeyValue : public Entity::Visitor { - TokenWriter& m_writer; -public: - WriteKeyValue( TokenWriter& writer ) - : m_writer( writer ){ - } + TokenWriter& m_writer; + public: + WriteKeyValue( TokenWriter& writer ) + : m_writer( writer ){ + } - void visit( const char* key, const char* value ){ - m_writer.writeString( key ); - m_writer.writeString( value ); - m_writer.nextLine(); - } + void visit( const char* key, const char* value ){ + m_writer.writeString( key ); + m_writer.writeString( value ); + m_writer.nextLine(); + } } visitor( writer ); @@ -58,57 +58,57 @@ public: class WriteTokensWalker : public scene::Traversable::Walker { -mutable Stack m_stack; -TokenWriter& m_writer; -bool m_ignorePatches; + mutable Stack m_stack; + TokenWriter& m_writer; + bool m_ignorePatches; public: -WriteTokensWalker( TokenWriter& writer, bool ignorePatches ) - : m_writer( writer ), m_ignorePatches( ignorePatches ){ -} -bool pre( scene::Node& node ) const { - m_stack.push( false ); - - Entity* entity = Node_getEntity( node ); - if ( entity != 0 ) { - if( entity->isContainer() && Node_getTraversable( node )->empty() && !string_equal( entity->getKeyValue( "classname" ), "worldspawn" ) - && string_empty( entity->getKeyValue( "origin" ) ) ){ - globalErrorStream() << "discarding empty group entity: # = " << g_count_entities << "; classname = " << entity->getKeyValue( "classname" ) << "\n"; - return false; - } - m_writer.writeToken( "//" ); - m_writer.writeToken( "entity" ); - m_writer.writeUnsigned( g_count_entities++ ); - m_writer.nextLine(); - - m_writer.writeToken( "{" ); - m_writer.nextLine(); - m_stack.top() = true; - - Entity_ExportTokens( *entity, m_writer ); + WriteTokensWalker( TokenWriter& writer, bool ignorePatches ) + : m_writer( writer ), m_ignorePatches( ignorePatches ){ } - else - { - MapExporter* exporter = Node_getMapExporter( node ); - if ( exporter != 0 - && !( m_ignorePatches && Node_isPatch( node ) ) ) { + bool pre( scene::Node& node ) const { + m_stack.push( false ); + + Entity* entity = Node_getEntity( node ); + if ( entity != 0 ) { + if( entity->isContainer() && Node_getTraversable( node )->empty() && !string_equal( entity->getKeyValue( "classname" ), "worldspawn" ) + && string_empty( entity->getKeyValue( "origin" ) ) ){ + globalErrorStream() << "discarding empty group entity: # = " << g_count_entities << "; classname = " << entity->getKeyValue( "classname" ) << "\n"; + return false; + } m_writer.writeToken( "//" ); - m_writer.writeToken( "brush" ); - m_writer.writeUnsigned( g_count_brushes++ ); + m_writer.writeToken( "entity" ); + m_writer.writeUnsigned( g_count_entities++ ); m_writer.nextLine(); - exporter->exportTokens( m_writer ); - } - } + m_writer.writeToken( "{" ); + m_writer.nextLine(); + m_stack.top() = true; - return true; -} -void post( scene::Node& node ) const { - if ( m_stack.top() ) { - m_writer.writeToken( "}" ); - m_writer.nextLine(); + Entity_ExportTokens( *entity, m_writer ); + } + else + { + MapExporter* exporter = Node_getMapExporter( node ); + if ( exporter != 0 + && !( m_ignorePatches && Node_isPatch( node ) ) ) { + m_writer.writeToken( "//" ); + m_writer.writeToken( "brush" ); + m_writer.writeUnsigned( g_count_brushes++ ); + m_writer.nextLine(); + + exporter->exportTokens( m_writer ); + } + } + + return true; + } + void post( scene::Node& node ) const { + if ( m_stack.top() ) { + m_writer.writeToken( "}" ); + m_writer.nextLine(); + } + m_stack.pop(); } - m_stack.pop(); -} }; void Map_Write( scene::Node& root, GraphTraversalFunc traverse, TokenWriter& writer, bool ignorePatches ){ diff --git a/plugins/mapxml/plugin.cpp b/plugins/mapxml/plugin.cpp index 179236d6..3bba36d0 100644 --- a/plugins/mapxml/plugin.cpp +++ b/plugins/mapxml/plugin.cpp @@ -41,45 +41,45 @@ class MapXMLDependencies : public GlobalEntityClassManagerModuleRef, public GlobalSceneGraphModuleRef { -PatchModuleRef m_patchDef2Doom3Module; -PatchModuleRef m_patchDoom3Module; + PatchModuleRef m_patchDef2Doom3Module; + PatchModuleRef m_patchDoom3Module; public: -MapXMLDependencies() : - GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), - m_patchDef2Doom3Module( "def2doom3" ), - m_patchDoom3Module( "doom3" ){ -} -BrushCreator& getBrushDoom3(){ - return GlobalBrushModule::getTable(); -} -PatchCreator& getPatchDoom3(){ - return *m_patchDoom3Module.getTable(); -} -PatchCreator& getPatchDef2Doom3(){ - return *m_patchDef2Doom3Module.getTable(); -} + MapXMLDependencies() : + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), + m_patchDef2Doom3Module( "def2doom3" ), + m_patchDoom3Module( "doom3" ){ + } + BrushCreator& getBrushDoom3(){ + return GlobalBrushModule::getTable(); + } + PatchCreator& getPatchDoom3(){ + return *m_patchDoom3Module.getTable(); + } + PatchCreator& getPatchDef2Doom3(){ + return *m_patchDef2Doom3Module.getTable(); + } }; class MapXMLAPI final : public TypeSystemRef, public MapFormat { public: -typedef MapFormat Type; -STRING_CONSTANT( Name, "xmldoom3" ); + typedef MapFormat Type; + STRING_CONSTANT( Name, "xmldoom3" ); -MapXMLAPI(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "xml doom3 maps", "*.xmap" ) ); -} -MapFormat* getTable(){ - return this; -} + MapXMLAPI(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "xml doom3 maps", "*.xmap" ) ); + } + MapFormat* getTable(){ + return this; + } -void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { - Map_Read( root, inputStream, entityTable ); -} -void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { - Map_Write( root, traverse, outputStream ); -} + void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const { + Map_Read( root, inputStream, entityTable ); + } + void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const { + Map_Write( root, traverse, outputStream ); + } }; typedef SingletonModule MapXMLModule; diff --git a/plugins/mapxml/xmlparse.cpp b/plugins/mapxml/xmlparse.cpp index 044adb66..7c667969 100644 --- a/plugins/mapxml/xmlparse.cpp +++ b/plugins/mapxml/xmlparse.cpp @@ -63,172 +63,172 @@ scene::Node& createPrimitive( const char* name ){ class TreeXMLImporter : public XMLImporter { public: -virtual TreeXMLImporter& child() = 0; + virtual TreeXMLImporter& child() = 0; }; class SubPrimitiveImporter : public TreeXMLImporter { -XMLImporter* m_importer; + XMLImporter* m_importer; public: -SubPrimitiveImporter( XMLImporter* importer ) : m_importer( importer ){ -} -void pushElement( const XMLElement& element ){ - m_importer->pushElement( element ); -} -void popElement( const char* name ){ - m_importer->popElement( name ); -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_importer->write( buffer, length ); -} -SubPrimitiveImporter& child(){ - return *this; -} + SubPrimitiveImporter( XMLImporter* importer ) : m_importer( importer ){ + } + void pushElement( const XMLElement& element ){ + m_importer->pushElement( element ); + } + void popElement( const char* name ){ + m_importer->popElement( name ); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_importer->write( buffer, length ); + } + SubPrimitiveImporter& child(){ + return *this; + } }; class PrimitiveImporter : public TreeXMLImporter { -scene::Node& m_parent; -XMLImporter* m_importer; -char m_child[sizeof( SubPrimitiveImporter )]; + scene::Node& m_parent; + XMLImporter* m_importer; + char m_child[sizeof( SubPrimitiveImporter )]; -SubPrimitiveImporter& subprimitive(){ - return *reinterpret_cast( m_child ); -} + SubPrimitiveImporter& subprimitive(){ + return *reinterpret_cast( m_child ); + } public: -PrimitiveImporter( scene::Node& parent ) : m_parent( parent ), m_importer( 0 ){ -} -void pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), "epair" ) ) { - ASSERT_MESSAGE( string_equal( element.name(), "epair" ), PARSE_ERROR ); - Node_getEntity( m_parent )->setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); + PrimitiveImporter( scene::Node& parent ) : m_parent( parent ), m_importer( 0 ){ } - else - { - NodeSmartReference node( createPrimitive( element.name() ) ); + void pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), "epair" ) ) { + ASSERT_MESSAGE( string_equal( element.name(), "epair" ), PARSE_ERROR ); + Node_getEntity( m_parent )->setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); + } + else + { + NodeSmartReference node( createPrimitive( element.name() ) ); - m_importer = Node_getXMLImporter( node ); + m_importer = Node_getXMLImporter( node ); - constructor( subprimitive(), m_importer ); + constructor( subprimitive(), m_importer ); - m_importer->pushElement( element ); + m_importer->pushElement( element ); - Node_getTraversable( m_parent )->insert( node ); + Node_getTraversable( m_parent )->insert( node ); + } } -} -void popElement( const char* name ){ - if ( string_equal( name, "epair" ) ) { - } - else - { - m_importer->popElement( name ); + void popElement( const char* name ){ + if ( string_equal( name, "epair" ) ) { + } + else + { + m_importer->popElement( name ); - destructor( subprimitive() ); - m_importer = 0; + destructor( subprimitive() ); + m_importer = 0; + } + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_importer->write( buffer, length ); + } + TreeXMLImporter& child(){ + return subprimitive(); } -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_importer->write( buffer, length ); -} -TreeXMLImporter& child(){ - return subprimitive(); -} }; class EntityImporter : public TreeXMLImporter { -scene::Node& m_parent; -char m_node[sizeof( NodeSmartReference )]; -char m_child[sizeof( PrimitiveImporter )]; -EntityCreator& m_entityTable; + scene::Node& m_parent; + char m_node[sizeof( NodeSmartReference )]; + char m_child[sizeof( PrimitiveImporter )]; + EntityCreator& m_entityTable; -NodeSmartReference& node(){ - return *reinterpret_cast( m_node ); -} -PrimitiveImporter& primitive(){ - return *reinterpret_cast( m_child ); -} + NodeSmartReference& node(){ + return *reinterpret_cast( m_node ); + } + PrimitiveImporter& primitive(){ + return *reinterpret_cast( m_child ); + } public: -EntityImporter( scene::Node& parent, EntityCreator& entityTable ) : m_parent( parent ), m_entityTable( entityTable ){ -} -void pushElement( const XMLElement& element ){ - ASSERT_MESSAGE( string_equal( element.name(), "entity" ), PARSE_ERROR ); - constructor( node(), NodeSmartReference( m_entityTable.createEntity( GlobalEntityClassManager().findOrInsert( "", true ) ) ) ); - constructor( primitive(), makeReference( node().get() ) ); -} -void popElement( const char* name ){ - ASSERT_MESSAGE( string_equal( name, "entity" ), PARSE_ERROR ); - NodeSmartReference entity( m_entityTable.createEntity( GlobalEntityClassManager().findOrInsert( Node_getEntity( node() )->getKeyValue( "classname" ), node_is_group( node() ) ) ) ); - - { - EntityCopyingVisitor visitor( *Node_getEntity( entity ) ); - Node_getEntity( node() )->forEachKeyValue( visitor ); + EntityImporter( scene::Node& parent, EntityCreator& entityTable ) : m_parent( parent ), m_entityTable( entityTable ){ } - - if ( Node_getTraversable( entity ) != 0 && !Node_getEntity( entity )->getEntityClass().fixedsize ) { - parentBrushes( node(), entity ); + void pushElement( const XMLElement& element ){ + ASSERT_MESSAGE( string_equal( element.name(), "entity" ), PARSE_ERROR ); + constructor( node(), NodeSmartReference( m_entityTable.createEntity( GlobalEntityClassManager().findOrInsert( "", true ) ) ) ); + constructor( primitive(), makeReference( node().get() ) ); } + void popElement( const char* name ){ + ASSERT_MESSAGE( string_equal( name, "entity" ), PARSE_ERROR ); + NodeSmartReference entity( m_entityTable.createEntity( GlobalEntityClassManager().findOrInsert( Node_getEntity( node() )->getKeyValue( "classname" ), node_is_group( node() ) ) ) ); - Node_getTraversable( m_parent )->insert( entity ); + { + EntityCopyingVisitor visitor( *Node_getEntity( entity ) ); + Node_getEntity( node() )->forEachKeyValue( visitor ); + } - destructor( primitive() ); - destructor( node() ); -} -std::size_t write( const char* buffer, std::size_t length ){ - return length; -} -TreeXMLImporter& child(){ - return primitive(); -} + if ( Node_getTraversable( entity ) != 0 && !Node_getEntity( entity )->getEntityClass().fixedsize ) { + parentBrushes( node(), entity ); + } + + Node_getTraversable( m_parent )->insert( entity ); + + destructor( primitive() ); + destructor( node() ); + } + std::size_t write( const char* buffer, std::size_t length ){ + return length; + } + TreeXMLImporter& child(){ + return primitive(); + } }; class MapDoom3Importer : public TreeXMLImporter { -scene::Node& m_root; -char m_child[sizeof( EntityImporter )]; -EntityCreator& m_entityTable; + scene::Node& m_root; + char m_child[sizeof( EntityImporter )]; + EntityCreator& m_entityTable; -EntityImporter& getEntity(){ - return *reinterpret_cast( m_child ); -} + EntityImporter& getEntity(){ + return *reinterpret_cast( m_child ); + } public: -MapDoom3Importer( scene::Node& root, EntityCreator& entityTable ) : m_root( root ), m_entityTable( entityTable ){ -} -void pushElement( const XMLElement& element ){ - ASSERT_MESSAGE( string_equal( element.name(), "mapdoom3" ), PARSE_ERROR ); - constructor( getEntity(), makeReference( m_root ), makeReference( m_entityTable ) ); -} -void popElement( const char* name ){ - ASSERT_MESSAGE( string_equal( name, "mapdoom3" ), PARSE_ERROR ); - destructor( getEntity() ); -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} -TreeXMLImporter& child(){ - return getEntity(); -} + MapDoom3Importer( scene::Node& root, EntityCreator& entityTable ) : m_root( root ), m_entityTable( entityTable ){ + } + void pushElement( const XMLElement& element ){ + ASSERT_MESSAGE( string_equal( element.name(), "mapdoom3" ), PARSE_ERROR ); + constructor( getEntity(), makeReference( m_root ), makeReference( m_entityTable ) ); + } + void popElement( const char* name ){ + ASSERT_MESSAGE( string_equal( name, "mapdoom3" ), PARSE_ERROR ); + destructor( getEntity() ); + } + std::size_t write( const char* data, std::size_t length ){ + return length; + } + TreeXMLImporter& child(){ + return getEntity(); + } }; class TreeXMLImporterStack : public XMLImporter { -std::vector< Reference > m_importers; + std::vector< Reference > m_importers; public: -TreeXMLImporterStack( TreeXMLImporter& importer ){ - m_importers.push_back( makeReference( importer ) ); -} -void pushElement( const XMLElement& element ){ - m_importers.back().get().pushElement( element ); - m_importers.push_back( makeReference( m_importers.back().get().child() ) ); -} -void popElement( const char* name ){ - m_importers.pop_back(); - m_importers.back().get().popElement( name ); -} -std::size_t write( const char* buffer, std::size_t length ){ - return ( *( m_importers.end() - 2 ) ).get().write( buffer, length ); -} + TreeXMLImporterStack( TreeXMLImporter& importer ){ + m_importers.push_back( makeReference( importer ) ); + } + void pushElement( const XMLElement& element ){ + m_importers.back().get().pushElement( element ); + m_importers.push_back( makeReference( m_importers.back().get().child() ) ); + } + void popElement( const char* name ){ + m_importers.pop_back(); + m_importers.back().get().popElement( name ); + } + std::size_t write( const char* buffer, std::size_t length ){ + return ( *( m_importers.end() - 2 ) ).get().write( buffer, length ); + } }; diff --git a/plugins/mapxml/xmlwrite.cpp b/plugins/mapxml/xmlwrite.cpp index 590e6431..77fcb2d4 100644 --- a/plugins/mapxml/xmlwrite.cpp +++ b/plugins/mapxml/xmlwrite.cpp @@ -36,36 +36,36 @@ inline XMLExporter* Node_getXMLExporter( scene::Node& node ){ class write_all : public scene::Traversable::Walker { -XMLImporter& m_importer; + XMLImporter& m_importer; public: -write_all( XMLImporter& importer ) : m_importer( importer ){ -} -bool pre( scene::Node& node ) const { - Entity* entity = Node_getEntity( node ); - if ( entity != 0 ) { - m_importer.write( "\n", 1 ); - StaticElement element( "entity" ); - m_importer.pushElement( element ); - entity_export exporter( *entity ); - exporter.exportXML( m_importer ); + write_all( XMLImporter& importer ) : m_importer( importer ){ } - else - { - XMLExporter* exporter = Node_getXMLExporter( node ); - if ( exporter != 0 ) { + bool pre( scene::Node& node ) const { + Entity* entity = Node_getEntity( node ); + if ( entity != 0 ) { m_importer.write( "\n", 1 ); - exporter->exportXML( m_importer ); + StaticElement element( "entity" ); + m_importer.pushElement( element ); + entity_export exporter( *entity ); + exporter.exportXML( m_importer ); + } + else + { + XMLExporter* exporter = Node_getXMLExporter( node ); + if ( exporter != 0 ) { + m_importer.write( "\n", 1 ); + exporter->exportXML( m_importer ); + m_importer.write( "\n", 1 ); + } + } + return true; + } + void post( scene::Node& node ) const { + if ( Node_getEntity( node ) != 0 ) { m_importer.write( "\n", 1 ); + m_importer.popElement( "entity" ); } } - return true; -} -void post( scene::Node& node ) const { - if ( Node_getEntity( node ) != 0 ) { - m_importer.write( "\n", 1 ); - m_importer.popElement( "entity" ); - } -} }; void Map_Write( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& out ){ diff --git a/plugins/md3model/md2.cpp b/plugins/md3model/md2.cpp index 1a138bc5..9e008ee7 100644 --- a/plugins/md3model/md2.cpp +++ b/plugins/md3model/md2.cpp @@ -170,21 +170,21 @@ void istream_read_md2Header( PointerInputStream& inputStream, md2Header_t& heade ArbitraryMeshVertex MD2Vertex_construct( const md2Header_t* pHeader, const md2Frame_t* pFrame, const md2XyzNormal_t* xyz, const md2St_t* st ){ return ArbitraryMeshVertex( - Vertex3f( - xyz->v[0] * pFrame->scale[0] + pFrame->translate[0], - xyz->v[1] * pFrame->scale[1] + pFrame->translate[1], - xyz->v[2] * pFrame->scale[2] + pFrame->translate[2] - ), - Normal3f( - g_mdl_normals[xyz->lightnormalindex][0], - g_mdl_normals[xyz->lightnormalindex][1], - g_mdl_normals[xyz->lightnormalindex][2] - ), - TexCoord2f( - (float)st->s / pHeader->skinwidth, - (float)st->t / pHeader->skinheight - ) - ); + Vertex3f( + xyz->v[0] * pFrame->scale[0] + pFrame->translate[0], + xyz->v[1] * pFrame->scale[1] + pFrame->translate[1], + xyz->v[2] * pFrame->scale[2] + pFrame->translate[2] + ), + Normal3f( + g_mdl_normals[xyz->lightnormalindex][0], + g_mdl_normals[xyz->lightnormalindex][1], + g_mdl_normals[xyz->lightnormalindex][2] + ), + TexCoord2f( + (float)st->s / pHeader->skinwidth, + (float)st->t / pHeader->skinheight + ) + ); } void MD2Surface_read( Model& model, const byte* buffer, ArchiveFile& file ){ diff --git a/plugins/md3model/md2.h b/plugins/md3model/md2.h index 33b34d76..9c93edc9 100644 --- a/plugins/md3model/md2.h +++ b/plugins/md3model/md2.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MD2_H ) #define INCLUDED_MD2_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; scene::Node& loadMD2Model( ArchiveFile& file ); diff --git a/plugins/md3model/md3.cpp b/plugins/md3model/md3.cpp index 99434212..3249dc4b 100644 --- a/plugins/md3model/md3.cpp +++ b/plugins/md3model/md3.cpp @@ -240,12 +240,12 @@ int MD3Surface_read( Surface& surface, unsigned char* buffer ){ istream_read_md3St( stStream, md3St ); surface.vertices().push_back( - ArbitraryMeshVertex( - Vertex3f( md3Xyz.xyz[0] * MD3_XYZ_SCALE, md3Xyz.xyz[1] * MD3_XYZ_SCALE, md3Xyz.xyz[2] * MD3_XYZ_SCALE ), - DecodeNormal( reinterpret_cast( &md3Xyz.normal ) ), - TexCoord2f( md3St.st[0], md3St.st[1] ) - ) - ); + ArbitraryMeshVertex( + Vertex3f( md3Xyz.xyz[0] * MD3_XYZ_SCALE, md3Xyz.xyz[1] * MD3_XYZ_SCALE, md3Xyz.xyz[2] * MD3_XYZ_SCALE ), + DecodeNormal( reinterpret_cast( &md3Xyz.normal ) ), + TexCoord2f( md3St.st[0], md3St.st[1] ) + ) + ); } } diff --git a/plugins/md3model/md3.h b/plugins/md3model/md3.h index 6b1e3e31..235d23b6 100644 --- a/plugins/md3model/md3.h +++ b/plugins/md3model/md3.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MD3_H ) #define INCLUDED_MD3_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; scene::Node& loadMD3Model( ArchiveFile& file ); diff --git a/plugins/md3model/md3normals.h b/plugins/md3model/md3normals.h index 3803c370..10c7d28b 100644 --- a/plugins/md3model/md3normals.h +++ b/plugins/md3model/md3normals.h @@ -32,10 +32,10 @@ inline Normal3f DecodeNormal( const byte bytes[2] ){ double lng = bytes[1] * ( c_pi / 128.0 ); return Normal3f( - static_cast( cos( lat ) * sin( lng ) ), - static_cast( sin( lat ) * sin( lng ) ), - static_cast( cos( lng ) ) - ); + static_cast( cos( lat ) * sin( lng ) ), + static_cast( sin( lat ) * sin( lng ) ), + static_cast( cos( lng ) ) + ); } #endif diff --git a/plugins/md3model/md5.cpp b/plugins/md3model/md5.cpp index 6da4b720..61e06ddc 100644 --- a/plugins/md3model/md5.cpp +++ b/plugins/md3model/md5.cpp @@ -80,9 +80,9 @@ inline Element float_squared( const Element& f ){ class MD5Joint { public: -int parent; -Vector3 position; -Vector4 rotation; + int parent; + Vector3 position; + Vector4 rotation; }; typedef Array MD5Joints; @@ -90,11 +90,11 @@ typedef Array MD5Joints; class MD5Vert { public: -std::size_t index; -float u; -float v; -std::size_t weight_index; -std::size_t weight_count; + std::size_t index; + float u; + float v; + std::size_t weight_index; + std::size_t weight_count; }; typedef Array MD5Verts; @@ -102,10 +102,10 @@ typedef Array MD5Verts; class MD5Tri { public: -std::size_t index; -std::size_t a; -std::size_t b; -std::size_t c; + std::size_t index; + std::size_t a; + std::size_t b; + std::size_t c; }; typedef Array MD5Tris; @@ -113,10 +113,10 @@ typedef Array MD5Tris; class MD5Weight { public: -std::size_t index; -std::size_t joint; -float t; -Vector3 v; + std::size_t index; + std::size_t joint; + float t; + Vector3 v; }; typedef Array MD5Weights; @@ -127,7 +127,7 @@ typedef Array MD5Components; class MD5Frame { public: -MD5Components m_components; + MD5Components m_components; }; typedef Array MD5Weights; @@ -399,11 +399,11 @@ bool MD5Model_parse( Model& model, Tokeniser& tokeniser ){ ArbitraryMeshVertex& b = surface.vertices()[*( j + 1 )]; ArbitraryMeshVertex& c = surface.vertices()[*( j + 2 )]; Vector3 weightedNormal( - vector3_cross( - reinterpret_cast( c.vertex ) - reinterpret_cast( a.vertex ), - reinterpret_cast( b.vertex ) - reinterpret_cast( a.vertex ) - ) - ); + vector3_cross( + reinterpret_cast( c.vertex ) - reinterpret_cast( a.vertex ), + reinterpret_cast( b.vertex ) - reinterpret_cast( a.vertex ) + ) + ); reinterpret_cast( a.normal ) += weightedNormal; reinterpret_cast( b.normal ) += weightedNormal; reinterpret_cast( c.normal ) += weightedNormal; diff --git a/plugins/md3model/md5.h b/plugins/md3model/md5.h index bcddd0d7..5d40e168 100644 --- a/plugins/md3model/md5.h +++ b/plugins/md3model/md5.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MD5_H ) #define INCLUDED_MD5_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; scene::Node& loadMD5Model( ArchiveFile& file ); diff --git a/plugins/md3model/mdc.cpp b/plugins/md3model/mdc.cpp index 2f394839..8434d5c9 100644 --- a/plugins/md3model/mdc.cpp +++ b/plugins/md3model/mdc.cpp @@ -196,12 +196,12 @@ unsigned int MDCSurface_read( Surface& surface, const byte* buffer ){ istream_read_mdcSt( stStream, mdcSt ); surface.vertices().push_back( - ArbitraryMeshVertex( - Vertex3f( mdcXyzNormal.xyz[0] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[1] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[2] * MDC_XYZ_SCALE ), - DecodeNormal( reinterpret_cast( &mdcXyzNormal.normal ) ), - TexCoord2f( mdcSt.st[0], mdcSt.st[1] ) - ) - ); + ArbitraryMeshVertex( + Vertex3f( mdcXyzNormal.xyz[0] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[1] * MDC_XYZ_SCALE, mdcXyzNormal.xyz[2] * MDC_XYZ_SCALE ), + DecodeNormal( reinterpret_cast( &mdcXyzNormal.normal ) ), + TexCoord2f( mdcSt.st[0], mdcSt.st[1] ) + ) + ); } } diff --git a/plugins/md3model/mdc.h b/plugins/md3model/mdc.h index 1f88439b..2435842b 100644 --- a/plugins/md3model/mdc.h +++ b/plugins/md3model/mdc.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MDC_H ) #define INCLUDED_MDC_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; scene::Node& loadMDCModel( ArchiveFile& file ); diff --git a/plugins/md3model/mdl.cpp b/plugins/md3model/mdl.cpp index 19e0d248..9586155d 100644 --- a/plugins/md3model/mdl.cpp +++ b/plugins/md3model/mdl.cpp @@ -58,53 +58,53 @@ void istream_read_mdlHeader( PointerInputStream& inputStream, mdlHeader_t& heade inline ArbitraryMeshVertex MDLVertex_construct( const mdlHeader_t& header, const mdlXyzNormal_t& xyz, const mdlSt_t& st, bool facesfront ){ return ArbitraryMeshVertex( - Vertex3f( - xyz.v[0] * header.scale[0] + header.scale_origin[0], - xyz.v[1] * header.scale[1] + header.scale_origin[1], - xyz.v[2] * header.scale[2] + header.scale_origin[2] - ), - Normal3f( - g_mdl_normals[xyz.lightnormalindex][0], - g_mdl_normals[xyz.lightnormalindex][1], - g_mdl_normals[xyz.lightnormalindex][2] - ), - TexCoord2f( - ( (float)st.s / header.skinwidth ) + ( ( st.onseam == MDL_ONSEAM && !facesfront ) ? 0.5f : 0.0f ), - (float)st.t / header.skinheight - ) - ); + Vertex3f( + xyz.v[0] * header.scale[0] + header.scale_origin[0], + xyz.v[1] * header.scale[1] + header.scale_origin[1], + xyz.v[2] * header.scale[2] + header.scale_origin[2] + ), + Normal3f( + g_mdl_normals[xyz.lightnormalindex][0], + g_mdl_normals[xyz.lightnormalindex][1], + g_mdl_normals[xyz.lightnormalindex][2] + ), + TexCoord2f( + ( (float)st.s / header.skinwidth ) + ( ( st.onseam == MDL_ONSEAM && !facesfront ) ? 0.5f : 0.0f ), + (float)st.t / header.skinheight + ) + ); } class mdlVertex_t { public: -inline mdlVertex_t( int vertindex, int facesfront ) - : m_vertindex( vertindex ), m_facesfront( facesfront ) -{} -inline bool operator<( const mdlVertex_t& other ) const { - if ( m_facesfront < other.m_facesfront ) { - return true; - } - if ( other.m_facesfront < m_facesfront ) { + inline mdlVertex_t( int vertindex, int facesfront ) + : m_vertindex( vertindex ), m_facesfront( facesfront ) + {} + inline bool operator<( const mdlVertex_t& other ) const { + if ( m_facesfront < other.m_facesfront ) { + return true; + } + if ( other.m_facesfront < m_facesfront ) { + return false; + } + + if ( m_vertindex < other.m_vertindex ) { + return true; + } + if ( other.m_vertindex < m_vertindex ) { + return false; + } + return false; } - - if ( m_vertindex < other.m_vertindex ) { - return true; - } - if ( other.m_vertindex < m_vertindex ) { - return false; + inline bool operator==( const mdlVertex_t& other ) const { + return m_vertindex == other.m_vertindex + && m_facesfront == other.m_facesfront; } - return false; -} -inline bool operator==( const mdlVertex_t& other ) const { - return m_vertindex == other.m_vertindex - && m_facesfront == other.m_facesfront; -} - -int m_vertindex; -int m_facesfront; + int m_vertindex; + int m_facesfront; }; typedef const mdlTriangle_t* mdlTriangleIterator; diff --git a/plugins/md3model/mdl.h b/plugins/md3model/mdl.h index dd893b71..d10e518f 100644 --- a/plugins/md3model/mdl.h +++ b/plugins/md3model/mdl.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MDL_H ) #define INCLUDED_MDL_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; scene::Node& loadMDLModel( ArchiveFile& file ); diff --git a/plugins/md3model/model.h b/plugins/md3model/model.h index b9a0cad4..69841190 100644 --- a/plugins/md3model/model.h +++ b/plugins/md3model/model.h @@ -40,25 +40,25 @@ class VectorLightList : public LightList { -typedef std::vector Lights; -Lights m_lights; + typedef std::vector Lights; + Lights m_lights; public: -void addLight( const RendererLight& light ){ - m_lights.push_back( &light ); -} -void clear(){ - m_lights.clear(); -} -void evaluateLights() const { -} -void lightsChanged() const { -} -void forEachLight( const RendererLightCallback& callback ) const { - for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) - { - callback( *( *i ) ); + void addLight( const RendererLight& light ){ + m_lights.push_back( &light ); + } + void clear(){ + m_lights.clear(); + } + void evaluateLights() const { + } + void lightsChanged() const { + } + void forEachLight( const RendererLightCallback& callback ) const { + for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) + { + callback( *( *i ) ); + } } -} }; inline VertexPointer vertexpointer_arbitrarymeshvertex( const ArbitraryMeshVertex* array ){ @@ -74,153 +74,153 @@ class Surface final : public OpenGLRenderable { public: -typedef VertexBuffer vertices_t; -typedef IndexBuffer indices_t; + typedef VertexBuffer vertices_t; + typedef IndexBuffer indices_t; private: -AABB m_aabb_local; -CopiedString m_shader; -Shader* m_state; + AABB m_aabb_local; + CopiedString m_shader; + Shader* m_state; -vertices_t m_vertices; -indices_t m_indices; + vertices_t m_vertices; + indices_t m_indices; -void CaptureShader(){ - m_state = GlobalShaderCache().capture( m_shader.c_str() ); -} -void ReleaseShader(){ - GlobalShaderCache().release( m_shader.c_str() ); -} + void CaptureShader(){ + m_state = GlobalShaderCache().capture( m_shader.c_str() ); + } + void ReleaseShader(){ + GlobalShaderCache().release( m_shader.c_str() ); + } public: -Surface() - : m_shader( "" ), m_state( 0 ){ - CaptureShader(); -} -~Surface(){ - ReleaseShader(); -} - -vertices_t& vertices(){ - return m_vertices; -} -indices_t& indices(){ - return m_indices; -} - -void setShader( const char* name ){ - ReleaseShader(); - parseTextureName( m_shader, name ); - CaptureShader(); -} -const char* getShader() const { - return m_shader.c_str(); -} -Shader* getState() const { - return m_state; -} -void updateAABB(){ - m_aabb_local = AABB(); - for ( vertices_t::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - aabb_extend_by_point_safe( m_aabb_local, reinterpret_cast( ( *i ).vertex ) ); - - - - for ( Surface::indices_t::iterator i = m_indices.begin(); i != m_indices.end(); i += 3 ) - { - ArbitraryMeshVertex& a = m_vertices[*( i + 0 )]; - ArbitraryMeshVertex& b = m_vertices[*( i + 1 )]; - ArbitraryMeshVertex& c = m_vertices[*( i + 2 )]; - - ArbitraryMeshTriangle_sumTangents( a, b, c ); + Surface() + : m_shader( "" ), m_state( 0 ){ + CaptureShader(); + } + ~Surface(){ + ReleaseShader(); } - for ( Surface::vertices_t::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - vector3_normalise( reinterpret_cast( ( *i ).tangent ) ); - vector3_normalise( reinterpret_cast( ( *i ).bitangent ) ); + vertices_t& vertices(){ + return m_vertices; + } + indices_t& indices(){ + return m_indices; } -} -void render( RenderStateFlags state ) const { + void setShader( const char* name ){ + ReleaseShader(); + parseTextureName( m_shader, name ); + CaptureShader(); + } + const char* getShader() const { + return m_shader.c_str(); + } + Shader* getState() const { + return m_state; + } + void updateAABB(){ + m_aabb_local = AABB(); + for ( vertices_t::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + aabb_extend_by_point_safe( m_aabb_local, reinterpret_cast( ( *i ).vertex ) ); + + + + for ( Surface::indices_t::iterator i = m_indices.begin(); i != m_indices.end(); i += 3 ) + { + ArbitraryMeshVertex& a = m_vertices[*( i + 0 )]; + ArbitraryMeshVertex& b = m_vertices[*( i + 1 )]; + ArbitraryMeshVertex& c = m_vertices[*( i + 2 )]; + + ArbitraryMeshTriangle_sumTangents( a, b, c ); + } + + for ( Surface::vertices_t::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + vector3_normalise( reinterpret_cast( ( *i ).tangent ) ); + vector3_normalise( reinterpret_cast( ( *i ).bitangent ) ); + } + } + + void render( RenderStateFlags state ) const { #if 1 - if ( ( state & RENDER_BUMP ) != 0 ) { - if ( GlobalShaderCache().useShaderLanguage() ) { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); - glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + if ( ( state & RENDER_BUMP ) != 0 ) { + if ( GlobalShaderCache().useShaderLanguage() ) { + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); + glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); + glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + } + else + { + glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); + glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); + glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + } } else { - glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); - glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); } - } - else - { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - } - glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->vertex ); - glDrawElements( GL_TRIANGLES, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); + glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->vertex ); + glDrawElements( GL_TRIANGLES, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); #else - glBegin( GL_TRIANGLES ); - for ( unsigned int i = 0; i < m_indices.size(); ++i ) - { - glTexCoord2fv( &m_vertices[m_indices[i]].texcoord.s ); - glNormal3fv( &m_vertices[m_indices[i]].normal.x ); - glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); - } - glEnd(); + glBegin( GL_TRIANGLES ); + for ( unsigned int i = 0; i < m_indices.size(); ++i ) + { + glTexCoord2fv( &m_vertices[m_indices[i]].texcoord.s ); + glNormal3fv( &m_vertices[m_indices[i]].normal.x ); + glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); + } + glEnd(); #endif #if defined( _DEBUG ) && !defined( _DEBUG_QUICKER ) - glBegin( GL_LINES ); + glBegin( GL_LINES ); - for ( VertexBuffer::const_iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - Vector3 normal = vector3_added( vertex3f_to_vector3( ( *i ).vertex ), vector3_scaled( normal3f_to_vector3( ( *i ).normal ), 8 ) ); - glVertex3fv( vertex3f_to_array( ( *i ).vertex ) ); - glVertex3fv( vector3_to_array( normal ) ); - } - glEnd(); + for ( VertexBuffer::const_iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + Vector3 normal = vector3_added( vertex3f_to_vector3( ( *i ).vertex ), vector3_scaled( normal3f_to_vector3( ( *i ).normal ), 8 ) ); + glVertex3fv( vertex3f_to_array( ( *i ).vertex ) ); + glVertex3fv( vector3_to_array( normal ) ); + } + glEnd(); #endif -} - -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} - -const AABB& localAABB() const { - return m_aabb_local; -} - -void render( Renderer& renderer, const Matrix4& localToWorld, Shader* state ) const { - renderer.SetState( state, Renderer::eFullMaterials ); - renderer.addRenderable( *this, localToWorld ); -} - -void render( Renderer& renderer, const Matrix4& localToWorld ) const { - render( renderer, localToWorld, m_state ); -} - -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - test.BeginMesh( localToWorld, true ); - - SelectionIntersection best; - test.TestTriangles( - vertexpointer_arbitrarymeshvertex( m_vertices.data() ), - IndexPointer( m_indices.data(), IndexPointer::index_type( m_indices.size() ) ), - best - ); - if ( best.valid() ) { - selector.addIntersection( best ); } -} + + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } + + const AABB& localAABB() const { + return m_aabb_local; + } + + void render( Renderer& renderer, const Matrix4& localToWorld, Shader* state ) const { + renderer.SetState( state, Renderer::eFullMaterials ); + renderer.addRenderable( *this, localToWorld ); + } + + void render( Renderer& renderer, const Matrix4& localToWorld ) const { + render( renderer, localToWorld, m_state ); + } + + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + test.BeginMesh( localToWorld, true ); + + SelectionIntersection best; + test.TestTriangles( + vertexpointer_arbitrarymeshvertex( m_vertices.data() ), + IndexPointer( m_indices.data(), IndexPointer::index_type( m_indices.size() ) ), + best + ); + if ( best.valid() ) { + selector.addIntersection( best ); + } + } }; // generic model node @@ -228,60 +228,60 @@ class Model : public Cullable, public Bounded { -typedef std::vector surfaces_t; -surfaces_t m_surfaces; + typedef std::vector surfaces_t; + surfaces_t m_surfaces; -AABB m_aabb_local; + AABB m_aabb_local; public: -Callback m_lightsChanged; + Callback m_lightsChanged; -~Model(){ - for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - { - delete *i; - } -} - -typedef surfaces_t::const_iterator const_iterator; - -const_iterator begin() const { - return m_surfaces.begin(); -} -const_iterator end() const { - return m_surfaces.end(); -} -std::size_t size() const { - return m_surfaces.size(); -} - -Surface& newSurface(){ - m_surfaces.push_back( new Surface ); - return *m_surfaces.back(); -} -void updateAABB(){ - m_aabb_local = AABB(); - for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - { - aabb_extend_by_aabb_safe( m_aabb_local, ( *i )->localAABB() ); - } -} - -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} - -virtual const AABB& localAABB() const { - return m_aabb_local; -} - -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - { - if ( ( *i )->intersectVolume( test.getVolume(), localToWorld ) != c_volumeOutside ) { - ( *i )->testSelect( selector, test, localToWorld ); + ~Model(){ + for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + { + delete *i; + } + } + + typedef surfaces_t::const_iterator const_iterator; + + const_iterator begin() const { + return m_surfaces.begin(); + } + const_iterator end() const { + return m_surfaces.end(); + } + std::size_t size() const { + return m_surfaces.size(); + } + + Surface& newSurface(){ + m_surfaces.push_back( new Surface ); + return *m_surfaces.back(); + } + void updateAABB(){ + m_aabb_local = AABB(); + for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + { + aabb_extend_by_aabb_safe( m_aabb_local, ( *i )->localAABB() ); + } + } + + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } + + virtual const AABB& localAABB() const { + return m_aabb_local; + } + + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + { + if ( ( *i )->intersectVolume( test.getVolume(), localToWorld ) != c_volumeOutside ) { + ( *i )->testSelect( selector, test, localToWorld ); + } } } -} }; inline void Surface_addLight( const Surface& surface, VectorLightList& lights, const Matrix4& localToWorld, const RendererLight& light ){ @@ -297,233 +297,233 @@ class ModelInstance : public LightCullable, public SkinnedModel { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -Model& m_model; + Model& m_model; -const LightList* m_lightList; -typedef Array SurfaceLightLists; -SurfaceLightLists m_surfaceLightLists; + const LightList* m_lightList; + typedef Array SurfaceLightLists; + SurfaceLightLists m_surfaceLightLists; -class Remap -{ -public: -CopiedString first; -Shader* second; -Remap() : second( 0 ){ -} -}; -typedef Array SurfaceRemaps; -SurfaceRemaps m_skins; + class Remap + { + public: + CopiedString first; + Shader* second; + Remap() : second( 0 ){ + } + }; + typedef Array SurfaceRemaps; + SurfaceRemaps m_skins; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Bounded& get( NullType){ - return m_model; -} -Cullable& get( NullType){ - return m_model; -} + Bounded& get( NullType){ + return m_model; + } + Cullable& get( NullType){ + return m_model; + } -void lightsChanged(){ - m_lightList->lightsChanged(); -} -typedef MemberCaller LightsChangedCaller; + void lightsChanged(){ + m_lightList->lightsChanged(); + } + typedef MemberCaller LightsChangedCaller; -void constructRemaps(){ - ModelSkin* skin = NodeTypeCast::cast( path().parent() ); - if ( skin != 0 && skin->realised() ) { - SurfaceRemaps::iterator j = m_skins.begin(); - for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i, ++j ) - { - const char* remap = skin->getRemap( ( *i )->getShader() ); - if ( !string_empty( remap ) ) { - ( *j ).first = remap; - ( *j ).second = GlobalShaderCache().capture( remap ); - } - else + void constructRemaps(){ + ModelSkin* skin = NodeTypeCast::cast( path().parent() ); + if ( skin != 0 && skin->realised() ) { + SurfaceRemaps::iterator j = m_skins.begin(); + for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i, ++j ) { - ( *j ).second = 0; + const char* remap = skin->getRemap( ( *i )->getShader() ); + if ( !string_empty( remap ) ) { + ( *j ).first = remap; + ( *j ).second = GlobalShaderCache().capture( remap ); + } + else + { + ( *j ).second = 0; + } + } + SceneChangeNotify(); + } + } + void destroyRemaps(){ + for ( SurfaceRemaps::iterator i = m_skins.begin(); i != m_skins.end(); ++i ) + { + if ( ( *i ).second != 0 ) { + GlobalShaderCache().release( ( *i ).first.c_str() ); + ( *i ).second = 0; } } - SceneChangeNotify(); } -} -void destroyRemaps(){ - for ( SurfaceRemaps::iterator i = m_skins.begin(); i != m_skins.end(); ++i ) - { - if ( ( *i ).second != 0 ) { - GlobalShaderCache().release( ( *i ).first.c_str() ); - ( *i ).second = 0; + void skinChanged(){ + ASSERT_MESSAGE( m_skins.size() == m_model.size(), "ERROR" ); + destroyRemaps(); + constructRemaps(); + } + + ModelInstance( const scene::Path& path, scene::Instance* parent, Model& model ) : + Instance( path, parent, this, StaticTypeCasts::instance().get() ), + m_model( model ), + m_surfaceLightLists( m_model.size() ), + m_skins( m_model.size() ){ + m_lightList = &GlobalShaderCache().attach( *this ); + m_model.m_lightsChanged = LightsChangedCaller( *this ); + + Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); + + constructRemaps(); + } + ~ModelInstance(){ + destroyRemaps(); + + Instance::setTransformChangedCallback( Callback() ); + + m_model.m_lightsChanged = Callback(); + GlobalShaderCache().detach( *this ); + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + SurfaceLightLists::const_iterator j = m_surfaceLightLists.begin(); + SurfaceRemaps::const_iterator k = m_skins.begin(); + for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i, ++j, ++k ) + { + if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { + renderer.setLights( *j ); + ( *i )->render( renderer, localToWorld, ( *k ).second != 0 ? ( *k ).second : ( *i )->getState() ); + } } } -} -void skinChanged(){ - ASSERT_MESSAGE( m_skins.size() == m_model.size(), "ERROR" ); - destroyRemaps(); - constructRemaps(); -} -ModelInstance( const scene::Path& path, scene::Instance* parent, Model& model ) : - Instance( path, parent, this, StaticTypeCasts::instance().get() ), - m_model( model ), - m_surfaceLightLists( m_model.size() ), - m_skins( m_model.size() ){ - m_lightList = &GlobalShaderCache().attach( *this ); - m_model.m_lightsChanged = LightsChangedCaller( *this ); + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_lightList->evaluateLights(); - Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); + render( renderer, volume, Instance::localToWorld() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); + } - constructRemaps(); -} -~ModelInstance(){ - destroyRemaps(); + void testSelect( Selector& selector, SelectionTest& test ){ + m_model.testSelect( selector, test, Instance::localToWorld() ); + } - Instance::setTransformChangedCallback( Callback() ); - - m_model.m_lightsChanged = Callback(); - GlobalShaderCache().detach( *this ); -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - SurfaceLightLists::const_iterator j = m_surfaceLightLists.begin(); - SurfaceRemaps::const_iterator k = m_skins.begin(); - for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i, ++j, ++k ) - { - if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { - renderer.setLights( *j ); - ( *i )->render( renderer, localToWorld, ( *k ).second != 0 ? ( *k ).second : ( *i )->getState() ); + bool testLight( const RendererLight& light ) const { + return light.testAABB( worldAABB() ); + } + void insertLight( const RendererLight& light ){ + const Matrix4& localToWorld = Instance::localToWorld(); + SurfaceLightLists::iterator j = m_surfaceLightLists.begin(); + for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i ) + { + Surface_addLight( *( *i ), *j++, localToWorld, light ); } } -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_lightList->evaluateLights(); - - render( renderer, volume, Instance::localToWorld() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} - -void testSelect( Selector& selector, SelectionTest& test ){ - m_model.testSelect( selector, test, Instance::localToWorld() ); -} - -bool testLight( const RendererLight& light ) const { - return light.testAABB( worldAABB() ); -} -void insertLight( const RendererLight& light ){ - const Matrix4& localToWorld = Instance::localToWorld(); - SurfaceLightLists::iterator j = m_surfaceLightLists.begin(); - for ( Model::const_iterator i = m_model.begin(); i != m_model.end(); ++i ) - { - Surface_addLight( *( *i ), *j++, localToWorld, light ); + void clearLights(){ + for ( SurfaceLightLists::iterator i = m_surfaceLightLists.begin(); i != m_surfaceLightLists.end(); ++i ) + { + ( *i ).clear(); + } } -} -void clearLights(){ - for ( SurfaceLightLists::iterator i = m_surfaceLightLists.begin(); i != m_surfaceLightLists.end(); ++i ) - { - ( *i ).clear(); - } -} }; class ModelNode : public scene::Node::Symbiot, public scene::Instantiable { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -Model m_model; + scene::Node m_node; + InstanceSet m_instances; + Model m_model; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -ModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ -} + ModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ + } -Model& model(){ - return m_model; -} + Model& model(){ + return m_model; + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new ModelInstance( path, parent, m_model ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new ModelInstance( path, parent, m_model ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; inline void Surface_constructQuad( Surface& surface, const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d, const Vector3& normal ){ surface.vertices().push_back( - ArbitraryMeshVertex( - vertex3f_for_vector3( a ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_topleft ) - ) - ); + ArbitraryMeshVertex( + vertex3f_for_vector3( a ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_topleft ) + ) + ); surface.vertices().push_back( - ArbitraryMeshVertex( - vertex3f_for_vector3( b ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_topright ) - ) - ); + ArbitraryMeshVertex( + vertex3f_for_vector3( b ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_topright ) + ) + ); surface.vertices().push_back( - ArbitraryMeshVertex( - vertex3f_for_vector3( c ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_botright ) - ) - ); + ArbitraryMeshVertex( + vertex3f_for_vector3( c ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_botright ) + ) + ); surface.vertices().push_back( - ArbitraryMeshVertex( - vertex3f_for_vector3( d ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_botleft ) - ) - ); + ArbitraryMeshVertex( + vertex3f_for_vector3( d ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_botleft ) + ) + ); } inline void Model_constructNull( Model& model ){ diff --git a/plugins/md3model/plugin.cpp b/plugins/md3model/plugin.cpp index 95fb5477..ba74d5c9 100644 --- a/plugins/md3model/plugin.cpp +++ b/plugins/md3model/plugin.cpp @@ -46,9 +46,9 @@ class MD3ModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return loadMD3Model( file ); -} + scene::Node& loadModel( ArchiveFile& file ){ + return loadMD3Model( file ); + } }; class ModelDependencies : @@ -64,17 +64,17 @@ class ModelDependencies : class ModelMD3API : public TypeSystemRef { -MD3ModelLoader m_modelmd3; + MD3ModelLoader m_modelmd3; public: -typedef ModelLoader Type; -STRING_CONSTANT( Name, "md3" ); + typedef ModelLoader Type; + STRING_CONSTANT( Name, "md3" ); -ModelMD3API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md3 models", "*.md3" ) ); -} -ModelLoader* getTable(){ - return &m_modelmd3; -} + ModelMD3API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md3 models", "*.md3" ) ); + } + ModelLoader* getTable(){ + return &m_modelmd3; + } }; typedef SingletonModule ModelMD3Module; @@ -86,24 +86,24 @@ ModelMD3Module g_ModelMD3Module; class MD2ModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return loadMD2Model( file ); -} + scene::Node& loadModel( ArchiveFile& file ){ + return loadMD2Model( file ); + } }; class ModelMD2API : public TypeSystemRef { -MD2ModelLoader m_modelmd2; + MD2ModelLoader m_modelmd2; public: -typedef ModelLoader Type; -STRING_CONSTANT( Name, "md2" ); + typedef ModelLoader Type; + STRING_CONSTANT( Name, "md2" ); -ModelMD2API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md2 models", "*.md2" ) ); -} -ModelLoader* getTable(){ - return &m_modelmd2; -} + ModelMD2API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md2 models", "*.md2" ) ); + } + ModelLoader* getTable(){ + return &m_modelmd2; + } }; typedef SingletonModule ModelMD2Module; @@ -113,24 +113,24 @@ ModelMD2Module g_ModelMD2Module; class MDLModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return loadMDLModel( file ); -} + scene::Node& loadModel( ArchiveFile& file ){ + return loadMDLModel( file ); + } }; class ModelMDLAPI : public TypeSystemRef { -MDLModelLoader m_modelmdl; + MDLModelLoader m_modelmdl; public: -typedef ModelLoader Type; -STRING_CONSTANT( Name, "mdl" ); + typedef ModelLoader Type; + STRING_CONSTANT( Name, "mdl" ); -ModelMDLAPI(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "mdl models", "*.mdl" ) ); -} -ModelLoader* getTable(){ - return &m_modelmdl; -} + ModelMDLAPI(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "mdl models", "*.mdl" ) ); + } + ModelLoader* getTable(){ + return &m_modelmdl; + } }; typedef SingletonModule ModelMDLModule; @@ -140,24 +140,24 @@ ModelMDLModule g_ModelMDLModule; class MDCModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return loadMDCModel( file ); -} + scene::Node& loadModel( ArchiveFile& file ){ + return loadMDCModel( file ); + } }; class ModelMDCAPI : public TypeSystemRef { -MDCModelLoader m_modelmdc; + MDCModelLoader m_modelmdc; public: -typedef ModelLoader Type; -STRING_CONSTANT( Name, "mdc" ); + typedef ModelLoader Type; + STRING_CONSTANT( Name, "mdc" ); -ModelMDCAPI(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "mdc models", "*.mdc" ) ); -} -ModelLoader* getTable(){ - return &m_modelmdc; -} + ModelMDCAPI(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "mdc models", "*.mdc" ) ); + } + ModelLoader* getTable(){ + return &m_modelmdc; + } }; typedef SingletonModule ModelMDCModule; @@ -167,17 +167,17 @@ ModelMDCModule g_ModelMDCModule; class ImageMDLAPI { -_QERPlugImageTable m_imagemdl; + _QERPlugImageTable m_imagemdl; public: -typedef _QERPlugImageTable Type; -STRING_CONSTANT( Name, "mdl" ); + typedef _QERPlugImageTable Type; + STRING_CONSTANT( Name, "mdl" ); -ImageMDLAPI(){ - m_imagemdl.loadImage = &LoadMDLImage; -} -_QERPlugImageTable* getTable(){ - return &m_imagemdl; -} + ImageMDLAPI(){ + m_imagemdl.loadImage = &LoadMDLImage; + } + _QERPlugImageTable* getTable(){ + return &m_imagemdl; + } }; typedef SingletonModule ImageMDLModule; @@ -188,9 +188,9 @@ ImageMDLModule g_ImageMDLModule; class MD5ModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return loadMD5Model( file ); -} + scene::Node& loadModel( ArchiveFile& file ){ + return loadMD5Model( file ); + } }; class ModelMD5Dependencies : public ModelDependencies, public GlobalScripLibModuleRef @@ -199,17 +199,17 @@ class ModelMD5Dependencies : public ModelDependencies, public GlobalScripLibModu class ModelMD5API : public TypeSystemRef { -MD5ModelLoader m_modelmd5; + MD5ModelLoader m_modelmd5; public: -typedef ModelLoader Type; -STRING_CONSTANT( Name, "md5mesh" ); + typedef ModelLoader Type; + STRING_CONSTANT( Name, "md5mesh" ); -ModelMD5API(){ - GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md5 meshes", "*.md5mesh" ) ); -} -ModelLoader* getTable(){ - return &m_modelmd5; -} + ModelMD5API(){ + GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "md5 meshes", "*.md5mesh" ) ); + } + ModelLoader* getTable(){ + return &m_modelmd5; + } }; typedef SingletonModule ModelMD5Module; diff --git a/plugins/model/model.cpp b/plugins/model/model.cpp index 32e2c230..f884e27e 100644 --- a/plugins/model/model.cpp +++ b/plugins/model/model.cpp @@ -44,269 +44,269 @@ class VectorLightList : public LightList { -typedef std::vector Lights; -Lights m_lights; + typedef std::vector Lights; + Lights m_lights; public: -void addLight( const RendererLight& light ){ - m_lights.push_back( &light ); -} -void clear(){ - m_lights.clear(); -} -void evaluateLights() const { -} -void lightsChanged() const { -} -void forEachLight( const RendererLightCallback& callback ) const { - for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) - { - callback( *( *i ) ); + void addLight( const RendererLight& light ){ + m_lights.push_back( &light ); + } + void clear(){ + m_lights.clear(); + } + void evaluateLights() const { + } + void lightsChanged() const { + } + void forEachLight( const RendererLightCallback& callback ) const { + for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) + { + callback( *( *i ) ); + } } -} }; class PicoSurface final : public OpenGLRenderable { -AABB m_aabb_local; -CopiedString m_shader; -Shader* m_state; + AABB m_aabb_local; + CopiedString m_shader; + Shader* m_state; -Array m_vertices; -Array m_indices; + Array m_vertices; + Array m_indices; public: -PicoSurface(){ - constructNull(); - CaptureShader(); -} -PicoSurface( picoSurface_t* surface ){ - CopyPicoSurface( surface ); - CaptureShader(); -} -~PicoSurface(){ - ReleaseShader(); -} + PicoSurface(){ + constructNull(); + CaptureShader(); + } + PicoSurface( picoSurface_t* surface ){ + CopyPicoSurface( surface ); + CaptureShader(); + } + ~PicoSurface(){ + ReleaseShader(); + } -void render( RenderStateFlags state ) const { - if ( ( state & RENDER_BUMP ) != 0 ) { - if ( GlobalShaderCache().useShaderLanguage() ) { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); - glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + void render( RenderStateFlags state ) const { + if ( ( state & RENDER_BUMP ) != 0 ) { + if ( GlobalShaderCache().useShaderLanguage() ) { + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); + glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); + glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + } + else + { + glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); + glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); + glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + } } else { - glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->tangent ); - glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->bitangent ); + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); + glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); } - } - else - { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->normal ); - glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->texcoord ); - } - glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->vertex ); - glDrawElements( GL_TRIANGLES, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); + glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_vertices.data()->vertex ); + glDrawElements( GL_TRIANGLES, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); #if defined( _DEBUG ) && !defined( _DEBUG_QUICKER ) - GLfloat modelview[16]; - glGetFloatv( GL_MODELVIEW_MATRIX, modelview ); // I know this is slow as hell, but hey - we're in _DEBUG - Matrix4 modelview_inv( - modelview[0], modelview[1], modelview[2], modelview[3], - modelview[4], modelview[5], modelview[6], modelview[7], - modelview[8], modelview[9], modelview[10], modelview[11], - modelview[12], modelview[13], modelview[14], modelview[15] ); - matrix4_full_invert( modelview_inv ); - Matrix4 modelview_inv_transposed = matrix4_transposed( modelview_inv ); + GLfloat modelview[16]; + glGetFloatv( GL_MODELVIEW_MATRIX, modelview ); // I know this is slow as hell, but hey - we're in _DEBUG + Matrix4 modelview_inv( + modelview[0], modelview[1], modelview[2], modelview[3], + modelview[4], modelview[5], modelview[6], modelview[7], + modelview[8], modelview[9], modelview[10], modelview[11], + modelview[12], modelview[13], modelview[14], modelview[15] ); + matrix4_full_invert( modelview_inv ); + Matrix4 modelview_inv_transposed = matrix4_transposed( modelview_inv ); - glBegin( GL_LINES ); + glBegin( GL_LINES ); - for ( Array::const_iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - Vector3 normal = normal3f_to_vector3( ( *i ).normal ); - normal = matrix4_transformed_direction( modelview_inv, vector3_normalised( matrix4_transformed_direction( modelview_inv_transposed, normal ) ) ); // do some magic - Vector3 normalTransformed = vector3_added( vertex3f_to_vector3( ( *i ).vertex ), vector3_scaled( normal, 8 ) ); - glVertex3fv( vertex3f_to_array( ( *i ).vertex ) ); - glVertex3fv( vector3_to_array( normalTransformed ) ); - } - glEnd(); + for ( Array::const_iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + Vector3 normal = normal3f_to_vector3( ( *i ).normal ); + normal = matrix4_transformed_direction( modelview_inv, vector3_normalised( matrix4_transformed_direction( modelview_inv_transposed, normal ) ) ); // do some magic + Vector3 normalTransformed = vector3_added( vertex3f_to_vector3( ( *i ).vertex ), vector3_scaled( normal, 8 ) ); + glVertex3fv( vertex3f_to_array( ( *i ).vertex ) ); + glVertex3fv( vector3_to_array( normalTransformed ) ); + } + glEnd(); #endif -} - -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} - -const AABB& localAABB() const { - return m_aabb_local; -} - -void render( Renderer& renderer, const Matrix4& localToWorld, Shader* state ) const { - renderer.SetState( state, Renderer::eFullMaterials ); - renderer.addRenderable( *this, localToWorld ); -} - -void render( Renderer& renderer, const Matrix4& localToWorld ) const { - render( renderer, localToWorld, m_state ); -} - -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - test.BeginMesh( localToWorld, true ); - - SelectionIntersection best; - testSelect( test, best ); - if ( best.valid() ) { - selector.addIntersection( best ); } -} -const char* getShader() const { - return m_shader.c_str(); -} -Shader* getState() const { - return m_state; -} + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } + + const AABB& localAABB() const { + return m_aabb_local; + } + + void render( Renderer& renderer, const Matrix4& localToWorld, Shader* state ) const { + renderer.SetState( state, Renderer::eFullMaterials ); + renderer.addRenderable( *this, localToWorld ); + } + + void render( Renderer& renderer, const Matrix4& localToWorld ) const { + render( renderer, localToWorld, m_state ); + } + + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + test.BeginMesh( localToWorld, true ); + + SelectionIntersection best; + testSelect( test, best ); + if ( best.valid() ) { + selector.addIntersection( best ); + } + } + + const char* getShader() const { + return m_shader.c_str(); + } + Shader* getState() const { + return m_state; + } private: -void CaptureShader(){ - m_state = GlobalShaderCache().capture( m_shader.c_str() ); -} -void ReleaseShader(){ - GlobalShaderCache().release( m_shader.c_str() ); -} - -void UpdateAABB(){ - m_aabb_local = AABB(); - for ( std::size_t i = 0; i < m_vertices.size(); ++i ) - aabb_extend_by_point_safe( m_aabb_local, reinterpret_cast( m_vertices[i].vertex ) ); - - - for ( Array::iterator i = m_indices.begin(); i != m_indices.end(); i += 3 ) - { - ArbitraryMeshVertex& a = m_vertices[*( i + 0 )]; - ArbitraryMeshVertex& b = m_vertices[*( i + 1 )]; - ArbitraryMeshVertex& c = m_vertices[*( i + 2 )]; - - ArbitraryMeshTriangle_sumTangents( a, b, c ); + void CaptureShader(){ + m_state = GlobalShaderCache().capture( m_shader.c_str() ); + } + void ReleaseShader(){ + GlobalShaderCache().release( m_shader.c_str() ); } - for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - vector3_normalise( reinterpret_cast( ( *i ).tangent ) ); - vector3_normalise( reinterpret_cast( ( *i ).bitangent ) ); - } -} + void UpdateAABB(){ + m_aabb_local = AABB(); + for ( std::size_t i = 0; i < m_vertices.size(); ++i ) + aabb_extend_by_point_safe( m_aabb_local, reinterpret_cast( m_vertices[i].vertex ) ); -void testSelect( SelectionTest& test, SelectionIntersection& best ){ - test.TestTriangles( - VertexPointer( VertexPointer::pointer( &m_vertices.data()->vertex ), sizeof( ArbitraryMeshVertex ) ), - IndexPointer( m_indices.data(), IndexPointer::index_type( m_indices.size() ) ), - best + + for ( Array::iterator i = m_indices.begin(); i != m_indices.end(); i += 3 ) + { + ArbitraryMeshVertex& a = m_vertices[*( i + 0 )]; + ArbitraryMeshVertex& b = m_vertices[*( i + 1 )]; + ArbitraryMeshVertex& c = m_vertices[*( i + 2 )]; + + ArbitraryMeshTriangle_sumTangents( a, b, c ); + } + + for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + vector3_normalise( reinterpret_cast( ( *i ).tangent ) ); + vector3_normalise( reinterpret_cast( ( *i ).bitangent ) ); + } + } + + void testSelect( SelectionTest& test, SelectionIntersection& best ){ + test.TestTriangles( + VertexPointer( VertexPointer::pointer( &m_vertices.data()->vertex ), sizeof( ArbitraryMeshVertex ) ), + IndexPointer( m_indices.data(), IndexPointer::index_type( m_indices.size() ) ), + best ); -} - -void CopyPicoSurface( picoSurface_t* surface ){ - picoShader_t* shader = PicoGetSurfaceShader( surface ); - if ( shader == 0 ) { - m_shader = ""; - } - else{ - m_shader = PicoGetShaderName( shader ); } - m_vertices.resize( PicoGetSurfaceNumVertexes( surface ) ); - m_indices.resize( PicoGetSurfaceNumIndexes( surface ) ); + void CopyPicoSurface( picoSurface_t* surface ){ + picoShader_t* shader = PicoGetSurfaceShader( surface ); + if ( shader == 0 ) { + m_shader = ""; + } + else{ + m_shader = PicoGetShaderName( shader ); + } - for ( std::size_t i = 0; i < m_vertices.size(); ++i ) - { - picoVec_t* xyz = PicoGetSurfaceXYZ( surface, int(i) ); - m_vertices[i].vertex = vertex3f_from_array( xyz ); + m_vertices.resize( PicoGetSurfaceNumVertexes( surface ) ); + m_indices.resize( PicoGetSurfaceNumIndexes( surface ) ); - picoVec_t* normal = PicoGetSurfaceNormal( surface, int(i) ); - m_vertices[i].normal = normal3f_from_array( normal ); + for ( std::size_t i = 0; i < m_vertices.size(); ++i ) + { + picoVec_t* xyz = PicoGetSurfaceXYZ( surface, int(i) ); + m_vertices[i].vertex = vertex3f_from_array( xyz ); - picoVec_t* st = PicoGetSurfaceST( surface, 0, int(i) ); - m_vertices[i].texcoord = TexCoord2f( st[0], st[1] ); + picoVec_t* normal = PicoGetSurfaceNormal( surface, int(i) ); + m_vertices[i].normal = normal3f_from_array( normal ); + + picoVec_t* st = PicoGetSurfaceST( surface, 0, int(i) ); + m_vertices[i].texcoord = TexCoord2f( st[0], st[1] ); #if 0 - picoVec_t* color = PicoGetSurfaceColor( surface, 0, int(i) ); - m_vertices[i].colour = Colour4b( color[0], color[1], color[2], color[3] ); + picoVec_t* color = PicoGetSurfaceColor( surface, 0, int(i) ); + m_vertices[i].colour = Colour4b( color[0], color[1], color[2], color[3] ); #endif + } + + picoIndex_t* indexes = PicoGetSurfaceIndexes( surface, 0 ); + for ( std::size_t j = 0; j < m_indices.size(); ++j ) + m_indices[ j ] = indexes[ j ]; + + UpdateAABB(); } - picoIndex_t* indexes = PicoGetSurfaceIndexes( surface, 0 ); - for ( std::size_t j = 0; j < m_indices.size(); ++j ) - m_indices[ j ] = indexes[ j ]; - - UpdateAABB(); -} - -void constructQuad( std::size_t index, const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d, const Vector3& normal ){ - m_vertices[index * 4 + 0] = ArbitraryMeshVertex( - vertex3f_for_vector3( a ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_topleft ) - ); - m_vertices[index * 4 + 1] = ArbitraryMeshVertex( - vertex3f_for_vector3( b ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_topright ) - ); - m_vertices[index * 4 + 2] = ArbitraryMeshVertex( - vertex3f_for_vector3( c ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_botright ) - ); - m_vertices[index * 4 + 3] = ArbitraryMeshVertex( - vertex3f_for_vector3( d ), - normal3f_for_vector3( normal ), - texcoord2f_from_array( aabb_texcoord_botleft ) - ); -} - -void constructNull(){ - AABB aabb( Vector3( 0, 0, 0 ), Vector3( 8, 8, 8 ) ); - - Vector3 points[8]; - aabb_corners( aabb, points ); - - m_vertices.resize( 24 ); - - constructQuad( 0, points[2], points[1], points[5], points[6], aabb_normals[0] ); - constructQuad( 1, points[1], points[0], points[4], points[5], aabb_normals[1] ); - constructQuad( 2, points[0], points[1], points[2], points[3], aabb_normals[2] ); - constructQuad( 3, points[0], points[3], points[7], points[4], aabb_normals[3] ); - constructQuad( 4, points[3], points[2], points[6], points[7], aabb_normals[4] ); - constructQuad( 5, points[7], points[6], points[5], points[4], aabb_normals[5] ); - - m_indices.resize( 36 ); - - RenderIndex indices[36] = { - 0, 1, 2, 0, 2, 3, - 4, 5, 6, 4, 6, 7, - 8, 9, 10, 8, 10, 11, - 12, 13, 14, 12, 14, 15, - 16, 17, 18, 16, 18, 19, - 20, 21, 22, 10, 22, 23, - }; - - - Array::iterator j = m_indices.begin(); - for ( RenderIndex* i = indices; i != indices + ( sizeof( indices ) / sizeof( RenderIndex ) ); ++i ) - { - *j++ = *i; + void constructQuad( std::size_t index, const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d, const Vector3& normal ){ + m_vertices[index * 4 + 0] = ArbitraryMeshVertex( + vertex3f_for_vector3( a ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_topleft ) + ); + m_vertices[index * 4 + 1] = ArbitraryMeshVertex( + vertex3f_for_vector3( b ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_topright ) + ); + m_vertices[index * 4 + 2] = ArbitraryMeshVertex( + vertex3f_for_vector3( c ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_botright ) + ); + m_vertices[index * 4 + 3] = ArbitraryMeshVertex( + vertex3f_for_vector3( d ), + normal3f_for_vector3( normal ), + texcoord2f_from_array( aabb_texcoord_botleft ) + ); } - m_shader = ""; + void constructNull(){ + AABB aabb( Vector3( 0, 0, 0 ), Vector3( 8, 8, 8 ) ); - UpdateAABB(); -} + Vector3 points[8]; + aabb_corners( aabb, points ); + + m_vertices.resize( 24 ); + + constructQuad( 0, points[2], points[1], points[5], points[6], aabb_normals[0] ); + constructQuad( 1, points[1], points[0], points[4], points[5], aabb_normals[1] ); + constructQuad( 2, points[0], points[1], points[2], points[3], aabb_normals[2] ); + constructQuad( 3, points[0], points[3], points[7], points[4], aabb_normals[3] ); + constructQuad( 4, points[3], points[2], points[6], points[7], aabb_normals[4] ); + constructQuad( 5, points[7], points[6], points[5], points[4], aabb_normals[5] ); + + m_indices.resize( 36 ); + + RenderIndex indices[36] = { + 0, 1, 2, 0, 2, 3, + 4, 5, 6, 4, 6, 7, + 8, 9, 10, 8, 10, 11, + 12, 13, 14, 12, 14, 15, + 16, 17, 18, 16, 18, 19, + 20, 21, 22, 10, 22, 23, + }; + + + Array::iterator j = m_indices.begin(); + for ( RenderIndex* i = indices; i != indices + ( sizeof( indices ) / sizeof( RenderIndex ) ); ++i ) + { + *j++ = *i; + } + + m_shader = ""; + + UpdateAABB(); + } }; @@ -317,95 +317,95 @@ class PicoModel : public Cullable, public Bounded { -typedef std::vector surfaces_t; -surfaces_t m_surfaces; + typedef std::vector surfaces_t; + surfaces_t m_surfaces; -AABB m_aabb_local; + AABB m_aabb_local; public: -Callback m_lightsChanged; + Callback m_lightsChanged; -PicoModel(){ - constructNull(); -} -PicoModel( picoModel_t* model ){ - CopyPicoModel( model ); -} -~PicoModel(){ - for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - delete *i; -} + PicoModel(){ + constructNull(); + } + PicoModel( picoModel_t* model ){ + CopyPicoModel( model ); + } + ~PicoModel(){ + for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + delete *i; + } -typedef surfaces_t::const_iterator const_iterator; + typedef surfaces_t::const_iterator const_iterator; -const_iterator begin() const { - return m_surfaces.begin(); -} -const_iterator end() const { - return m_surfaces.end(); -} -std::size_t size() const { - return m_surfaces.size(); -} + const_iterator begin() const { + return m_surfaces.begin(); + } + const_iterator end() const { + return m_surfaces.end(); + } + std::size_t size() const { + return m_surfaces.size(); + } -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } -virtual const AABB& localAABB() const { - return m_aabb_local; -} + virtual const AABB& localAABB() const { + return m_aabb_local; + } -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, std::vector states ) const { - for ( surfaces_t::const_iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - { - if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { - ( *i )->render( renderer, localToWorld, states[i - m_surfaces.begin()] ); + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld, std::vector states ) const { + for ( surfaces_t::const_iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + { + if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { + ( *i )->render( renderer, localToWorld, states[i - m_surfaces.begin()] ); + } } } -} -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) - { - if ( ( *i )->intersectVolume( test.getVolume(), localToWorld ) != c_volumeOutside ) { - ( *i )->testSelect( selector, test, localToWorld ); + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + for ( surfaces_t::iterator i = m_surfaces.begin(); i != m_surfaces.end(); ++i ) + { + if ( ( *i )->intersectVolume( test.getVolume(), localToWorld ) != c_volumeOutside ) { + ( *i )->testSelect( selector, test, localToWorld ); + } } } -} private: -void CopyPicoModel( picoModel_t* model ){ - m_aabb_local = AABB(); + void CopyPicoModel( picoModel_t* model ){ + m_aabb_local = AABB(); - /* each surface on the model will become a new map drawsurface */ - int numSurfaces = PicoGetModelNumSurfaces( model ); - //% SYs_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces ); - for ( int s = 0; s < numSurfaces; ++s ) - { - /* get surface */ - picoSurface_t* surface = PicoGetModelSurface( model, s ); - if ( surface == 0 ) { - continue; + /* each surface on the model will become a new map drawsurface */ + int numSurfaces = PicoGetModelNumSurfaces( model ); + //% SYs_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces ); + for ( int s = 0; s < numSurfaces; ++s ) + { + /* get surface */ + picoSurface_t* surface = PicoGetModelSurface( model, s ); + if ( surface == 0 ) { + continue; + } + + /* only handle triangle surfaces initially (fixme: support patches) */ + if ( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) { + continue; + } + + /* fix the surface's normals */ + PicoFixSurfaceNormals( surface ); + + PicoSurface* picosurface = new PicoSurface( surface ); + aabb_extend_by_aabb_safe( m_aabb_local, picosurface->localAABB() ); + m_surfaces.push_back( picosurface ); } - - /* only handle triangle surfaces initially (fixme: support patches) */ - if ( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) { - continue; - } - - /* fix the surface's normals */ - PicoFixSurfaceNormals( surface ); - - PicoSurface* picosurface = new PicoSurface( surface ); - aabb_extend_by_aabb_safe( m_aabb_local, picosurface->localAABB() ); + } + void constructNull(){ + PicoSurface* picosurface = new PicoSurface(); + m_aabb_local = picosurface->localAABB(); m_surfaces.push_back( picosurface ); } -} -void constructNull(){ - PicoSurface* picosurface = new PicoSurface(); - m_aabb_local = picosurface->localAABB(); - m_surfaces.push_back( picosurface ); -} }; inline void Surface_addLight( PicoSurface& surface, VectorLightList& lights, const Matrix4& localToWorld, const RendererLight& light ){ @@ -421,204 +421,204 @@ class PicoModelInstance : public LightCullable, public SkinnedModel { -class TypeCasts -{ -InstanceTypeCastTable m_casts; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + + PicoModel& m_picomodel; + + const LightList* m_lightList; + typedef Array SurfaceLightLists; + SurfaceLightLists m_surfaceLightLists; + + class Remap + { + public: + CopiedString first; + Shader* second; + Remap() : second( 0 ){ + } + }; + typedef Array SurfaceRemaps; + SurfaceRemaps m_skins; + + PicoModelInstance( const PicoModelInstance& ); + PicoModelInstance operator=( const PicoModelInstance& ); public: -TypeCasts(){ - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + typedef LazyStatic StaticTypeCasts; -PicoModel& m_picomodel; + void* m_test; -const LightList* m_lightList; -typedef Array SurfaceLightLists; -SurfaceLightLists m_surfaceLightLists; + Bounded& get( NullType){ + return m_picomodel; + } + Cullable& get( NullType){ + return m_picomodel; + } -class Remap -{ -public: -CopiedString first; -Shader* second; -Remap() : second( 0 ){ -} -}; -typedef Array SurfaceRemaps; -SurfaceRemaps m_skins; + void lightsChanged(){ + m_lightList->lightsChanged(); + } + typedef MemberCaller LightsChangedCaller; -PicoModelInstance( const PicoModelInstance& ); -PicoModelInstance operator=( const PicoModelInstance& ); -public: -typedef LazyStatic StaticTypeCasts; - -void* m_test; - -Bounded& get( NullType){ - return m_picomodel; -} -Cullable& get( NullType){ - return m_picomodel; -} - -void lightsChanged(){ - m_lightList->lightsChanged(); -} -typedef MemberCaller LightsChangedCaller; - -void constructRemaps(){ - ASSERT_MESSAGE( m_skins.size() == m_picomodel.size(), "ERROR" ); - ModelSkin* skin = NodeTypeCast::cast( path().parent() ); - if ( skin != 0 && skin->realised() ) { - SurfaceRemaps::iterator j = m_skins.begin(); - for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i, ++j ) - { - const char* remap = skin->getRemap( ( *i )->getShader() ); - if ( !string_empty( remap ) ) { - ( *j ).first = remap; - ( *j ).second = GlobalShaderCache().capture( remap ); - } - else + void constructRemaps(){ + ASSERT_MESSAGE( m_skins.size() == m_picomodel.size(), "ERROR" ); + ModelSkin* skin = NodeTypeCast::cast( path().parent() ); + if ( skin != 0 && skin->realised() ) { + SurfaceRemaps::iterator j = m_skins.begin(); + for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i, ++j ) { - ( *j ).second = 0; + const char* remap = skin->getRemap( ( *i )->getShader() ); + if ( !string_empty( remap ) ) { + ( *j ).first = remap; + ( *j ).second = GlobalShaderCache().capture( remap ); + } + else + { + ( *j ).second = 0; + } + } + SceneChangeNotify(); + } + } + void destroyRemaps(){ + ASSERT_MESSAGE( m_skins.size() == m_picomodel.size(), "ERROR" ); + for ( SurfaceRemaps::iterator i = m_skins.begin(); i != m_skins.end(); ++i ) + { + if ( ( *i ).second != 0 ) { + GlobalShaderCache().release( ( *i ).first.c_str() ); + ( *i ).second = 0; } } - SceneChangeNotify(); } -} -void destroyRemaps(){ - ASSERT_MESSAGE( m_skins.size() == m_picomodel.size(), "ERROR" ); - for ( SurfaceRemaps::iterator i = m_skins.begin(); i != m_skins.end(); ++i ) - { - if ( ( *i ).second != 0 ) { - GlobalShaderCache().release( ( *i ).first.c_str() ); - ( *i ).second = 0; + void skinChanged(){ + destroyRemaps(); + constructRemaps(); + } + + PicoModelInstance( const scene::Path& path, scene::Instance* parent, PicoModel& picomodel ) : + Instance( path, parent, this, StaticTypeCasts::instance().get() ), + m_picomodel( picomodel ), + m_surfaceLightLists( m_picomodel.size() ), + m_skins( m_picomodel.size() ){ + m_lightList = &GlobalShaderCache().attach( *this ); + m_picomodel.m_lightsChanged = LightsChangedCaller( *this ); + + Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); + + constructRemaps(); + } + ~PicoModelInstance(){ + destroyRemaps(); + + Instance::setTransformChangedCallback( Callback() ); + + m_picomodel.m_lightsChanged = Callback(); + GlobalShaderCache().detach( *this ); + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + SurfaceLightLists::const_iterator j = m_surfaceLightLists.begin(); + SurfaceRemaps::const_iterator k = m_skins.begin(); + for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i, ++j, ++k ) + { + if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { + renderer.setLights( *j ); + ( *i )->render( renderer, localToWorld, ( *k ).second != 0 ? ( *k ).second : ( *i )->getState() ); + } } } -} -void skinChanged(){ - destroyRemaps(); - constructRemaps(); -} -PicoModelInstance( const scene::Path& path, scene::Instance* parent, PicoModel& picomodel ) : - Instance( path, parent, this, StaticTypeCasts::instance().get() ), - m_picomodel( picomodel ), - m_surfaceLightLists( m_picomodel.size() ), - m_skins( m_picomodel.size() ){ - m_lightList = &GlobalShaderCache().attach( *this ); - m_picomodel.m_lightsChanged = LightsChangedCaller( *this ); + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_lightList->evaluateLights(); - Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); + render( renderer, volume, Instance::localToWorld() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); + } - constructRemaps(); -} -~PicoModelInstance(){ - destroyRemaps(); + void testSelect( Selector& selector, SelectionTest& test ){ + m_picomodel.testSelect( selector, test, Instance::localToWorld() ); + } - Instance::setTransformChangedCallback( Callback() ); - - m_picomodel.m_lightsChanged = Callback(); - GlobalShaderCache().detach( *this ); -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - SurfaceLightLists::const_iterator j = m_surfaceLightLists.begin(); - SurfaceRemaps::const_iterator k = m_skins.begin(); - for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i, ++j, ++k ) - { - if ( ( *i )->intersectVolume( volume, localToWorld ) != c_volumeOutside ) { - renderer.setLights( *j ); - ( *i )->render( renderer, localToWorld, ( *k ).second != 0 ? ( *k ).second : ( *i )->getState() ); + bool testLight( const RendererLight& light ) const { + return light.testAABB( worldAABB() ); + } + void insertLight( const RendererLight& light ){ + const Matrix4& localToWorld = Instance::localToWorld(); + SurfaceLightLists::iterator j = m_surfaceLightLists.begin(); + for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i ) + { + Surface_addLight( *( *i ), *j++, localToWorld, light ); } } -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_lightList->evaluateLights(); - - render( renderer, volume, Instance::localToWorld() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} - -void testSelect( Selector& selector, SelectionTest& test ){ - m_picomodel.testSelect( selector, test, Instance::localToWorld() ); -} - -bool testLight( const RendererLight& light ) const { - return light.testAABB( worldAABB() ); -} -void insertLight( const RendererLight& light ){ - const Matrix4& localToWorld = Instance::localToWorld(); - SurfaceLightLists::iterator j = m_surfaceLightLists.begin(); - for ( PicoModel::const_iterator i = m_picomodel.begin(); i != m_picomodel.end(); ++i ) - { - Surface_addLight( *( *i ), *j++, localToWorld, light ); + void clearLights(){ + for ( SurfaceLightLists::iterator i = m_surfaceLightLists.begin(); i != m_surfaceLightLists.end(); ++i ) + { + ( *i ).clear(); + } } -} -void clearLights(){ - for ( SurfaceLightLists::iterator i = m_surfaceLightLists.begin(); i != m_surfaceLightLists.end(); ++i ) - { - ( *i ).clear(); - } -} }; class PicoModelNode : public scene::Node::Symbiot, public scene::Instantiable { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -PicoModel m_picomodel; + scene::Node m_node; + InstanceSet m_instances; + PicoModel m_picomodel; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -PicoModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ -} -PicoModelNode( picoModel_t* model ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_picomodel( model ){ -} + PicoModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ + } + PicoModelNode( picoModel_t* model ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_picomodel( model ){ + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new PicoModelInstance( path, parent, m_picomodel ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new PicoModelInstance( path, parent, m_picomodel ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; @@ -628,91 +628,91 @@ template class create_new { public: -static Type* construct( const Key& key ){ - return new Type( key ); -} -static void destroy( Type* value ){ - delete value; -} + static Type* construct( const Key& key ){ + return new Type( key ); + } + static void destroy( Type* value ){ + delete value; + } }; template > class cache_element : public creation_policy { public: -inline cache_element() : m_count( 0 ), m_value( 0 ) {} -inline ~cache_element(){ - ASSERT_MESSAGE( m_count == 0, "destroyed a reference before it was released\n" ); - if ( m_count > 0 ) { - destroy(); + inline cache_element() : m_count( 0 ), m_value( 0 ) {} + inline ~cache_element(){ + ASSERT_MESSAGE( m_count == 0, "destroyed a reference before it was released\n" ); + if ( m_count > 0 ) { + destroy(); + } } -} -inline Type* capture( const Key& key ){ - if ( ++m_count == 1 ) { - construct( key ); + inline Type* capture( const Key& key ){ + if ( ++m_count == 1 ) { + construct( key ); + } + return m_value; } - return m_value; -} -inline void release(){ - ASSERT_MESSAGE( !empty(), "failed to release reference - not found in cache\n" ); - if ( --m_count == 0 ) { - destroy(); + inline void release(){ + ASSERT_MESSAGE( !empty(), "failed to release reference - not found in cache\n" ); + if ( --m_count == 0 ) { + destroy(); + } + } + inline bool empty(){ + return m_count == 0; + } + inline void refresh( const Key& key ){ + m_value->refresh( key ); } -} -inline bool empty(){ - return m_count == 0; -} -inline void refresh( const Key& key ){ - m_value->refresh( key ); -} private: -inline void construct( const Key& key ){ - m_value = creation_policy::construct( key ); -} -inline void destroy(){ - creation_policy::destroy( m_value ); -} + inline void construct( const Key& key ){ + m_value = creation_policy::construct( key ); + } + inline void destroy(){ + creation_policy::destroy( m_value ); + } -std::size_t m_count; -Type* m_value; + std::size_t m_count; + Type* m_value; }; class create_picomodel { -typedef PicoModelKey key_type; -typedef PicoModel value_type; + typedef PicoModelKey key_type; + typedef PicoModel value_type; public: -static value_type* construct( const key_type& key ){ - picoModel_t* picomodel = PicoLoadModel( const_cast( key.first.c_str() ), key.second ); - value_type* value = new value_type( picomodel ); - PicoFreeModel( picomodel ); - return value; -} -static void destroy( value_type* value ){ - delete value; -} + static value_type* construct( const key_type& key ){ + picoModel_t* picomodel = PicoLoadModel( const_cast( key.first.c_str() ), key.second ); + value_type* value = new value_type( picomodel ); + PicoFreeModel( picomodel ); + return value; + } + static void destroy( value_type* value ){ + delete value; + } }; #include class ModelCache { -typedef PicoModel value_type; + typedef PicoModel value_type; public: -typedef PicoModelKey key_type; -typedef cache_element elem_type; -typedef std::map cache_type; + typedef PicoModelKey key_type; + typedef cache_element elem_type; + typedef std::map cache_type; -value_type* capture( const key_type& key ){ - return m_cache[key].capture( key ); -} -void release( const key_type& key ){ - m_cache[key].release(); -} + value_type* capture( const key_type& key ){ + return m_cache[key].capture( key ); + } + void release( const key_type& key ){ + m_cache[key].release(); + } private: -cache_type m_cache; + cache_type m_cache; }; ModelCache g_model_cache; @@ -730,197 +730,197 @@ class RemapWrapper : public Bounded { public: -RemapWrapper( const char* name ){ - parse_namestr( name ); + RemapWrapper( const char* name ){ + parse_namestr( name ); - m_model = g_model_cache.capture( ModelCache::key_type( m_name, m_frame ) ); + m_model = g_model_cache.capture( ModelCache::key_type( m_name, m_frame ) ); - construct_shaders(); -} -virtual ~RemapWrapper(){ - g_model_cache.release( ModelCache::key_type( m_name, m_frame ) ); + construct_shaders(); + } + virtual ~RemapWrapper(){ + g_model_cache.release( ModelCache::key_type( m_name, m_frame ) ); - for ( shaders_t::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) - { - GlobalShaderCache().release( ( *i ).c_str() ); + for ( shaders_t::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) + { + GlobalShaderCache().release( ( *i ).c_str() ); + } + + for ( remaps_t::iterator j = m_remaps.begin(); j != m_remaps.end(); ++j ) + { + delete ( *j ); + } } - for ( remaps_t::iterator j = m_remaps.begin(); j != m_remaps.end(); ++j ) - { - delete ( *j ); + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return m_model->intersectVolume( test, localToWorld ); } -} -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return m_model->intersectVolume( test, localToWorld ); -} + virtual const AABB& localAABB() const { + return m_model->localAABB(); + } -virtual const AABB& localAABB() const { - return m_model->localAABB(); -} + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + m_model->render( renderer, volume, localToWorld, m_states ); + } -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - m_model->render( renderer, volume, localToWorld, m_states ); -} - -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - m_model->testSelect( selector, test, localToWorld ); -} + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + m_model->testSelect( selector, test, localToWorld ); + } private: -void add_remap( const char *remap ){ - const char *ch; - remap_t *pRemap; + void add_remap( const char *remap ){ + const char *ch; + remap_t *pRemap; - ch = remap; + ch = remap; - while ( *ch && *ch != ';' ) - ch++; + while ( *ch && *ch != ';' ) + ch++; - if ( *ch == '\0' ) { - // bad remap - globalWarningStream() << "WARNING: Shader _remap key found in a model entity without a ; character\n"; - } - else { - pRemap = new remap_t; - - strncpy( pRemap->m_remapbuff, remap, sizeof( pRemap->m_remapbuff ) ); - - pRemap->m_remapbuff[ch - remap] = '\0'; - - pRemap->original = pRemap->m_remapbuff; - pRemap->remap = pRemap->m_remapbuff + ( ch - remap ) + 1; - - m_remaps.push_back( pRemap ); - } -} - -void parse_namestr( const char *name ){ - const char *ptr, *s; - bool hasName, hasFrame; - - hasName = hasFrame = false; - - m_frame = 0; - - for ( s = ptr = name; ; ++ptr ) - { - if ( !hasName && ( *ptr == ':' || *ptr == '\0' ) ) { - // model name - hasName = true; - m_name = CopiedString( s, ptr ); - s = ptr + 1; - } - else if ( *ptr == '?' || *ptr == '\0' ) { - // model frame - hasFrame = true; - m_frame = atoi( CopiedString( s, ptr ).c_str() ); - s = ptr + 1; - } - else if ( *ptr == '&' || *ptr == '\0' ) { - // a remap - add_remap( CopiedString( s, ptr ).c_str() ); - s = ptr + 1; + if ( *ch == '\0' ) { + // bad remap + globalWarningStream() << "WARNING: Shader _remap key found in a model entity without a ; character\n"; } + else { + pRemap = new remap_t; - if ( *ptr == '\0' ) { - break; + strncpy( pRemap->m_remapbuff, remap, sizeof( pRemap->m_remapbuff ) ); + + pRemap->m_remapbuff[ch - remap] = '\0'; + + pRemap->original = pRemap->m_remapbuff; + pRemap->remap = pRemap->m_remapbuff + ( ch - remap ) + 1; + + m_remaps.push_back( pRemap ); } } -} -void construct_shaders(){ - const char* global_shader = shader_for_remap( "*" ); + void parse_namestr( const char *name ){ + const char *ptr, *s; + bool hasName, hasFrame; - m_shaders.reserve( m_model->size() ); - m_states.reserve( m_model->size() ); - for ( PicoModel::iterator i = m_model->begin(); i != m_model->end(); ++i ) - { - const char* shader = shader_for_remap( ( *i )->getShader() ); - m_shaders.push_back( - ( shader[0] != '\0' ) - ? shader - : ( global_shader[0] != '\0' ) - ? global_shader - : ( *i )->getShader() ); - m_states.push_back( GlobalShaderCache().capture( m_shaders.back().c_str() ) ); - } -} + hasName = hasFrame = false; -inline const char* shader_for_remap( const char* remap ){ - for ( remaps_t::iterator i = m_remaps.begin(); i != m_remaps.end(); ++i ) - { - if ( shader_equal( remap, ( *i )->original ) ) { - return ( *i )->remap; + m_frame = 0; + + for ( s = ptr = name; ; ++ptr ) + { + if ( !hasName && ( *ptr == ':' || *ptr == '\0' ) ) { + // model name + hasName = true; + m_name = CopiedString( s, ptr ); + s = ptr + 1; + } + else if ( *ptr == '?' || *ptr == '\0' ) { + // model frame + hasFrame = true; + m_frame = atoi( CopiedString( s, ptr ).c_str() ); + s = ptr + 1; + } + else if ( *ptr == '&' || *ptr == '\0' ) { + // a remap + add_remap( CopiedString( s, ptr ).c_str() ); + s = ptr + 1; + } + + if ( *ptr == '\0' ) { + break; + } } } - return ""; -} -CopiedString m_name; -int m_frame; -PicoModel* m_model; + void construct_shaders(){ + const char* global_shader = shader_for_remap( "*" ); -typedef std::vector remaps_t; -remaps_t m_remaps; -typedef std::vector shaders_t; -shaders_t m_shaders; -typedef std::vector states_t; -states_t m_states; + m_shaders.reserve( m_model->size() ); + m_states.reserve( m_model->size() ); + for ( PicoModel::iterator i = m_model->begin(); i != m_model->end(); ++i ) + { + const char* shader = shader_for_remap( ( *i )->getShader() ); + m_shaders.push_back( + ( shader[0] != '\0' ) + ? shader + : ( global_shader[0] != '\0' ) + ? global_shader + : ( *i )->getShader() ); + m_states.push_back( GlobalShaderCache().capture( m_shaders.back().c_str() ) ); + } + } + + inline const char* shader_for_remap( const char* remap ){ + for ( remaps_t::iterator i = m_remaps.begin(); i != m_remaps.end(); ++i ) + { + if ( shader_equal( remap, ( *i )->original ) ) { + return ( *i )->remap; + } + } + return ""; + } + + CopiedString m_name; + int m_frame; + PicoModel* m_model; + + typedef std::vector remaps_t; + remaps_t m_remaps; + typedef std::vector shaders_t; + shaders_t m_shaders; + typedef std::vector states_t; + states_t m_states; }; class RemapWrapperInstance : public scene::Instance, public Renderable, public SelectionTestable { -RemapWrapper& m_remapwrapper; + RemapWrapper& m_remapwrapper; public: -RemapWrapperInstance( const scene::Path& path, scene::Instance* parent, RemapWrapper& remapwrapper ) : Instance( path, parent ), m_remapwrapper( remapwrapper ){ - scene::Instance::m_cullable = &m_remapwrapper; - scene::Instance::m_render = this; - scene::Instance::m_select = this; -} + RemapWrapperInstance( const scene::Path& path, scene::Instance* parent, RemapWrapper& remapwrapper ) : Instance( path, parent ), m_remapwrapper( remapwrapper ){ + scene::Instance::m_cullable = &m_remapwrapper; + scene::Instance::m_render = this; + scene::Instance::m_select = this; + } -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_remapwrapper.render( renderer, volume, Instance::localToWorld() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_remapwrapper.render( renderer, volume, Instance::localToWorld() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); + } -void testSelect( Selector& selector, SelectionTest& test ){ - m_remapwrapper.testSelect( selector, test, Instance::localToWorld() ); -} + void testSelect( Selector& selector, SelectionTest& test ){ + m_remapwrapper.testSelect( selector, test, Instance::localToWorld() ); + } }; class RemapWrapperNode : public scene::Node::Symbiot, public scene::Instantiable { -scene::Node m_node; -typedef RemapWrapperInstance instance_type; -InstanceSet m_instances; -RemapWrapper m_remapwrapper; + scene::Node m_node; + typedef RemapWrapperInstance instance_type; + InstanceSet m_instances; + RemapWrapper m_remapwrapper; public: -RemapWrapperNode( const char* name ) : m_node( this ), m_remapwrapper( name ){ - m_node.m_instance = this; -} + RemapWrapperNode( const char* name ) : m_node( this ), m_remapwrapper( name ){ + m_node.m_instance = this; + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new instance_type( path, parent, m_remapwrapper ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new instance_type( path, parent, m_remapwrapper ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; scene::Node& LoadRemapModel( const char* name ){ diff --git a/plugins/model/model.h b/plugins/model/model.h index 9961fb9f..e0b8192e 100644 --- a/plugins/model/model.h +++ b/plugins/model/model.h @@ -22,7 +22,9 @@ #if !defined( INCLUDED_MODEL_H ) #define INCLUDED_MODEL_H -namespace scene { class Node; } +namespace scene { +class Node; +} class ArchiveFile; typedef struct picoModule_s picoModule_t; scene::Node& loadPicoModel( const picoModule_t* module, ArchiveFile& file ); diff --git a/plugins/model/plugin.cpp b/plugins/model/plugin.cpp index 504428eb..d30935b1 100644 --- a/plugins/model/plugin.cpp +++ b/plugins/model/plugin.cpp @@ -94,13 +94,13 @@ void pico_initialise(){ class PicoModelLoader : public ModelLoader { -const picoModule_t* m_module; + const picoModule_t* m_module; public: -PicoModelLoader( const picoModule_t* module ) : m_module( module ){ -} -scene::Node& loadModel( ArchiveFile& file ){ - return loadPicoModel( m_module, file ); -} + PicoModelLoader( const picoModule_t* module ) : m_module( module ){ + } + scene::Node& loadModel( ArchiveFile& file ){ + return loadPicoModel( m_module, file ); + } }; class ModelPicoDependencies : @@ -116,38 +116,38 @@ class ModelPicoDependencies : class ModelPicoAPI : public TypeSystemRef { -PicoModelLoader m_modelLoader; + PicoModelLoader m_modelLoader; public: -typedef ModelLoader Type; + typedef ModelLoader Type; -ModelPicoAPI( const char* extension, const picoModule_t* module ) : - m_modelLoader( module ){ - StringOutputStream filter( 128 ); - filter << "*." << extension; - GlobalFiletypesModule::getTable().addType( Type::Name(), extension, filetype_t( module->displayName, filter.c_str() ) ); -} -ModelLoader* getTable(){ - return &m_modelLoader; -} + ModelPicoAPI( const char* extension, const picoModule_t* module ) : + m_modelLoader( module ){ + StringOutputStream filter( 128 ); + filter << "*." << extension; + GlobalFiletypesModule::getTable().addType( Type::Name(), extension, filetype_t( module->displayName, filter.c_str() ) ); + } + ModelLoader* getTable(){ + return &m_modelLoader; + } }; class PicoModelAPIConstructor { -CopiedString m_extension; -const picoModule_t* m_module; + CopiedString m_extension; + const picoModule_t* m_module; public: -PicoModelAPIConstructor( const char* extension, const picoModule_t* module ) : - m_extension( extension ), m_module( module ){ -} -const char* getName(){ - return m_extension.c_str(); -} -ModelPicoAPI* constructAPI( ModelPicoDependencies& dependencies ){ - return new ModelPicoAPI( m_extension.c_str(), m_module ); -} -void destroyAPI( ModelPicoAPI* api ){ - delete api; -} + PicoModelAPIConstructor( const char* extension, const picoModule_t* module ) : + m_extension( extension ), m_module( module ){ + } + const char* getName(){ + return m_extension.c_str(); + } + ModelPicoAPI* constructAPI( ModelPicoDependencies& dependencies ){ + return new ModelPicoAPI( m_extension.c_str(), m_module ); + } + void destroyAPI( ModelPicoAPI* api ){ + delete api; + } }; diff --git a/plugins/sample/sample.cpp b/plugins/sample/sample.cpp index df3ba904..e3a28bec 100644 --- a/plugins/sample/sample.cpp +++ b/plugins/sample/sample.cpp @@ -56,21 +56,21 @@ void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush class SamplePluginModule : public TypeSystemRef { -_QERPluginTable m_plugin; + _QERPluginTable m_plugin; public: -typedef _QERPluginTable Type; -STRING_CONSTANT( Name, "sample" ); + typedef _QERPluginTable Type; + STRING_CONSTANT( Name, "sample" ); -SamplePluginModule(){ - m_plugin.m_pfnQERPlug_Init = &Sample::init; - m_plugin.m_pfnQERPlug_GetName = &Sample::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &Sample::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &Sample::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &Sample::dispatch; -} -_QERPluginTable* getTable(){ - return &m_plugin; -} + SamplePluginModule(){ + m_plugin.m_pfnQERPlug_Init = &Sample::init; + m_plugin.m_pfnQERPlug_GetName = &Sample::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &Sample::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &Sample::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &Sample::dispatch; + } + _QERPluginTable* getTable(){ + return &m_plugin; + } }; typedef SingletonModule SingletonSamplePluginModule; diff --git a/plugins/shaders/plugin.cpp b/plugins/shaders/plugin.cpp index f7c74fb3..21011e67 100644 --- a/plugins/shaders/plugin.cpp +++ b/plugins/shaders/plugin.cpp @@ -38,37 +38,37 @@ class ShadersDependencies : public GlobalScripLibModuleRef, public GlobalRadiantModuleRef { -ImageModuleRef m_bitmapModule; + ImageModuleRef m_bitmapModule; public: -ShadersDependencies() : - //m_bitmapModule( "bmp" ){ - m_bitmapModule( "png" ){ -} -ImageModuleRef& getBitmapModule(){ - return m_bitmapModule; -} + ShadersDependencies() : + //m_bitmapModule( "bmp" ){ + m_bitmapModule( "png" ){ + } + ImageModuleRef& getBitmapModule(){ + return m_bitmapModule; + } }; class ShadersQ3API { -ShaderSystem* m_shadersq3; + ShaderSystem* m_shadersq3; public: -typedef ShaderSystem Type; -STRING_CONSTANT( Name, "quake3" ); + typedef ShaderSystem Type; + STRING_CONSTANT( Name, "quake3" ); -ShadersQ3API( ShadersDependencies& dependencies ){ - g_shadersExtension = "shader"; - g_shadersDirectory = "scripts/"; - g_bitmapModule = dependencies.getBitmapModule().getTable(); - Shaders_Construct(); - m_shadersq3 = &GetShaderSystem(); -} -~ShadersQ3API(){ - Shaders_Destroy(); -} -ShaderSystem* getTable(){ - return m_shadersq3; -} + ShadersQ3API( ShadersDependencies& dependencies ){ + g_shadersExtension = "shader"; + g_shadersDirectory = "scripts/"; + g_bitmapModule = dependencies.getBitmapModule().getTable(); + Shaders_Construct(); + m_shadersq3 = &GetShaderSystem(); + } + ~ShadersQ3API(){ + Shaders_Destroy(); + } + ShaderSystem* getTable(){ + return m_shadersq3; + } }; typedef SingletonModule > ShadersQ3Module; @@ -78,27 +78,27 @@ ShadersQ3Module g_ShadersQ3Module; class ShadersDoom3API { -ShaderSystem* m_shadersdoom3; + ShaderSystem* m_shadersdoom3; public: -typedef ShaderSystem Type; -STRING_CONSTANT( Name, "doom3" ); + typedef ShaderSystem Type; + STRING_CONSTANT( Name, "doom3" ); -ShadersDoom3API( ShadersDependencies& dependencies ){ - g_shadersExtension = "mtr"; - g_shadersDirectory = "materials/"; - g_enableDefaultShaders = false; - g_shaderLanguage = SHADERLANGUAGE_DOOM3; - g_useShaderList = false; - g_bitmapModule = dependencies.getBitmapModule().getTable(); - Shaders_Construct(); - m_shadersdoom3 = &GetShaderSystem(); -} -~ShadersDoom3API(){ - Shaders_Destroy(); -} -ShaderSystem* getTable(){ - return m_shadersdoom3; -} + ShadersDoom3API( ShadersDependencies& dependencies ){ + g_shadersExtension = "mtr"; + g_shadersDirectory = "materials/"; + g_enableDefaultShaders = false; + g_shaderLanguage = SHADERLANGUAGE_DOOM3; + g_useShaderList = false; + g_bitmapModule = dependencies.getBitmapModule().getTable(); + Shaders_Construct(); + m_shadersdoom3 = &GetShaderSystem(); + } + ~ShadersDoom3API(){ + Shaders_Destroy(); + } + ShaderSystem* getTable(){ + return m_shadersdoom3; + } }; typedef SingletonModule > ShadersDoom3Module; @@ -108,27 +108,27 @@ ShadersDoom3Module g_ShadersDoom3Module; class ShadersQuake4API { -ShaderSystem* m_shadersquake4; + ShaderSystem* m_shadersquake4; public: -typedef ShaderSystem Type; -STRING_CONSTANT( Name, "quake4" ); + typedef ShaderSystem Type; + STRING_CONSTANT( Name, "quake4" ); -ShadersQuake4API( ShadersDependencies& dependencies ){ - g_shadersExtension = "mtr"; - g_shadersDirectory = "materials/"; - g_enableDefaultShaders = false; - g_shaderLanguage = SHADERLANGUAGE_QUAKE4; - g_useShaderList = false; - g_bitmapModule = dependencies.getBitmapModule().getTable(); - Shaders_Construct(); - m_shadersquake4 = &GetShaderSystem(); -} -~ShadersQuake4API(){ - Shaders_Destroy(); -} -ShaderSystem* getTable(){ - return m_shadersquake4; -} + ShadersQuake4API( ShadersDependencies& dependencies ){ + g_shadersExtension = "mtr"; + g_shadersDirectory = "materials/"; + g_enableDefaultShaders = false; + g_shaderLanguage = SHADERLANGUAGE_QUAKE4; + g_useShaderList = false; + g_bitmapModule = dependencies.getBitmapModule().getTable(); + Shaders_Construct(); + m_shadersquake4 = &GetShaderSystem(); + } + ~ShadersQuake4API(){ + Shaders_Destroy(); + } + ShaderSystem* getTable(){ + return m_shadersquake4; + } }; typedef SingletonModule > ShadersQuake4Module; diff --git a/plugins/shaders/shaders.cpp b/plugins/shaders/shaders.cpp index 82371dcb..299bc6bb 100644 --- a/plugins/shaders/shaders.cpp +++ b/plugins/shaders/shaders.cpp @@ -108,8 +108,8 @@ inline byte* getPixel( byte* pixels, int width, int height, int x, int y ){ class KernelElement { public: -int x, y; -float w; + int x, y; + float w; }; Image& convertHeightmapToNormalmap( Image& heightmap, float scale ){ @@ -272,102 +272,102 @@ typedef std::pair BlendFuncExpression; class ShaderTemplate { -std::size_t m_refcount; -CopiedString m_Name; + std::size_t m_refcount; + CopiedString m_Name; public: -ShaderParameters m_params; + ShaderParameters m_params; -TextureExpression m_textureName; -TextureExpression m_diffuse; -TextureExpression m_bump; -ShaderValue m_heightmapScale; -TextureExpression m_specular; -TextureExpression m_lightFalloffImage; + TextureExpression m_textureName; + TextureExpression m_diffuse; + TextureExpression m_bump; + ShaderValue m_heightmapScale; + TextureExpression m_specular; + TextureExpression m_lightFalloffImage; -int m_nFlags; -float m_fTrans; + int m_nFlags; + float m_fTrans; // alphafunc stuff -IShader::EAlphaFunc m_AlphaFunc; -float m_AlphaRef; + IShader::EAlphaFunc m_AlphaFunc; + float m_AlphaRef; // cull stuff -IShader::ECull m_Cull; + IShader::ECull m_Cull; -ShaderTemplate() : - m_refcount( 0 ){ - m_nFlags = 0; - m_fTrans = 1.0f; -} - -void IncRef(){ - ++m_refcount; -} -void DecRef(){ - ASSERT_MESSAGE( m_refcount != 0, "shader reference-count going below zero" ); - if ( --m_refcount == 0 ) { - delete this; + ShaderTemplate() : + m_refcount( 0 ){ + m_nFlags = 0; + m_fTrans = 1.0f; } -} -std::size_t refcount(){ - return m_refcount; -} + void IncRef(){ + ++m_refcount; + } + void DecRef(){ + ASSERT_MESSAGE( m_refcount != 0, "shader reference-count going below zero" ); + if ( --m_refcount == 0 ) { + delete this; + } + } -const char* getName() const { - return m_Name.c_str(); -} -void setName( const char* name ){ - m_Name = name; -} + std::size_t refcount(){ + return m_refcount; + } + + const char* getName() const { + return m_Name.c_str(); + } + void setName( const char* name ){ + m_Name = name; + } // ----------------------------------------- -bool parseDoom3( Tokeniser& tokeniser ); -bool parseQuake3( Tokeniser& tokeniser ); -bool parseTemplate( Tokeniser& tokeniser ); + bool parseDoom3( Tokeniser& tokeniser ); + bool parseQuake3( Tokeniser& tokeniser ); + bool parseTemplate( Tokeniser& tokeniser ); -void CreateDefault( const char *name ){ - if ( g_enableDefaultShaders ) { - m_textureName = name; + void CreateDefault( const char *name ){ + if ( g_enableDefaultShaders ) { + m_textureName = name; + } + else + { + m_textureName = ""; + } + setName( name ); } - else + + + class MapLayerTemplate { - m_textureName = ""; - } - setName( name ); -} - - -class MapLayerTemplate -{ -TextureExpression m_texture; -BlendFuncExpression m_blendFunc; -bool m_clampToBorder; -ShaderValue m_alphaTest; -public: -MapLayerTemplate( const TextureExpression& texture, const BlendFuncExpression& blendFunc, bool clampToBorder, const ShaderValue& alphaTest ) : - m_texture( texture ), - m_blendFunc( blendFunc ), - m_clampToBorder( false ), - m_alphaTest( alphaTest ){ -} -const TextureExpression& texture() const { - return m_texture; -} -const BlendFuncExpression& blendFunc() const { - return m_blendFunc; -} -bool clampToBorder() const { - return m_clampToBorder; -} -const ShaderValue& alphaTest() const { - return m_alphaTest; -} -}; -typedef std::vector MapLayers; -MapLayers m_layers; + TextureExpression m_texture; + BlendFuncExpression m_blendFunc; + bool m_clampToBorder; + ShaderValue m_alphaTest; + public: + MapLayerTemplate( const TextureExpression& texture, const BlendFuncExpression& blendFunc, bool clampToBorder, const ShaderValue& alphaTest ) : + m_texture( texture ), + m_blendFunc( blendFunc ), + m_clampToBorder( false ), + m_alphaTest( alphaTest ){ + } + const TextureExpression& texture() const { + return m_texture; + } + const BlendFuncExpression& blendFunc() const { + return m_blendFunc; + } + bool clampToBorder() const { + return m_clampToBorder; + } + const ShaderValue& alphaTest() const { + return m_alphaTest; + } + }; + typedef std::vector MapLayers; + MapLayers m_layers; }; @@ -423,15 +423,15 @@ enum LayerTypeId class LayerTemplate { public: -LayerTypeId m_type; -TextureExpression m_texture; -BlendFuncExpression m_blendFunc; -bool m_clampToBorder; -ShaderValue m_alphaTest; -ShaderValue m_heightmapScale; + LayerTypeId m_type; + TextureExpression m_texture; + BlendFuncExpression m_blendFunc; + bool m_clampToBorder; + ShaderValue m_alphaTest; + ShaderValue m_heightmapScale; -LayerTemplate() : m_type( LAYER_NONE ), m_blendFunc( "GL_ONE", "GL_ZERO" ), m_clampToBorder( false ), m_alphaTest( "-1" ), m_heightmapScale( "0" ){ -} + LayerTemplate() : m_type( LAYER_NONE ), m_blendFunc( "GL_ONE", "GL_ZERO" ), m_clampToBorder( false ), m_alphaTest( "-1" ), m_heightmapScale( "0" ){ + } }; bool parseShaderParameters( Tokeniser& tokeniser, ShaderParameters& params ){ @@ -504,11 +504,11 @@ bool ShaderTemplate::parseDoom3( Tokeniser& tokeniser ){ } else if ( !string_empty( currentLayer.m_texture.c_str() ) ) { m_layers.push_back( MapLayerTemplate( - currentLayer.m_texture.c_str(), - currentLayer.m_blendFunc, - currentLayer.m_clampToBorder, - currentLayer.m_alphaTest - ) ); + currentLayer.m_texture.c_str(), + currentLayer.m_blendFunc, + currentLayer.m_clampToBorder, + currentLayer.m_alphaTest + ) ); } currentLayer.m_type = LAYER_NONE; currentLayer.m_texture = ""; @@ -635,9 +635,9 @@ bool ShaderTemplate::parseDoom3( Tokeniser& tokeniser ){ m_nFlags |= QER_AREAPORTAL; } else if ( string_equal_nocase( token, "playerclip" ) - || string_equal_nocase( token, "monsterclip" ) - || string_equal_nocase( token, "ikclip" ) - || string_equal_nocase( token, "moveableclip" ) ) { + || string_equal_nocase( token, "monsterclip" ) + || string_equal_nocase( token, "ikclip" ) + || string_equal_nocase( token, "moveableclip" ) ) { m_nFlags |= QER_CLIP; } if ( string_equal_nocase( token, "fogLight" ) ) { @@ -688,12 +688,12 @@ ShaderTemplate* findTemplate( const char* name ){ class ShaderDefinition { public: -ShaderDefinition( ShaderTemplate* shaderTemplate, const ShaderArguments& args, const char* filename ) - : shaderTemplate( shaderTemplate ), args( args ), filename( filename ){ -} -ShaderTemplate* shaderTemplate; -ShaderArguments args; -const char* filename; + ShaderDefinition( ShaderTemplate* shaderTemplate, const ShaderArguments& args, const char* filename ) + : shaderTemplate( shaderTemplate ), args( args ), filename( filename ){ + } + ShaderTemplate* shaderTemplate; + ShaderArguments args; + const char* filename; }; typedef std::map ShaderDefinitionMap; @@ -829,271 +829,274 @@ BlendFactor evaluateBlendFactor( const ShaderValue& value, const ShaderParameter class CShader : public IShader { -std::size_t m_refcount; + std::size_t m_refcount; -const ShaderTemplate& m_template; -const ShaderArguments& m_args; -const char* m_filename; + const ShaderTemplate& m_template; + const ShaderArguments& m_args; + const char* m_filename; // name is shader-name, otherwise texture-name (if not a real shader) -CopiedString m_Name; + CopiedString m_Name; -qtexture_t* m_pTexture; -qtexture_t* m_notfound; -qtexture_t* m_pDiffuse; -float m_heightmapScale; -qtexture_t* m_pBump; -qtexture_t* m_pSpecular; -qtexture_t* m_pLightFalloffImage; -BlendFunc m_blendFunc; + qtexture_t* m_pTexture; + qtexture_t* m_notfound; + qtexture_t* m_pDiffuse; + float m_heightmapScale; + qtexture_t* m_pBump; + qtexture_t* m_pSpecular; + qtexture_t* m_pLightFalloffImage; + BlendFunc m_blendFunc; -bool m_bInUse; + bool m_bInUse; public: -static bool m_lightingEnabled; + static bool m_lightingEnabled; -CShader( const ShaderDefinition& definition ) : - m_refcount( 0 ), - m_template( *definition.shaderTemplate ), - m_args( definition.args ), - m_filename( definition.filename ), - m_blendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ), - m_bInUse( false ){ - m_pTexture = 0; - m_pDiffuse = 0; - m_pBump = 0; - m_pSpecular = 0; + CShader( const ShaderDefinition& definition ) : + m_refcount( 0 ), + m_template( *definition.shaderTemplate ), + m_args( definition.args ), + m_filename( definition.filename ), + m_blendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ), + m_bInUse( false ){ + m_pTexture = 0; + m_pDiffuse = 0; + m_pBump = 0; + m_pSpecular = 0; - m_notfound = 0; + m_notfound = 0; - realise(); -} -virtual ~CShader(){ - unrealise(); + realise(); + } + virtual ~CShader(){ + unrealise(); - ASSERT_MESSAGE( m_refcount == 0, "deleting active shader" ); -} + ASSERT_MESSAGE( m_refcount == 0, "deleting active shader" ); + } // IShaders implementation ----------------- -void IncRef(){ - ++m_refcount; -} -void DecRef(){ - ASSERT_MESSAGE( m_refcount != 0, "shader reference-count going below zero" ); - if ( --m_refcount == 0 ) { - delete this; + void IncRef(){ + ++m_refcount; + } + void DecRef(){ + ASSERT_MESSAGE( m_refcount != 0, "shader reference-count going below zero" ); + if ( --m_refcount == 0 ) { + delete this; + } } -} -std::size_t refcount(){ - return m_refcount; -} + std::size_t refcount(){ + return m_refcount; + } // get/set the qtexture_t* Radiant uses to represent this shader object -qtexture_t* getTexture() const { - return m_pTexture; -} -qtexture_t* getDiffuse() const { - return m_pDiffuse; -} -qtexture_t* getBump() const { - return m_pBump; -} -qtexture_t* getSpecular() const { - return m_pSpecular; -} + qtexture_t* getTexture() const { + return m_pTexture; + } + qtexture_t* getDiffuse() const { + return m_pDiffuse; + } + qtexture_t* getBump() const { + return m_pBump; + } + qtexture_t* getSpecular() const { + return m_pSpecular; + } // get shader name -const char* getName() const { - return m_Name.c_str(); -} -bool IsInUse() const { - return m_bInUse; -} -void SetInUse( bool bInUse ){ - m_bInUse = bInUse; - g_ActiveShadersChangedNotify(); -} + const char* getName() const { + return m_Name.c_str(); + } + bool IsInUse() const { + return m_bInUse; + } + void SetInUse( bool bInUse ){ + m_bInUse = bInUse; + g_ActiveShadersChangedNotify(); + } // get the shader flags -int getFlags() const { - return m_template.m_nFlags; -} + int getFlags() const { + return m_template.m_nFlags; + } // get the transparency value -float getTrans() const { - return m_template.m_fTrans; -} + float getTrans() const { + return m_template.m_fTrans; + } // test if it's a true shader, or a default shader created to wrap around a texture -bool IsDefault() const { - return string_empty( m_filename ); -} + bool IsDefault() const { + return string_empty( m_filename ); + } // get the alphaFunc -void getAlphaFunc( EAlphaFunc *func, float *ref ) { *func = m_template.m_AlphaFunc; *ref = m_template.m_AlphaRef; }; -BlendFunc getBlendFunc() const { - return m_blendFunc; -} + void getAlphaFunc( EAlphaFunc *func, float *ref ) { + *func = m_template.m_AlphaFunc; + *ref = m_template.m_AlphaRef; + }; + BlendFunc getBlendFunc() const { + return m_blendFunc; + } // get the cull type -ECull getCull(){ - return m_template.m_Cull; -}; + ECull getCull(){ + return m_template.m_Cull; + }; // get shader file name (ie the file where this one is defined) -const char* getShaderFileName() const { - return m_filename; -} + const char* getShaderFileName() const { + return m_filename; + } // ----------------------------------------- -void realise(){ - m_pTexture = evaluateTexture( m_template.m_textureName, m_template.m_params, m_args ); + void realise(){ + m_pTexture = evaluateTexture( m_template.m_textureName, m_template.m_params, m_args ); - if ( m_pTexture->texture_number == 0 ) { - m_notfound = m_pTexture; + if ( m_pTexture->texture_number == 0 ) { + m_notfound = m_pTexture; - { - StringOutputStream name( 256 ); - name << GlobalRadiant().getAppPath() << "bitmaps/" << ( IsDefault() ? "notex.png" : "shadernotex.png" ); - m_pTexture = GlobalTexturesCache().capture( LoadImageCallback( 0, loadBitmap ), name.c_str() ); - } - } - - realiseLighting(); -} - -void unrealise(){ - GlobalTexturesCache().release( m_pTexture ); - - if ( m_notfound != 0 ) { - GlobalTexturesCache().release( m_notfound ); - } - - unrealiseLighting(); -} - -void realiseLighting(){ - if ( m_lightingEnabled ) { - LoadImageCallback loader = GlobalTexturesCache().defaultLoader(); - if ( !string_empty( m_template.m_heightmapScale.c_str() ) ) { - m_heightmapScale = evaluateFloat( m_template.m_heightmapScale, m_template.m_params, m_args ); - loader = LoadImageCallback( &m_heightmapScale, loadHeightmap ); - } - m_pDiffuse = evaluateTexture( m_template.m_diffuse, m_template.m_params, m_args ); - m_pBump = evaluateTexture( m_template.m_bump, m_template.m_params, m_args, loader ); - m_pSpecular = evaluateTexture( m_template.m_specular, m_template.m_params, m_args ); - m_pLightFalloffImage = evaluateTexture( m_template.m_lightFalloffImage, m_template.m_params, m_args ); - - for ( ShaderTemplate::MapLayers::const_iterator i = m_template.m_layers.begin(); i != m_template.m_layers.end(); ++i ) - { - m_layers.push_back( evaluateLayer( *i, m_template.m_params, m_args ) ); - } - - if ( m_layers.size() == 1 ) { - const BlendFuncExpression& blendFunc = m_template.m_layers.front().blendFunc(); - if ( !string_empty( blendFunc.second.c_str() ) ) { - m_blendFunc = BlendFunc( - evaluateBlendFactor( blendFunc.first.c_str(), m_template.m_params, m_args ), - evaluateBlendFactor( blendFunc.second.c_str(), m_template.m_params, m_args ) - ); - } - else { - const char* blend = evaluateShaderValue( blendFunc.first.c_str(), m_template.m_params, m_args ); + StringOutputStream name( 256 ); + name << GlobalRadiant().getAppPath() << "bitmaps/" << ( IsDefault() ? "notex.png" : "shadernotex.png" ); + m_pTexture = GlobalTexturesCache().capture( LoadImageCallback( 0, loadBitmap ), name.c_str() ); + } + } - if ( string_equal_nocase( blend, "add" ) ) { - m_blendFunc = BlendFunc( BLEND_ONE, BLEND_ONE ); - } - else if ( string_equal_nocase( blend, "filter" ) ) { - m_blendFunc = BlendFunc( BLEND_DST_COLOUR, BLEND_ZERO ); - } - else if ( string_equal_nocase( blend, "blend" ) ) { - m_blendFunc = BlendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ); + realiseLighting(); + } + + void unrealise(){ + GlobalTexturesCache().release( m_pTexture ); + + if ( m_notfound != 0 ) { + GlobalTexturesCache().release( m_notfound ); + } + + unrealiseLighting(); + } + + void realiseLighting(){ + if ( m_lightingEnabled ) { + LoadImageCallback loader = GlobalTexturesCache().defaultLoader(); + if ( !string_empty( m_template.m_heightmapScale.c_str() ) ) { + m_heightmapScale = evaluateFloat( m_template.m_heightmapScale, m_template.m_params, m_args ); + loader = LoadImageCallback( &m_heightmapScale, loadHeightmap ); + } + m_pDiffuse = evaluateTexture( m_template.m_diffuse, m_template.m_params, m_args ); + m_pBump = evaluateTexture( m_template.m_bump, m_template.m_params, m_args, loader ); + m_pSpecular = evaluateTexture( m_template.m_specular, m_template.m_params, m_args ); + m_pLightFalloffImage = evaluateTexture( m_template.m_lightFalloffImage, m_template.m_params, m_args ); + + for ( ShaderTemplate::MapLayers::const_iterator i = m_template.m_layers.begin(); i != m_template.m_layers.end(); ++i ) + { + m_layers.push_back( evaluateLayer( *i, m_template.m_params, m_args ) ); + } + + if ( m_layers.size() == 1 ) { + const BlendFuncExpression& blendFunc = m_template.m_layers.front().blendFunc(); + if ( !string_empty( blendFunc.second.c_str() ) ) { + m_blendFunc = BlendFunc( + evaluateBlendFactor( blendFunc.first.c_str(), m_template.m_params, m_args ), + evaluateBlendFactor( blendFunc.second.c_str(), m_template.m_params, m_args ) + ); } else { - globalErrorStream() << "parsing blend value failed: " << makeQuoted( blend ) << "\n"; + const char* blend = evaluateShaderValue( blendFunc.first.c_str(), m_template.m_params, m_args ); + + if ( string_equal_nocase( blend, "add" ) ) { + m_blendFunc = BlendFunc( BLEND_ONE, BLEND_ONE ); + } + else if ( string_equal_nocase( blend, "filter" ) ) { + m_blendFunc = BlendFunc( BLEND_DST_COLOUR, BLEND_ZERO ); + } + else if ( string_equal_nocase( blend, "blend" ) ) { + m_blendFunc = BlendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ); + } + else + { + globalErrorStream() << "parsing blend value failed: " << makeQuoted( blend ) << "\n"; + } } } } } -} -void unrealiseLighting(){ - if ( m_lightingEnabled ) { - GlobalTexturesCache().release( m_pDiffuse ); - GlobalTexturesCache().release( m_pBump ); - GlobalTexturesCache().release( m_pSpecular ); + void unrealiseLighting(){ + if ( m_lightingEnabled ) { + GlobalTexturesCache().release( m_pDiffuse ); + GlobalTexturesCache().release( m_pBump ); + GlobalTexturesCache().release( m_pSpecular ); - GlobalTexturesCache().release( m_pLightFalloffImage ); + GlobalTexturesCache().release( m_pLightFalloffImage ); - for ( MapLayers::iterator i = m_layers.begin(); i != m_layers.end(); ++i ) - { - GlobalTexturesCache().release( ( *i ).texture() ); + for ( MapLayers::iterator i = m_layers.begin(); i != m_layers.end(); ++i ) + { + GlobalTexturesCache().release( ( *i ).texture() ); + } + m_layers.clear(); + + m_blendFunc = BlendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ); } - m_layers.clear(); - - m_blendFunc = BlendFunc( BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA ); } -} // set shader name -void setName( const char* name ){ - m_Name = name; -} + void setName( const char* name ){ + m_Name = name; + } -class MapLayer : public ShaderLayer -{ -qtexture_t* m_texture; -BlendFunc m_blendFunc; -bool m_clampToBorder; -float m_alphaTest; -public: -MapLayer( qtexture_t* texture, BlendFunc blendFunc, bool clampToBorder, float alphaTest ) : - m_texture( texture ), - m_blendFunc( blendFunc ), - m_clampToBorder( false ), - m_alphaTest( alphaTest ){ -} -qtexture_t* texture() const { - return m_texture; -} -BlendFunc blendFunc() const { - return m_blendFunc; -} -bool clampToBorder() const { - return m_clampToBorder; -} -float alphaTest() const { - return m_alphaTest; -} -}; + class MapLayer : public ShaderLayer + { + qtexture_t* m_texture; + BlendFunc m_blendFunc; + bool m_clampToBorder; + float m_alphaTest; + public: + MapLayer( qtexture_t* texture, BlendFunc blendFunc, bool clampToBorder, float alphaTest ) : + m_texture( texture ), + m_blendFunc( blendFunc ), + m_clampToBorder( false ), + m_alphaTest( alphaTest ){ + } + qtexture_t* texture() const { + return m_texture; + } + BlendFunc blendFunc() const { + return m_blendFunc; + } + bool clampToBorder() const { + return m_clampToBorder; + } + float alphaTest() const { + return m_alphaTest; + } + }; -static MapLayer evaluateLayer( const ShaderTemplate::MapLayerTemplate& layerTemplate, const ShaderParameters& params, const ShaderArguments& args ){ - return MapLayer( - evaluateTexture( layerTemplate.texture(), params, args ), - evaluateBlendFunc( layerTemplate.blendFunc(), params, args ), - layerTemplate.clampToBorder(), - evaluateFloat( layerTemplate.alphaTest(), params, args ) - ); -} + static MapLayer evaluateLayer( const ShaderTemplate::MapLayerTemplate& layerTemplate, const ShaderParameters& params, const ShaderArguments& args ){ + return MapLayer( + evaluateTexture( layerTemplate.texture(), params, args ), + evaluateBlendFunc( layerTemplate.blendFunc(), params, args ), + layerTemplate.clampToBorder(), + evaluateFloat( layerTemplate.alphaTest(), params, args ) + ); + } -typedef std::vector MapLayers; -MapLayers m_layers; + typedef std::vector MapLayers; + MapLayers m_layers; -const ShaderLayer* firstLayer() const { - if ( m_layers.empty() ) { + const ShaderLayer* firstLayer() const { + if ( m_layers.empty() ) { + return 0; + } + return &m_layers.front(); + } + void forEachLayer( const ShaderLayerCallback& callback ) const { + for ( MapLayers::const_iterator i = m_layers.begin(); i != m_layers.end(); ++i ) + { + callback( *i ); + } + } + + qtexture_t* lightFalloffImage() const { + if ( !string_empty( m_template.m_lightFalloffImage.c_str() ) ) { + return m_pLightFalloffImage; + } return 0; } - return &m_layers.front(); -} -void forEachLayer( const ShaderLayerCallback& callback ) const { - for ( MapLayers::const_iterator i = m_layers.begin(); i != m_layers.end(); ++i ) - { - callback( *i ); - } -} - -qtexture_t* lightFalloffImage() const { - if ( !string_empty( m_template.m_lightFalloffImage.c_str() ) ) { - return m_pLightFalloffImage; - } - return 0; -} }; bool CShader::m_lightingEnabled = false; @@ -1226,13 +1229,13 @@ bool ShaderTemplate::parseQuake3( Tokeniser& tokeniser ){ } if ( string_equal_nocase( cull, "none" ) - || string_equal_nocase( cull, "twosided" ) - || string_equal_nocase( cull, "disable" ) ) { + || string_equal_nocase( cull, "twosided" ) + || string_equal_nocase( cull, "disable" ) ) { m_Cull = IShader::eCullNone; } else if ( string_equal_nocase( cull, "back" ) - || string_equal_nocase( cull, "backside" ) - || string_equal_nocase( cull, "backsided" ) ) { + || string_equal_nocase( cull, "backside" ) + || string_equal_nocase( cull, "backsided" ) ) { m_Cull = IShader::eCullBack; } else @@ -1264,8 +1267,8 @@ bool ShaderTemplate::parseQuake3( Tokeniser& tokeniser ){ m_nFlags |= QER_NONSOLID; } else if ( string_equal_nocase( surfaceparm, "water" ) || - string_equal_nocase( surfaceparm, "lava" ) || - string_equal_nocase( surfaceparm, "slime") ){ + string_equal_nocase( surfaceparm, "lava" ) || + string_equal_nocase( surfaceparm, "slime") ){ m_nFlags |= QER_LIQUID; } else if ( string_equal_nocase( surfaceparm, "areaportal" ) ) { @@ -1287,15 +1290,15 @@ bool ShaderTemplate::parseQuake3( Tokeniser& tokeniser ){ class Layer { public: -LayerTypeId m_type; -TextureExpression m_texture; -BlendFunc m_blendFunc; -bool m_clampToBorder; -float m_alphaTest; -float m_heightmapScale; + LayerTypeId m_type; + TextureExpression m_texture; + BlendFunc m_blendFunc; + bool m_clampToBorder; + float m_alphaTest; + float m_heightmapScale; -Layer() : m_type( LAYER_NONE ), m_blendFunc( BLEND_ONE, BLEND_ZERO ), m_clampToBorder( false ), m_alphaTest( -1 ), m_heightmapScale( 0 ){ -} + Layer() : m_type( LAYER_NONE ), m_blendFunc( BLEND_ONE, BLEND_ZERO ), m_clampToBorder( false ), m_alphaTest( -1 ), m_heightmapScale( 0 ){ + } }; std::list g_shaderFilenames; @@ -1347,8 +1350,8 @@ void ParseShaderFile( Tokeniser& tokeniser, const char* filename ){ else { if ( !string_equal( token, "material" ) - && !string_equal( token, "particle" ) - && !string_equal( token, "skin" ) ) { + && !string_equal( token, "particle" ) + && !string_equal( token, "skin" ) ) { tokeniser.ungetToken(); } // first token should be the path + name.. (from base) @@ -1361,14 +1364,14 @@ void ParseShaderFile( Tokeniser& tokeniser, const char* filename ){ g_shaders.insert( ShaderTemplateMap::value_type( shaderTemplate->getName(), shaderTemplate ) ); bool result = ( g_shaderLanguage == SHADERLANGUAGE_QUAKE3 ) - ? shaderTemplate->parseQuake3( tokeniser ) - : shaderTemplate->parseDoom3( tokeniser ); + ? shaderTemplate->parseQuake3( tokeniser ) + : shaderTemplate->parseDoom3( tokeniser ); if ( result ) { // do we already have this shader? if ( !g_shaderDefinitions.insert( ShaderDefinitionMap::value_type( shaderTemplate->getName(), ShaderDefinition( shaderTemplate.get(), ShaderArguments(), filename ) ) ).second ) { - #ifdef _DEBUG +#ifdef _DEBUG globalWarningStream() << "WARNING: shader " << shaderTemplate->getName() << " is already in memory, definition in " << filename << " ignored.\n"; - #endif +#endif } } else @@ -1728,67 +1731,67 @@ void Shaders_Refresh(){ class Quake3ShaderSystem : public ShaderSystem, public ModuleObserver { public: -void realise(){ - Shaders_Realise(); -} -void unrealise(){ - Shaders_Unrealise(); -} -void refresh(){ - Shaders_Refresh(); -} - -IShader* getShaderForName( const char* name ){ - return Shader_ForName( name ); -} - -void foreachShaderName( const ShaderNameCallback& callback ){ - for ( ShaderDefinitionMap::const_iterator i = g_shaderDefinitions.begin(); i != g_shaderDefinitions.end(); ++i ) - { - callback( ( *i ).first.c_str() ); + void realise(){ + Shaders_Realise(); + } + void unrealise(){ + Shaders_Unrealise(); + } + void refresh(){ + Shaders_Refresh(); } -} -void beginActiveShadersIterator(){ - ActiveShaders_IteratorBegin(); -} -bool endActiveShadersIterator(){ - return ActiveShaders_IteratorAtEnd(); -} -IShader* dereferenceActiveShadersIterator(){ - return ActiveShaders_IteratorCurrent(); -} -void incrementActiveShadersIterator(){ - ActiveShaders_IteratorIncrement(); -} -void setActiveShadersChangedNotify( const Callback& notify ){ - g_ActiveShadersChangedNotify = notify; -} + IShader* getShaderForName( const char* name ){ + return Shader_ForName( name ); + } -void attach( ModuleObserver& observer ){ - g_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - g_observers.detach( observer ); -} - -void setLightingEnabled( bool enabled ){ - if ( CShader::m_lightingEnabled != enabled ) { - for ( shaders_t::const_iterator i = g_ActiveShaders.begin(); i != g_ActiveShaders.end(); ++i ) + void foreachShaderName( const ShaderNameCallback& callback ){ + for ( ShaderDefinitionMap::const_iterator i = g_shaderDefinitions.begin(); i != g_shaderDefinitions.end(); ++i ) { - ( *i ).second->unrealiseLighting(); - } - CShader::m_lightingEnabled = enabled; - for ( shaders_t::const_iterator i = g_ActiveShaders.begin(); i != g_ActiveShaders.end(); ++i ) - { - ( *i ).second->realiseLighting(); + callback( ( *i ).first.c_str() ); } } -} -const char* getTexturePrefix() const { - return g_texturePrefix; -} + void beginActiveShadersIterator(){ + ActiveShaders_IteratorBegin(); + } + bool endActiveShadersIterator(){ + return ActiveShaders_IteratorAtEnd(); + } + IShader* dereferenceActiveShadersIterator(){ + return ActiveShaders_IteratorCurrent(); + } + void incrementActiveShadersIterator(){ + ActiveShaders_IteratorIncrement(); + } + void setActiveShadersChangedNotify( const Callback& notify ){ + g_ActiveShadersChangedNotify = notify; + } + + void attach( ModuleObserver& observer ){ + g_observers.attach( observer ); + } + void detach( ModuleObserver& observer ){ + g_observers.detach( observer ); + } + + void setLightingEnabled( bool enabled ){ + if ( CShader::m_lightingEnabled != enabled ) { + for ( shaders_t::const_iterator i = g_ActiveShaders.begin(); i != g_ActiveShaders.end(); ++i ) + { + ( *i ).second->unrealiseLighting(); + } + CShader::m_lightingEnabled = enabled; + for ( shaders_t::const_iterator i = g_ActiveShaders.begin(); i != g_ActiveShaders.end(); ++i ) + { + ( *i ).second->realiseLighting(); + } + } + } + + const char* getTexturePrefix() const { + return g_texturePrefix; + } }; Quake3ShaderSystem g_Quake3ShaderSystem; diff --git a/plugins/spritemodel/plugin.cpp b/plugins/spritemodel/plugin.cpp index fd881ecf..536c59b7 100644 --- a/plugins/spritemodel/plugin.cpp +++ b/plugins/spritemodel/plugin.cpp @@ -151,17 +151,17 @@ class CSynapseClientModel : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); -const char* GetName(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); + const char* GetName(); -CSynapseClientModel() { } -virtual ~CSynapseClientModel() { } + CSynapseClientModel() { } + virtual ~CSynapseClientModel() { } -bool OnActivate(){ - init_filetypes(); // see todo list above. - return true; -} + bool OnActivate(){ + init_filetypes(); // see todo list above. + return true; + } }; CSynapseServer* g_pSynapseServer = NULL; diff --git a/plugins/spritemodel/spritemodel.h b/plugins/spritemodel/spritemodel.h index 698cf449..9c715ac9 100644 --- a/plugins/spritemodel/spritemodel.h +++ b/plugins/spritemodel/spritemodel.h @@ -32,31 +32,35 @@ class CSpriteModel : public IRender //, public ISelect { public: -CSpriteModel(); -~CSpriteModel(); + CSpriteModel(); + ~CSpriteModel(); -void IncRef() { refCount++; } -void DecRef() { - if ( --refCount == 0 ) { - delete this; + void IncRef() { + refCount++; + } + void DecRef() { + if ( --refCount == 0 ) { + delete this; + } } -} //IRender -void Draw( int state, int rflags ) const; -const aabb_t *GetAABB() const { return &m_BBox; } + void Draw( int state, int rflags ) const; + const aabb_t *GetAABB() const { + return &m_BBox; + } //ISelect //bool TestRay (const ray_t *ray, vec_t *dist) const; -void Construct( IShader *pShader ); + void Construct( IShader *pShader ); protected: -IShader *m_pShader; + IShader *m_pShader; private: -int refCount; -aabb_t m_BBox; + int refCount; + aabb_t m_BBox; }; void LoadSpriteModel( entity_interfaces_t *interfaces, const char *name ); diff --git a/plugins/textool/2DView.cpp b/plugins/textool/2DView.cpp index 50ac6e48..6419abab 100644 --- a/plugins/textool/2DView.cpp +++ b/plugins/textool/2DView.cpp @@ -98,8 +98,10 @@ bool C2DView::OnRButtonDown( int x, int y ){ m_xPosMove = x; // horizontal position of cursor m_yPosMove = y; // vertical position of cursor // store - m_MinsMove[0] = m_Mins[0]; m_MinsMove[1] = m_Mins[1]; - m_MaxsMove[0] = m_Maxs[0]; m_MaxsMove[1] = m_Maxs[1]; + m_MinsMove[0] = m_Mins[0]; + m_MinsMove[1] = m_Mins[1]; + m_MaxsMove[0] = m_Maxs[0]; + m_MaxsMove[1] = m_Maxs[1]; ViewState = View_Move; // set popup to true m_bPopup = true; diff --git a/plugins/textool/2DView.h b/plugins/textool/2DView.h index c2773abf..1c01cc3c 100644 --- a/plugins/textool/2DView.h +++ b/plugins/textool/2DView.h @@ -32,38 +32,42 @@ class C2DView { -enum E2DViewState { View_Idle, View_Move } ViewState; -int m_xPosMove, m_yPosMove; -float m_MinsMove[2], m_MaxsMove[2]; -qboolean m_bDoGrid; -float m_GridStep[2]; -qboolean m_bPopup; + enum E2DViewState { View_Idle, View_Move } ViewState; + int m_xPosMove, m_yPosMove; + float m_MinsMove[2], m_MaxsMove[2]; + qboolean m_bDoGrid; + float m_GridStep[2]; + qboolean m_bPopup; public: -RECT m_rect; -float m_Mins[2],m_Maxs[2],m_Center[2]; -C2DView(){ - ViewState = View_Idle; - m_bDoGrid = false; - m_bPopup = false; -} -~C2DView() { } -void SetGrid( float xGridStep, float yGridStep ) -{ m_bDoGrid = true; m_GridStep[0] = xGridStep; m_GridStep[1] = yGridStep; } + RECT m_rect; + float m_Mins[2],m_Maxs[2],m_Center[2]; + C2DView(){ + ViewState = View_Idle; + m_bDoGrid = false; + m_bPopup = false; + } + ~C2DView() { } + void SetGrid( float xGridStep, float yGridStep ) + { + m_bDoGrid = true; + m_GridStep[0] = xGridStep; + m_GridStep[1] = yGridStep; + } // get window coordinates for space coordinates -void WindowForSpace( int &x, int &y, const float c[2] ); -void SpaceForWindow( float c[2], int x, int y ); -void GridForWindow( float c[2], int x, int y ); -qboolean DoesSelect( int x, int y, float c[2] ); -void PreparePaint(); + void WindowForSpace( int &x, int &y, const float c[2] ); + void SpaceForWindow( float c[2], int x, int y ); + void GridForWindow( float c[2], int x, int y ); + qboolean DoesSelect( int x, int y, float c[2] ); + void PreparePaint(); -bool OnRButtonDown( int x, int y ); -bool OnMouseMove( int x, int y ); -bool OnRButtonUp( int x, int y ); -bool OnKeyDown( char *s ); + bool OnRButtonDown( int x, int y ); + bool OnMouseMove( int x, int y ); + bool OnRButtonUp( int x, int y ); + bool OnKeyDown( char *s ); -void ZoomIn(); -void ZoomOut(); + void ZoomIn(); + void ZoomOut(); }; #endif diff --git a/plugins/textool/ControlPointsManager.cpp b/plugins/textool/ControlPointsManager.cpp index 796cf9a5..eb5cd1e8 100644 --- a/plugins/textool/ControlPointsManager.cpp +++ b/plugins/textool/ControlPointsManager.cpp @@ -29,7 +29,7 @@ #include "StdAfx.h" void CControlPointsManagerBFace::Init( int iPts, CtrlPts_t *Pts, C2DView *p2DView, int TexSize[2], - _QERFaceData* pFaceData, OpenGLBinding *pQglTable ){ + _QERFaceData* pFaceData, OpenGLBinding *pQglTable ){ ManagerState = Idle; m_NumPoints = iPts; m_pPts = Pts; @@ -37,9 +37,11 @@ void CControlPointsManagerBFace::Init( int iPts, CtrlPts_t *Pts, C2DView *p2DVie memcpy( &m_RefPts, Pts, sizeof( CtrlPts_t ) ); // init TM memset( m_TM, 0, sizeof( float[2][3] ) ); - m_TM[0][0] = 1.0f; m_TM[1][1] = 1.0f; + m_TM[0][0] = 1.0f; + m_TM[1][1] = 1.0f; m_bGotAnchor = false; - m_TransOffset[0] = 0.0f; m_TransOffset[1] = 0.0f; + m_TransOffset[0] = 0.0f; + m_TransOffset[1] = 0.0f; m_TexSize[0] = TexSize[0]; m_TexSize[1] = TexSize[1]; m_pFaceData = pFaceData; @@ -110,11 +112,13 @@ bool CControlPointsManagerBFace::OnMouseMove( int xPos, int yPos ){ // current position of the Anchor in XY space XYSpaceForSTSpace( XYAnchor, m_Anchor ); // compute transformation matrix - XYTM[0][0] = c; XYTM[1][1] = c; + XYTM[0][0] = c; + XYTM[1][1] = c; if ( cross[2] > 0 ) { s *= -1.0f; } - XYTM[0][1] = s; XYTM[1][0] = -s; + XYTM[0][1] = s; + XYTM[1][0] = -s; XYTM[0][2] = -c * XYRefAnchor[0] - s * XYRefAnchor[1] + XYAnchor[0]; XYTM[1][2] = s * XYRefAnchor[0] - c * XYRefAnchor[1] + XYAnchor[1]; // express this transformation matrix in ST space diff --git a/plugins/textool/ControlPointsManager.h b/plugins/textool/ControlPointsManager.h index 7ade7c41..4b225b79 100644 --- a/plugins/textool/ControlPointsManager.h +++ b/plugins/textool/ControlPointsManager.h @@ -41,93 +41,103 @@ class CControlPointsManager { protected: // used by Render -OpenGLBinding *m_pQglTable; -C2DView *m_p2DView; + OpenGLBinding *m_pQglTable; + C2DView *m_p2DView; public: -CControlPointsManager() { m_pQglTable = NULL; m_p2DView = NULL; } -virtual ~CControlPointsManager() { } -void Init( C2DView *p2DView, OpenGLBinding *pQglTable ) { m_pQglTable = pQglTable; m_p2DView = p2DView; } + CControlPointsManager() { + m_pQglTable = NULL; + m_p2DView = NULL; + } + virtual ~CControlPointsManager() { } + void Init( C2DView *p2DView, OpenGLBinding *pQglTable ) { + m_pQglTable = pQglTable; + m_p2DView = p2DView; + } -virtual bool OnLButtonDown( int x, int y ) = 0; -virtual bool OnMouseMove( int x, int y ) = 0; -virtual bool OnLButtonUp( int x, int y ) = 0; + virtual bool OnLButtonDown( int x, int y ) = 0; + virtual bool OnMouseMove( int x, int y ) = 0; + virtual bool OnLButtonUp( int x, int y ) = 0; -virtual void render() = 0; -virtual void Commit() = 0; + virtual void render() = 0; + virtual void Commit() = 0; }; // brush face manager class CControlPointsManagerBFace : public CControlPointsManager { -enum EManagerState { Idle, Drag } ManagerState; -int m_NumPoints; + enum EManagerState { Idle, Drag } ManagerState; + int m_NumPoints; // initial geometry -CtrlPts_t m_RefPts; + CtrlPts_t m_RefPts; // current geometry -CtrlPts_t *m_pPts; + CtrlPts_t *m_pPts; // transform matrix ( 2DView is Window <-> ST ) -float m_TM[2][3]; + float m_TM[2][3]; // texture size for ST <-> XY -int m_TexSize[2]; + int m_TexSize[2]; // used when translating -float m_TransOffset[2]; + float m_TransOffset[2]; // dragged point index -int m_iDragPoint; + int m_iDragPoint; // do we have an anchor ? -bool m_bGotAnchor; + bool m_bGotAnchor; // anchor point index -int m_iAnchorPoint; + int m_iAnchorPoint; // coordinates of Anchor -float m_Anchor[2]; + float m_Anchor[2]; // used for commit -_QERFaceData *m_pFaceData; + _QERFaceData *m_pFaceData; public: // construction / init ------------------------------------------------- -CControlPointsManagerBFace() { ManagerState = Idle; } -virtual ~CControlPointsManagerBFace() { } + CControlPointsManagerBFace() { + ManagerState = Idle; + } + virtual ~CControlPointsManagerBFace() { } // NOTE: pQglTable is sent to CControlPointsManager::Init -void Init( int iPts, CtrlPts_t * Pts, C2DView * p2DView, int TexSize[2], _QERFaceData * pFaceData, OpenGLBinding * pQglTable ); + void Init( int iPts, CtrlPts_t * Pts, C2DView * p2DView, int TexSize[2], _QERFaceData * pFaceData, OpenGLBinding * pQglTable ); // CControlPointsManager interface ------------------------------------- -virtual bool OnLButtonDown( int x, int y ); -virtual bool OnMouseMove( int x, int y ); -virtual bool OnLButtonUp( int x, int y ); + virtual bool OnLButtonDown( int x, int y ); + virtual bool OnMouseMove( int x, int y ); + virtual bool OnLButtonUp( int x, int y ); -virtual void render(); -virtual void Commit(); + virtual void render(); + virtual void Commit(); private: // internal members -void UpdateCtrlPts(); -void ComputeTransOffset( int i ); -void XYSpaceForSTSpace( float xy[2], const float st[2] ); + void UpdateCtrlPts(); + void ComputeTransOffset( int i ); + void XYSpaceForSTSpace( float xy[2], const float st[2] ); }; // patch manager class CControlPointsManagerPatch : public CControlPointsManager { -enum EManagerState { Idle, Drag } ManagerState; + enum EManagerState { Idle, Drag } ManagerState; // reference data, used for commits -patchMesh_t* m_pPatch; + patchMesh_t* m_pPatch; // work patch, holds current data -patchMesh_t* m_pWorkPatch; -int m_iDragPoint[2]; + patchMesh_t* m_pWorkPatch; + int m_iDragPoint[2]; public: // construction / init ------------------------------------------------- -CControlPointsManagerPatch() { ManagerState = Idle; } -virtual ~CControlPointsManagerPatch() { } + CControlPointsManagerPatch() { + ManagerState = Idle; + } + virtual ~CControlPointsManagerPatch() { } // NOTE: pQglTable is sent to CControlPointsManager::Init -void Init( patchMesh_t* pWorkPatch, C2DView *p2DView, OpenGLBinding *pQglTable, patchMesh_t* pPatch ); + void Init( patchMesh_t* pWorkPatch, C2DView *p2DView, OpenGLBinding *pQglTable, patchMesh_t* pPatch ); // CControlPointsManager interface ------------------------------------- -virtual bool OnLButtonDown( int x, int y ); -virtual bool OnMouseMove( int x, int y ); -virtual bool OnLButtonUp( int x, int y ); + virtual bool OnLButtonDown( int x, int y ); + virtual bool OnMouseMove( int x, int y ); + virtual bool OnLButtonUp( int x, int y ); -virtual void render(); -virtual void Commit(); + virtual void render(); + virtual void Commit(); }; #endif diff --git a/plugins/textool/StdAfx.h b/plugins/textool/StdAfx.h index a31c0a6d..cf37f940 100644 --- a/plugins/textool/StdAfx.h +++ b/plugins/textool/StdAfx.h @@ -99,27 +99,33 @@ extern "C" void Sys_Printf( char *text, ... ); // NOTE: I'm not too sure about the bool flags being any use.. they are supposed to tell if we handle the event or not class CWindowListener : public IWindowListener { -int refCount; + int refCount; public: // Increment the number of references to this object -void IncRef() { refCount++; } -// Decrement the reference count -void DecRef() { - if ( --refCount <= 0 ) { - delete this; + void IncRef() { + refCount++; + } +// Decrement the reference count + void DecRef() { + if ( --refCount <= 0 ) { + delete this; + } } -} // IWindowListener --------------------------------------- -bool OnLButtonDown( guint32 nFlags, double x, double y ); -bool OnMButtonDown( guint32 nFlags, double x, double y ) { return false; } -bool OnRButtonDown( guint32 nFlags, double x, double y ); -bool OnLButtonUp( guint32 nFlags, double x, double y ); -bool OnMButtonUp( guint32 nFlags, double x, double y ) { return false; } -bool OnRButtonUp( guint32 nFlags, double x, double y ); -bool OnMouseMove( guint32 nFlags, double x, double y ); -bool OnKeyPressed( char *s ); -bool Paint(); -void Close(); + bool OnLButtonDown( guint32 nFlags, double x, double y ); + bool OnMButtonDown( guint32 nFlags, double x, double y ) { + return false; + } + bool OnRButtonDown( guint32 nFlags, double x, double y ); + bool OnLButtonUp( guint32 nFlags, double x, double y ); + bool OnMButtonUp( guint32 nFlags, double x, double y ) { + return false; + } + bool OnRButtonUp( guint32 nFlags, double x, double y ); + bool OnMouseMove( guint32 nFlags, double x, double y ); + bool OnKeyPressed( char *s ); + bool Paint(); + void Close(); }; #include "2DView.h" @@ -148,11 +154,11 @@ class CSynapseClientTexTool : public CSynapseClient { public: // CSynapseClient API -bool RequestAPI( APIDescriptor_t *pAPI ); -const char* GetInfo(); + bool RequestAPI( APIDescriptor_t *pAPI ); + const char* GetInfo(); -CSynapseClientTexTool() { } -virtual ~CSynapseClientTexTool() { } + CSynapseClientTexTool() { } + virtual ~CSynapseClientTexTool() { } }; extern IWindow *g_pToolWnd; diff --git a/plugins/textool/TexTool.cpp b/plugins/textool/TexTool.cpp index 56bbff3b..70e6b680 100644 --- a/plugins/textool/TexTool.cpp +++ b/plugins/textool/TexTool.cpp @@ -56,9 +56,9 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); g_signal_connect( G_OBJECT( window ), "delete_event", - G_CALLBACK( dialog_delete_callback ), NULL ); + G_CALLBACK( dialog_delete_callback ), NULL ); g_signal_connect( G_OBJECT( window ), "destroy", - G_CALLBACK( gtk_widget_destroy ), NULL ); + G_CALLBACK( gtk_widget_destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), lpCaption ); gtk_container_set_border_width( GTK_CONTAINER( window ), 10 ); g_object_set_data( G_OBJECT( window ), "loop", &loop ); @@ -86,7 +86,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -96,7 +96,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Ok" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -104,7 +104,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); gtk_widget_show( w ); ret = IDCANCEL; } @@ -112,7 +112,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -120,13 +120,13 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); gtk_widget_show( w ); ret = IDCANCEL; } @@ -135,7 +135,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "Yes" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); gtk_widget_set_can_default( w, TRUE ); gtk_widget_grab_default( w ); gtk_widget_show( w ); @@ -143,7 +143,7 @@ int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ w = gtk_button_new_with_label( "No" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); g_signal_connect( G_OBJECT( w ), "clicked", - G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + G_CALLBACK( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); gtk_widget_show( w ); ret = IDNO; } @@ -231,8 +231,8 @@ bool g_bHelp = false; bool g_bClosing = false; const char *PLUGIN_ABOUT = "Texture Tools for Radiant\n\n" - "Gtk port by Leonardo Zide (leo@lokigames.com)\n" - "Original version by Timothee \"TTimo\" Besset (timo@qeradiant.com)"; + "Gtk port by Leonardo Zide (leo@lokigames.com)\n" + "Original version by Timothee \"TTimo\" Besset (timo@qeradiant.com)"; extern "C" void* WINAPI QERPlug_GetFuncTable(){ return &g_FuncTable; @@ -340,8 +340,10 @@ void InitTexView( IWindow* hwndDlg ){ // we have something selected // setup: compute BBox for the winding ( in ST space ) //++timo FIXME: move this in a C2DView member ? used as well for patches - g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; - g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; + g_2DView.m_Mins[0] = +9999.0f; + g_2DView.m_Mins[1] = +9999.0f; + g_2DView.m_Maxs[0] = -9999.0f; + g_2DView.m_Maxs[1] = -9999.0f; for ( i = 0; i < g_pSelectedFaceWinding->numpoints; i++ ) { if ( g_pSelectedFaceWinding->points[i][3] < g_2DView.m_Mins[0] ) { @@ -383,8 +385,10 @@ void InitTexView( IWindow* hwndDlg ){ g_bPatch = true; int i,j; // compute BBox for all patch points - g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; - g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; + g_2DView.m_Mins[0] = +9999.0f; + g_2DView.m_Mins[1] = +9999.0f; + g_2DView.m_Maxs[0] = -9999.0f; + g_2DView.m_Maxs[1] = -9999.0f; for ( i = 0; i < g_pPatch->width; i++ ) { for ( j = 0; j < g_pPatch->height; j++ ) @@ -523,8 +527,8 @@ static bool CanProcess(){ if ( !g_bTexViewReady ) { g_bClosing = true; DoMessageBox( "You must have brush primitives activated in your project settings and\n" - "have a patch or a single face selected to use the TexTool plugin.\n" - "See plugins/TexToolHelp for documentation.", "TexTool plugin", MB_ICONERROR | MB_OK ); + "have a patch or a single face selected to use the TexTool plugin.\n" + "See plugins/TexToolHelp for documentation.", "TexTool plugin", MB_ICONERROR | MB_OK ); // decref, this will destroy g_pToolWnd->DecRef(); g_pToolWnd = NULL; @@ -547,9 +551,11 @@ static void button_press( GtkWidget *widget, GdkEventButton *event, gpointer dat switch ( event->button ) { case 1: - g_pManager->OnLButtonDown( event->x, event->y ); break; + g_pManager->OnLButtonDown( event->x, event->y ); + break; case 3: - g_2DView.OnRButtonDown( event->x, event->y ); break; + g_2DView.OnRButtonDown( event->x, event->y ); + break; } } } @@ -559,9 +565,11 @@ static void button_release( GtkWidget *widget, GdkEventButton *event, gpointer d switch ( event->button ) { case 1: - g_pManager->OnLButtonUp( event->x, event->y ); break; + g_pManager->OnLButtonUp( event->x, event->y ); + break; case 3: - g_2DView.OnRButtonUp( event->x, event->y ); break; + g_2DView.OnRButtonUp( event->x, event->y ); + break; } } } @@ -640,20 +648,20 @@ static GtkWidget* CreateOpenGLWidget(){ g_pToolWidget = g_QglTable.m_pfn_glwidget_new( FALSE, g_QglTable.m_pfn_GetQeglobalsGLWidget() ); gtk_widget_set_events( g_pToolWidget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK | - GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK ); + GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK ); // Connect signal handlers g_signal_connect( G_OBJECT( g_pToolWidget ), "expose_event", G_CALLBACK( expose ), NULL ); g_signal_connect( G_OBJECT( g_pToolWidget ), "motion_notify_event", - G_CALLBACK( motion ), NULL ); + G_CALLBACK( motion ), NULL ); g_signal_connect( G_OBJECT( g_pToolWidget ), "button_press_event", - G_CALLBACK( button_press ), NULL ); + G_CALLBACK( button_press ), NULL ); g_signal_connect( G_OBJECT( g_pToolWidget ), "button_release_event", - G_CALLBACK( button_release ), NULL ); + G_CALLBACK( button_release ), NULL ); g_signal_connect( G_OBJECT( g_pToolWnd ), "delete_event", G_CALLBACK( close ), NULL ); g_signal_connect( G_OBJECT( g_pToolWnd ), "key_press_event", - G_CALLBACK( keypress ), NULL ); + G_CALLBACK( keypress ), NULL ); return g_pToolWidget; } @@ -771,7 +779,7 @@ bool CWindowListener::OnKeyPressed( char *s ){ } extern "C" void QERPlug_Dispatch( const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ){ - #if 0 +#if 0 // if it's the first call, perhaps we need some additional init steps if ( !g_bQglInitDone ) { g_QglTable.m_nSize = sizeof( OpenGLBinding ); @@ -788,7 +796,7 @@ extern "C" void QERPlug_Dispatch( const char* p, vec3_t vMin, vec3_t vMax, bool if ( !g_bSelectedFaceInitDone ) { g_SelectedFaceTable.m_nSize = sizeof( _QERSelectedFaceTable ); if ( g_FuncTable.m_pfnRequestInterface( QERSelectedFaceTable_GUID, - static_cast( &g_SelectedFaceTable ) ) ) { + static_cast( &g_SelectedFaceTable ) ) ) { g_bSelectedFaceInitDone = true; } else @@ -821,7 +829,7 @@ extern "C" void QERPlug_Dispatch( const char* p, vec3_t vMin, vec3_t vMax, bool return; } } - #endif +#endif if ( !strcmp( p, "About..." ) ) { DoMessageBox( PLUGIN_ABOUT, "About ...", MB_OK ); @@ -847,7 +855,7 @@ extern "C" void QERPlug_Dispatch( const char* p, vec3_t vMin, vec3_t vMax, bool else if ( !strcmp( p, "Help..." ) ) { if ( !g_bHelp ) { DoMessageBox( "Select a brush face (ctrl+shift+left mouse) or a patch, and hit Go...\n" - "See tutorials for more", "TexTool plugin", MB_OK ); + "See tutorials for more", "TexTool plugin", MB_OK ); } else{ DoMessageBox( "Are you kidding me ?", "TexTool plugin", MB_OK ); diff --git a/plugins/vfspk3/archive.cpp b/plugins/vfspk3/archive.cpp index de398777..2f6de2f3 100644 --- a/plugins/vfspk3/archive.cpp +++ b/plugins/vfspk3/archive.cpp @@ -42,78 +42,78 @@ class DirectoryArchive final : public Archive { -CopiedString m_root; + CopiedString m_root; public: -DirectoryArchive( const char* root ) : m_root( root ){ -} - -void release(){ - delete this; -} -virtual ArchiveFile* openFile( const char* name ){ - UnixPath path( m_root.c_str() ); - path.push_filename( name ); - DirectoryArchiveFile* file = new DirectoryArchiveFile( name, path.c_str() ); - if ( !file->failed() ) { - return file; + DirectoryArchive( const char* root ) : m_root( root ){ } - file->release(); - return 0; -} -virtual ArchiveTextFile* openTextFile( const char* name ){ - UnixPath path( m_root.c_str() ); - path.push_filename( name ); - DirectoryArchiveTextFile* file = new DirectoryArchiveTextFile( name, path.c_str() ); - if ( !file->failed() ) { - return file; + + void release(){ + delete this; } - file->release(); - return 0; -} -virtual bool containsFile( const char* name ){ - UnixPath path( m_root.c_str() ); - path.push_filename( name ); - return file_readable( path.c_str() ); -} -virtual void forEachFile( VisitorFunc visitor, const char* root ){ - std::vector dirs; - UnixPath path( m_root.c_str() ); - path.push( root ); - dirs.push_back( directory_open( path.c_str() ) ); - - while ( !dirs.empty() && directory_good( dirs.back() ) ) - { - const char* name = directory_read_and_increment( dirs.back() ); - - if ( name == 0 ) { - directory_close( dirs.back() ); - dirs.pop_back(); - path.pop(); + virtual ArchiveFile* openFile( const char* name ){ + UnixPath path( m_root.c_str() ); + path.push_filename( name ); + DirectoryArchiveFile* file = new DirectoryArchiveFile( name, path.c_str() ); + if ( !file->failed() ) { + return file; } - else if ( !string_equal( name, "." ) && !string_equal( name, ".." ) ) { - path.push_filename( name ); + file->release(); + return 0; + } + virtual ArchiveTextFile* openTextFile( const char* name ){ + UnixPath path( m_root.c_str() ); + path.push_filename( name ); + DirectoryArchiveTextFile* file = new DirectoryArchiveTextFile( name, path.c_str() ); + if ( !file->failed() ) { + return file; + } + file->release(); + return 0; + } + virtual bool containsFile( const char* name ){ + UnixPath path( m_root.c_str() ); + path.push_filename( name ); + return file_readable( path.c_str() ); + } + virtual void forEachFile( VisitorFunc visitor, const char* root ){ + std::vector dirs; + UnixPath path( m_root.c_str() ); + path.push( root ); + dirs.push_back( directory_open( path.c_str() ) ); - bool is_directory = file_is_directory( path.c_str() ); + while ( !dirs.empty() && directory_good( dirs.back() ) ) + { + const char* name = directory_read_and_increment( dirs.back() ); - if ( !is_directory ) { - visitor.file( path_make_relative( path.c_str(), m_root.c_str() ) ); + if ( name == 0 ) { + directory_close( dirs.back() ); + dirs.pop_back(); + path.pop(); } + else if ( !string_equal( name, "." ) && !string_equal( name, ".." ) ) { + path.push_filename( name ); - path.pop(); + bool is_directory = file_is_directory( path.c_str() ); - if ( is_directory ) { - path.push( name ); - - if ( !visitor.directory( path_make_relative( path.c_str(), m_root.c_str() ), dirs.size() ) ) { - dirs.push_back( directory_open( path.c_str() ) ); + if ( !is_directory ) { + visitor.file( path_make_relative( path.c_str(), m_root.c_str() ) ); } - else{ - path.pop(); + + path.pop(); + + if ( is_directory ) { + path.push( name ); + + if ( !visitor.directory( path_make_relative( path.c_str(), m_root.c_str() ), dirs.size() ) ) { + dirs.push_back( directory_open( path.c_str() ) ); + } + else{ + path.pop(); + } } } } } -} }; Archive* OpenArchive( const char* name ){ @@ -124,39 +124,39 @@ Archive* OpenArchive( const char* name ){ class TestArchive { -class TestVisitor : public Archive::IVisitor -{ + class TestVisitor : public Archive::IVisitor + { + public: + virtual void visit( const char* name ){ + int bleh = 0; + } + }; public: -virtual void visit( const char* name ){ - int bleh = 0; -} -}; -public: -void test1(){ - Archive* archive = OpenArchive( "d:/quake/id1/" ); - ArchiveFile* file = archive->openFile( "quake101.wad" ); - if ( file != 0 ) { - char buffer[1024]; - file->getInputStream().read( buffer, 1024 ); - file->release(); + void test1(){ + Archive* archive = OpenArchive( "d:/quake/id1/" ); + ArchiveFile* file = archive->openFile( "quake101.wad" ); + if ( file != 0 ) { + char buffer[1024]; + file->getInputStream().read( buffer, 1024 ); + file->release(); + } + TestVisitor visitor; + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); + archive->release(); + } + void test2(){ + Archive* archive = OpenArchive( "d:/gtkradiant_root/baseq3/" ); + TestVisitor visitor; + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "textures" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "textures" ); + archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures" ); + archive->release(); + } + TestArchive(){ + test1(); + test2(); } - TestVisitor visitor; - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 0 ), "" ); - archive->release(); -} -void test2(){ - Archive* archive = OpenArchive( "d:/gtkradiant_root/baseq3/" ); - TestVisitor visitor; - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 2 ), "" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFiles, 1 ), "textures" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eDirectories, 1 ), "textures" ); - archive->forEachFile( Archive::VisitorFunc( &visitor, Archive::eFilesAndDirectories, 1 ), "textures" ); - archive->release(); -} -TestArchive(){ - test1(); - test2(); -} }; TestArchive g_test; diff --git a/plugins/vfspk3/vfs.cpp b/plugins/vfspk3/vfs.cpp index e7fb0369..94550347 100644 --- a/plugins/vfspk3/vfs.cpp +++ b/plugins/vfspk3/vfs.cpp @@ -158,48 +158,48 @@ inline void pathlist_prepend_unique( GSList*& pathlist, char* path ){ class DirectoryListVisitor : public Archive::Visitor { -GSList*& m_matches; -const char* m_directory; + GSList*& m_matches; + const char* m_directory; public: -DirectoryListVisitor( GSList*& matches, const char* directory ) - : m_matches( matches ), m_directory( directory ) -{} -void visit( const char* name ){ - const char* subname = path_make_relative( name, m_directory ); - if ( subname != name ) { - if ( subname[0] == '/' ) { - ++subname; + DirectoryListVisitor( GSList*& matches, const char* directory ) + : m_matches( matches ), m_directory( directory ) + {} + void visit( const char* name ){ + const char* subname = path_make_relative( name, m_directory ); + if ( subname != name ) { + if ( subname[0] == '/' ) { + ++subname; + } + char* dir = g_strdup( subname ); + char* last_char = dir + strlen( dir ); + if ( last_char != dir && *( --last_char ) == '/' ) { + *last_char = '\0'; + } + pathlist_prepend_unique( m_matches, dir ); } - char* dir = g_strdup( subname ); - char* last_char = dir + strlen( dir ); - if ( last_char != dir && *( --last_char ) == '/' ) { - *last_char = '\0'; - } - pathlist_prepend_unique( m_matches, dir ); } -} }; class FileListVisitor : public Archive::Visitor { -GSList*& m_matches; -const char* m_directory; -const char* m_extension; + GSList*& m_matches; + const char* m_directory; + const char* m_extension; public: -FileListVisitor( GSList*& matches, const char* directory, const char* extension ) - : m_matches( matches ), m_directory( directory ), m_extension( extension ) -{} -void visit( const char* name ){ - const char* subname = path_make_relative( name, m_directory ); - if ( subname != name ) { - if ( subname[0] == '/' ) { - ++subname; - } - if ( m_extension[0] == '*' || extension_equal( path_get_extension( subname ), m_extension ) ) { - pathlist_prepend_unique( m_matches, g_strdup( subname ) ); + FileListVisitor( GSList*& matches, const char* directory, const char* extension ) + : m_matches( matches ), m_directory( directory ), m_extension( extension ) + {} + void visit( const char* name ){ + const char* subname = path_make_relative( name, m_directory ); + if ( subname != name ) { + if ( subname[0] == '/' ) { + ++subname; + } + if ( m_extension[0] == '*' || extension_equal( path_get_extension( subname ), m_extension ) ) { + pathlist_prepend_unique( m_matches, g_strdup( subname ) ); + } } } -} }; static GSList* GetListInternal( const char *refdir, const char *ext, bool directories, std::size_t depth ){ @@ -269,9 +269,9 @@ static int string_compare_nocase_upper( const char* a, const char* b ){ class PakLess { public: -bool operator()( const CopiedString& self, const CopiedString& other ) const { - return string_compare_nocase_upper( self.c_str(), other.c_str() ) > 0; -} + bool operator()( const CopiedString& self, const CopiedString& other ) const { + return string_compare_nocase_upper( self.c_str(), other.c_str() ) > 0; + } }; typedef std::set Archives; @@ -474,7 +474,7 @@ int GetFileCount( const char *filename, int flag ){ for ( archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i ) { if ( ( ( *i ).is_pakfile && ( flag & VFS_SEARCH_PAK ) != 0 ) - || ( !( *i ).is_pakfile && ( flag & VFS_SEARCH_DIR ) != 0 ) ) { + || ( !( *i ).is_pakfile && ( flag & VFS_SEARCH_DIR ) != 0 ) ) { if ( ( *i ).archive->containsFile( fixed ) ) { ++count; } @@ -583,113 +583,113 @@ const char* FindPath( const char* absolute ){ class Quake3FileSystem : public VirtualFileSystem { public: -void initDirectory( const char *path ){ - InitDirectory( path, FileSystemQ3API_getArchiveModules() ); -} -void initialise(){ - globalOutputStream() << "filesystem initialised\n"; - g_observers.realise(); -} -void shutdown(){ - g_observers.unrealise(); - globalOutputStream() << "filesystem shutdown\n"; - Shutdown(); -} - -int getFileCount( const char *filename, int flags ){ - return GetFileCount( filename, flags ); -} -ArchiveFile* openFile( const char* filename ){ - return OpenFile( filename ); -} -ArchiveTextFile* openTextFile( const char* filename ){ - return OpenTextFile( filename ); -} -std::size_t loadFile( const char *filename, void **buffer ){ - return LoadFile( filename, buffer, 0 ); -} -void freeFile( void *p ){ - FreeFile( p ); -} - -void forEachDirectory( const char* basedir, const FileNameCallback& callback, std::size_t depth ){ - GSList* list = GetDirList( basedir, depth ); - - for ( GSList* i = list; i != 0; i = g_slist_next( i ) ) - { - callback( reinterpret_cast( ( *i ).data ) ); + void initDirectory( const char *path ){ + InitDirectory( path, FileSystemQ3API_getArchiveModules() ); + } + void initialise(){ + globalOutputStream() << "filesystem initialised\n"; + g_observers.realise(); + } + void shutdown(){ + g_observers.unrealise(); + globalOutputStream() << "filesystem shutdown\n"; + Shutdown(); } - ClearFileDirList( &list ); -} -void forEachFile( const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth ){ - GSList* list = GetFileList( basedir, extension, depth ); - - for ( GSList* i = list; i != 0; i = g_slist_next( i ) ) - { - const char* name = reinterpret_cast( ( *i ).data ); - if ( extension_equal( path_get_extension( name ), extension ) ) { - callback( name ); - } + int getFileCount( const char *filename, int flags ){ + return GetFileCount( filename, flags ); + } + ArchiveFile* openFile( const char* filename ){ + return OpenFile( filename ); + } + ArchiveTextFile* openTextFile( const char* filename ){ + return OpenTextFile( filename ); + } + std::size_t loadFile( const char *filename, void **buffer ){ + return LoadFile( filename, buffer, 0 ); + } + void freeFile( void *p ){ + FreeFile( p ); } - ClearFileDirList( &list ); -} -GSList* getDirList( const char *basedir ){ - return GetDirList( basedir, 1 ); -} -GSList* getFileList( const char *basedir, const char *extension ){ - return GetFileList( basedir, extension, 1 ); -} -void clearFileDirList( GSList **lst ){ - ClearFileDirList( lst ); -} + void forEachDirectory( const char* basedir, const FileNameCallback& callback, std::size_t depth ){ + GSList* list = GetDirList( basedir, depth ); -const char* findFile( const char *name ){ - return FindFile( name ); -} -const char* findRoot( const char *name ){ - return FindPath( name ); -} - -void attach( ModuleObserver& observer ){ - g_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - g_observers.detach( observer ); -} - -Archive* getArchive( const char* archiveName, bool pakonly ){ - for ( archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i ) - { - if ( pakonly && !( *i ).is_pakfile ) { - continue; + for ( GSList* i = list; i != 0; i = g_slist_next( i ) ) + { + callback( reinterpret_cast( ( *i ).data ) ); } - if ( path_equal( ( *i ).name.c_str(), archiveName ) ) { - return ( *i ).archive; - } - } - return 0; -} -void forEachArchive( const ArchiveNameCallback& callback, bool pakonly, bool reverse ){ - if ( reverse ) { - g_archives.reverse(); + ClearFileDirList( &list ); } + void forEachFile( const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth ){ + GSList* list = GetFileList( basedir, extension, depth ); - for ( archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i ) - { - if ( pakonly && !( *i ).is_pakfile ) { - continue; + for ( GSList* i = list; i != 0; i = g_slist_next( i ) ) + { + const char* name = reinterpret_cast( ( *i ).data ); + if ( extension_equal( path_get_extension( name ), extension ) ) { + callback( name ); + } } - callback( ( *i ).name.c_str() ); + ClearFileDirList( &list ); + } + GSList* getDirList( const char *basedir ){ + return GetDirList( basedir, 1 ); + } + GSList* getFileList( const char *basedir, const char *extension ){ + return GetFileList( basedir, extension, 1 ); + } + void clearFileDirList( GSList **lst ){ + ClearFileDirList( lst ); } - if ( reverse ) { - g_archives.reverse(); + const char* findFile( const char *name ){ + return FindFile( name ); + } + const char* findRoot( const char *name ){ + return FindPath( name ); + } + + void attach( ModuleObserver& observer ){ + g_observers.attach( observer ); + } + void detach( ModuleObserver& observer ){ + g_observers.detach( observer ); + } + + Archive* getArchive( const char* archiveName, bool pakonly ){ + for ( archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i ) + { + if ( pakonly && !( *i ).is_pakfile ) { + continue; + } + + if ( path_equal( ( *i ).name.c_str(), archiveName ) ) { + return ( *i ).archive; + } + } + return 0; + } + void forEachArchive( const ArchiveNameCallback& callback, bool pakonly, bool reverse ){ + if ( reverse ) { + g_archives.reverse(); + } + + for ( archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i ) + { + if ( pakonly && !( *i ).is_pakfile ) { + continue; + } + + callback( ( *i ).name.c_str() ); + } + + if ( reverse ) { + g_archives.reverse(); + } } -} }; Quake3FileSystem g_Quake3FileSystem; diff --git a/plugins/vfspk3/vfspk3.cpp b/plugins/vfspk3/vfspk3.cpp index 478ce8f1..5b19b449 100644 --- a/plugins/vfspk3/vfspk3.cpp +++ b/plugins/vfspk3/vfspk3.cpp @@ -32,33 +32,33 @@ class FileSystemDependencies : public GlobalRadiantModuleRef { -ArchiveModulesRef m_archive_modules; + ArchiveModulesRef m_archive_modules; public: -FileSystemDependencies() : - m_archive_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "archivetypes" ) ){ -} -ArchiveModules& getArchiveModules(){ - return m_archive_modules.get(); -} + FileSystemDependencies() : + m_archive_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "archivetypes" ) ){ + } + ArchiveModules& getArchiveModules(){ + return m_archive_modules.get(); + } }; class FileSystemQ3API { -VirtualFileSystem* m_filesystemq3; + VirtualFileSystem* m_filesystemq3; public: -typedef VirtualFileSystem Type; -STRING_CONSTANT( Name, "*" ); + typedef VirtualFileSystem Type; + STRING_CONSTANT( Name, "*" ); -FileSystemQ3API(){ - FileSystem_Init(); - m_filesystemq3 = &GetFileSystem(); -} -~FileSystemQ3API(){ - FileSystem_Shutdown(); -} -VirtualFileSystem* getTable(){ - return m_filesystemq3; -} + FileSystemQ3API(){ + FileSystem_Init(); + m_filesystemq3 = &GetFileSystem(); + } + ~FileSystemQ3API(){ + FileSystem_Shutdown(); + } + VirtualFileSystem* getTable(){ + return m_filesystemq3; + } }; typedef SingletonModule FileSystemQ3Module; diff --git a/radiant/brush.cpp b/radiant/brush.cpp index 8b8d2779..3d1fa22f 100644 --- a/radiant/brush.cpp +++ b/radiant/brush.cpp @@ -57,36 +57,36 @@ struct SListNode class ProximalVertex { public: -const SListNode* m_vertices; + const SListNode* m_vertices; -ProximalVertex( const SListNode* next ) - : m_vertices( next ){ -} + ProximalVertex( const SListNode* next ) + : m_vertices( next ){ + } -bool operator<( const ProximalVertex& other ) const { - if ( !( operator==( other ) ) ) { - return m_vertices < other.m_vertices; - } - return false; -} -bool operator==( const ProximalVertex& other ) const { - const SListNode* v = m_vertices; - std::size_t DEBUG_LOOP = 0; - do - { - if ( v == other.m_vertices ) { - return true; + bool operator<( const ProximalVertex& other ) const { + if ( !( operator==( other ) ) ) { + return m_vertices < other.m_vertices; } - v = v->m_next; - //ASSERT_MESSAGE(DEBUG_LOOP < c_brush_maxFaces, "infinite loop"); - if ( !( DEBUG_LOOP < c_brush_maxFaces ) ) { - break; - } - ++DEBUG_LOOP; + return false; + } + bool operator==( const ProximalVertex& other ) const { + const SListNode* v = m_vertices; + std::size_t DEBUG_LOOP = 0; + do + { + if ( v == other.m_vertices ) { + return true; + } + v = v->m_next; + //ASSERT_MESSAGE(DEBUG_LOOP < c_brush_maxFaces, "infinite loop"); + if ( !( DEBUG_LOOP < c_brush_maxFaces ) ) { + break; + } + ++DEBUG_LOOP; + } + while ( v != m_vertices ); + return false; } - while ( v != m_vertices ); - return false; -} }; typedef Array ProximalVertexArray; @@ -320,23 +320,23 @@ void Brush::buildBRep(){ class FaceFilterWrapper : public Filter { -FaceFilter& m_filter; -bool m_active; -bool m_invert; + FaceFilter& m_filter; + bool m_active; + bool m_invert; public: -FaceFilterWrapper( FaceFilter& filter, bool invert ) : - m_filter( filter ), - m_invert( invert ){ -} -void setActive( bool active ){ - m_active = active; -} -bool active(){ - return m_active; -} -bool filter( const Face& face ){ - return m_invert ^ m_filter.filter( face ); -} + FaceFilterWrapper( FaceFilter& filter, bool invert ) : + m_filter( filter ), + m_invert( invert ){ + } + void setActive( bool active ){ + m_active = active; + } + bool active(){ + return m_active; + } + bool filter( const Face& face ){ + return m_invert ^ m_filter.filter( face ); + } }; @@ -361,21 +361,21 @@ bool face_filtered( Face& face ){ class BrushFilterWrapper : public Filter { -bool m_active; -bool m_invert; -BrushFilter& m_filter; + bool m_active; + bool m_invert; + BrushFilter& m_filter; public: -BrushFilterWrapper( BrushFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ -} -void setActive( bool active ){ - m_active = active; -} -bool active(){ - return m_active; -} -bool filter( const Brush& brush ){ - return m_invert ^ m_filter.filter( brush ); -} + BrushFilterWrapper( BrushFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ + } + void setActive( bool active ){ + m_active = active; + } + bool active(){ + return m_active; + } + bool filter( const Brush& brush ){ + return m_invert ^ m_filter.filter( brush ); + } }; @@ -406,8 +406,8 @@ public: const Brush::VertexModeVertex* const m_v[3]; bool m_transformed; VertexModePlane( const Plane3& plane, const Face* face, - const Brush::VertexModeVertex* v1, const Brush::VertexModeVertex* v2, const Brush::VertexModeVertex* v3, - bool transformed ) : m_plane( plane ), m_face( face ), m_v{ v1, v2, v3 }, m_transformed( transformed ){ + const Brush::VertexModeVertex* v1, const Brush::VertexModeVertex* v2, const Brush::VertexModeVertex* v3, + bool transformed ) : m_plane( plane ), m_face( face ), m_v{ v1, v2, v3 }, m_transformed( transformed ){ } }; @@ -449,7 +449,7 @@ const Face* vertex_mode_find_common_face( const Brush::VertexModeVertex& v1, con const Face* face = 0; for( const auto& i : v1.m_faces ){ if( std::find( v2.m_faces.begin(), v2.m_faces.end(), i ) != v2.m_faces.end() - && std::find( v3.m_faces.begin(), v3.m_faces.end(), i ) != v3.m_faces.end() ){ + && std::find( v3.m_faces.begin(), v3.m_faces.end(), i ) != v3.m_faces.end() ){ face = i; break; } @@ -464,8 +464,8 @@ void Brush::vertexModeBuildHull( bool allTransformed /*= false*/ ){ pointCloud.reserve( m_vertexModeVertices.size() ); for( auto& i : m_vertexModeVertices ){ pointCloud.push_back( quickhull::Vector3( static_cast( i.m_vertexTransformed.x() ), - static_cast( i.m_vertexTransformed.y() ), - static_cast( i.m_vertexTransformed.z() ) ) ); + static_cast( i.m_vertexTransformed.y() ), + static_cast( i.m_vertexTransformed.z() ) ) ); } auto hull = quickhull.getConvexHull( pointCloud, true, true ); const auto& indexBuffer = hull.getIndexBuffer(); @@ -509,8 +509,8 @@ void Brush::vertexModeBuildHull( bool allTransformed /*= false*/ ){ Matrix4 local2tex; Texdef_Construct_local2tex( face.getTexdef().m_projection, face.getShader().width(), face.getShader().height(), face.getPlane().plane3().normal(), local2tex ); const DoubleVector3 st[3]{ matrix4_transformed_point( local2tex, i.m_v[0]->m_vertex ), - matrix4_transformed_point( local2tex, i.m_v[1]->m_vertex ), - matrix4_transformed_point( local2tex, i.m_v[2]->m_vertex ) }; + matrix4_transformed_point( local2tex, i.m_v[1]->m_vertex ), + matrix4_transformed_point( local2tex, i.m_v[2]->m_vertex ) }; const DoubleVector3 points[3]{ i.m_v[0]->m_vertexTransformed, i.m_v[1]->m_vertexTransformed, i.m_v[2]->m_vertexTransformed }; Texdef_from_ST( projection, points, st, face.getShader().width(), face.getShader().height() ); } diff --git a/radiant/brush.h b/radiant/brush.h index b84f97af..6f3e1c31 100644 --- a/radiant/brush.h +++ b/radiant/brush.h @@ -76,7 +76,7 @@ const unsigned int BRUSH_DETAIL_MASK = ( 1 << BRUSH_DETAIL_FLAG ); inline bool texdef_sane( const texdef_t& texdef ){ return fabs( texdef.shift[0] ) < ( 1 << 16 ) - && fabs( texdef.shift[1] ) < ( 1 << 16 ); + && fabs( texdef.shift[1] ) < ( 1 << 16 ); } inline void Winding_DrawWireframe( const Winding& winding ){ @@ -241,39 +241,39 @@ inline void planepts_snap( PlanePoints planepts, double snap ){ inline PointVertex pointvertex_for_planept( const DoubleVector3& point, const Colour4b& colour ){ return PointVertex( - Vertex3f( - static_cast( point.x() ), - static_cast( point.y() ), - static_cast( point.z() ) - ), - colour - ); + Vertex3f( + static_cast( point.x() ), + static_cast( point.y() ), + static_cast( point.z() ) + ), + colour + ); } inline PointVertex pointvertex_for_windingpoint( const Vector3& point, const Colour4b& colour ){ return PointVertex( - vertex3f_for_vector3( point ), - colour - ); + vertex3f_for_vector3( point ), + colour + ); } inline DepthTestedPointVertex depthtested_pointvertex_for_windingpoint( const Vector3& point, const Colour4b& colour ){ return DepthTestedPointVertex( - vertex3f_for_vector3( point ), - colour - ); + vertex3f_for_vector3( point ), + colour + ); } inline bool check_plane_is_integer( const PlanePoints& planePoints ){ return !float_is_integer( planePoints[0][0] ) - || !float_is_integer( planePoints[0][1] ) - || !float_is_integer( planePoints[0][2] ) - || !float_is_integer( planePoints[1][0] ) - || !float_is_integer( planePoints[1][1] ) - || !float_is_integer( planePoints[1][2] ) - || !float_is_integer( planePoints[2][0] ) - || !float_is_integer( planePoints[2][1] ) - || !float_is_integer( planePoints[2][2] ); + || !float_is_integer( planePoints[0][1] ) + || !float_is_integer( planePoints[0][2] ) + || !float_is_integer( planePoints[1][0] ) + || !float_is_integer( planePoints[1][1] ) + || !float_is_integer( planePoints[1][2] ) + || !float_is_integer( planePoints[2][0] ) + || !float_is_integer( planePoints[2][1] ) + || !float_is_integer( planePoints[2][2] ); } inline void brush_check_shader( const char* name ){ @@ -285,24 +285,24 @@ inline void brush_check_shader( const char* name ){ class FaceShaderObserver { public: -virtual void realiseShader() = 0; -virtual void unrealiseShader() = 0; + virtual void realiseShader() = 0; + virtual void unrealiseShader() = 0; }; class FaceShaderObserverRealise { public: -void operator()( FaceShaderObserver& observer ) const { - observer.realiseShader(); -} + void operator()( FaceShaderObserver& observer ) const { + observer.realiseShader(); + } }; class FaceShaderObserverUnrealise { public: -void operator()( FaceShaderObserver& observer ) const { - observer.unrealiseShader(); -} + void operator()( FaceShaderObserver& observer ) const { + observer.unrealiseShader(); + } }; typedef ReferencePair FaceShaderObserverPair; @@ -311,18 +311,18 @@ typedef ReferencePair FaceShaderObserverPair; class ContentsFlagsValue { public: -ContentsFlagsValue(){ -} -ContentsFlagsValue( int surfaceFlags, int contentFlags, int value, bool specified ) : - m_surfaceFlags( surfaceFlags ), - m_contentFlags( contentFlags ), - m_value( value ), - m_specified( specified ){ -} -int m_surfaceFlags; -int m_contentFlags; -int m_value; -bool m_specified; + ContentsFlagsValue(){ + } + ContentsFlagsValue( int surfaceFlags, int contentFlags, int value, bool specified ) : + m_surfaceFlags( surfaceFlags ), + m_contentFlags( contentFlags ), + m_value( value ), + m_specified( specified ){ + } + int m_surfaceFlags; + int m_contentFlags; + int m_value; + bool m_specified; }; inline void ContentsFlagsValue_assignMasked( ContentsFlagsValue& flags, const ContentsFlagsValue& other ){ @@ -341,145 +341,145 @@ inline void ContentsFlagsValue_assignMasked( ContentsFlagsValue& flags, const Co class FaceShader : public ModuleObserver { public: -class SavedState -{ -public: -CopiedString m_shader; -ContentsFlagsValue m_flags; + class SavedState + { + public: + CopiedString m_shader; + ContentsFlagsValue m_flags; -SavedState( const FaceShader& faceShader ){ - m_shader = faceShader.getShader(); - m_flags = faceShader.m_flags; -} + SavedState( const FaceShader& faceShader ){ + m_shader = faceShader.getShader(); + m_flags = faceShader.m_flags; + } -void exportState( FaceShader& faceShader ) const { - faceShader.setShader( m_shader.c_str() ); - //faceShader.setFlags( m_flags ); //detail, structural flags aren't undoable with this - faceShader.m_flags = m_flags; -} -}; + void exportState( FaceShader& faceShader ) const { + faceShader.setShader( m_shader.c_str() ); + //faceShader.setFlags( m_flags ); //detail, structural flags aren't undoable with this + faceShader.m_flags = m_flags; + } + }; -CopiedString m_shader; -Shader* m_state; -ContentsFlagsValue m_flags; -FaceShaderObserverPair m_observers; -bool m_instanced; -bool m_realised; + CopiedString m_shader; + Shader* m_state; + ContentsFlagsValue m_flags; + FaceShaderObserverPair m_observers; + bool m_instanced; + bool m_realised; -FaceShader( const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue( 0, 0, 0, false ) ) : - m_shader( shader ), - m_state( 0 ), - m_flags( flags ), - m_instanced( false ), - m_realised( false ){ - captureShader(); -} -~FaceShader(){ - releaseShader(); -} + FaceShader( const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue( 0, 0, 0, false ) ) : + m_shader( shader ), + m_state( 0 ), + m_flags( flags ), + m_instanced( false ), + m_realised( false ){ + captureShader(); + } + ~FaceShader(){ + releaseShader(); + } // copy-construction not supported -FaceShader( const FaceShader& other ); + FaceShader( const FaceShader& other ); -void instanceAttach(){ - m_instanced = true; - m_state->incrementUsed(); -} -void instanceDetach(){ - m_state->decrementUsed(); - m_instanced = false; -} - -void captureShader(){ - ASSERT_MESSAGE( m_state == 0, "shader cannot be captured" ); - brush_check_shader( m_shader.c_str() ); - m_state = GlobalShaderCache().capture( m_shader.c_str() ); - m_state->attach( *this ); -} -void releaseShader(){ - ASSERT_MESSAGE( m_state != 0, "shader cannot be released" ); - m_state->detach( *this ); - GlobalShaderCache().release( m_shader.c_str() ); - m_state = 0; -} - -void realise(){ - ASSERT_MESSAGE( !m_realised, "FaceTexdef::realise: already realised" ); - m_realised = true; - m_observers.forEach( FaceShaderObserverRealise() ); -} -void unrealise(){ - ASSERT_MESSAGE( m_realised, "FaceTexdef::unrealise: already unrealised" ); - m_observers.forEach( FaceShaderObserverUnrealise() ); - m_realised = false; -} - -void attach( FaceShaderObserver& observer ){ - m_observers.attach( observer ); - if ( m_realised ) { - observer.realiseShader(); - } -} - -void detach( FaceShaderObserver& observer ){ - if ( m_realised ) { - observer.unrealiseShader(); - } - m_observers.detach( observer ); -} - -const char* getShader() const { - return m_shader.c_str(); -} -void setShader( const char* name ){ - if ( m_instanced ) { - m_state->decrementUsed(); - } - releaseShader(); - m_shader = name; - captureShader(); - if ( m_instanced ) { + void instanceAttach(){ + m_instanced = true; m_state->incrementUsed(); } -} -ContentsFlagsValue getFlags() const { - ASSERT_MESSAGE( m_realised, "FaceShader::getFlags: flags not valid when unrealised" ); - if ( !m_flags.m_specified ) { - return ContentsFlagsValue( - m_state->getTexture().surfaceFlags, - m_state->getTexture().contentFlags, - m_state->getTexture().value, - true - ); + void instanceDetach(){ + m_state->decrementUsed(); + m_instanced = false; } - return m_flags; -} -void setFlags( const ContentsFlagsValue& flags ){ - ASSERT_MESSAGE( m_realised, "FaceShader::setFlags: flags not valid when unrealised" ); - ContentsFlagsValue_assignMasked( m_flags, flags ); -} -Shader* state() const { - return m_state; -} + void captureShader(){ + ASSERT_MESSAGE( m_state == 0, "shader cannot be captured" ); + brush_check_shader( m_shader.c_str() ); + m_state = GlobalShaderCache().capture( m_shader.c_str() ); + m_state->attach( *this ); + } + void releaseShader(){ + ASSERT_MESSAGE( m_state != 0, "shader cannot be released" ); + m_state->detach( *this ); + GlobalShaderCache().release( m_shader.c_str() ); + m_state = 0; + } -std::size_t width() const { - if ( m_realised ) { - return m_state->getTexture().width; + void realise(){ + ASSERT_MESSAGE( !m_realised, "FaceTexdef::realise: already realised" ); + m_realised = true; + m_observers.forEach( FaceShaderObserverRealise() ); } - return 1; -} -std::size_t height() const { - if ( m_realised ) { - return m_state->getTexture().height; + void unrealise(){ + ASSERT_MESSAGE( m_realised, "FaceTexdef::unrealise: already unrealised" ); + m_observers.forEach( FaceShaderObserverUnrealise() ); + m_realised = false; } - return 1; -} -unsigned int shaderFlags() const { - if ( m_realised ) { - return m_state->getFlags(); + + void attach( FaceShaderObserver& observer ){ + m_observers.attach( observer ); + if ( m_realised ) { + observer.realiseShader(); + } + } + + void detach( FaceShaderObserver& observer ){ + if ( m_realised ) { + observer.unrealiseShader(); + } + m_observers.detach( observer ); + } + + const char* getShader() const { + return m_shader.c_str(); + } + void setShader( const char* name ){ + if ( m_instanced ) { + m_state->decrementUsed(); + } + releaseShader(); + m_shader = name; + captureShader(); + if ( m_instanced ) { + m_state->incrementUsed(); + } + } + ContentsFlagsValue getFlags() const { + ASSERT_MESSAGE( m_realised, "FaceShader::getFlags: flags not valid when unrealised" ); + if ( !m_flags.m_specified ) { + return ContentsFlagsValue( + m_state->getTexture().surfaceFlags, + m_state->getTexture().contentFlags, + m_state->getTexture().value, + true + ); + } + return m_flags; + } + void setFlags( const ContentsFlagsValue& flags ){ + ASSERT_MESSAGE( m_realised, "FaceShader::setFlags: flags not valid when unrealised" ); + ContentsFlagsValue_assignMasked( m_flags, flags ); + } + + Shader* state() const { + return m_state; + } + + std::size_t width() const { + if ( m_realised ) { + return m_state->getTexture().width; + } + return 1; + } + std::size_t height() const { + if ( m_realised ) { + return m_state->getTexture().height; + } + return 1; + } + unsigned int shaderFlags() const { + if ( m_realised ) { + return m_state->getFlags(); + } + return 0; } - return 0; -} }; @@ -488,151 +488,151 @@ unsigned int shaderFlags() const { class FaceTexdef : public FaceShaderObserver { // not copyable -FaceTexdef( const FaceTexdef& other ); + FaceTexdef( const FaceTexdef& other ); // not assignable -FaceTexdef& operator=( const FaceTexdef& other ); + FaceTexdef& operator=( const FaceTexdef& other ); public: -class SavedState -{ -public: -TextureProjection m_projection; + class SavedState + { + public: + TextureProjection m_projection; -SavedState( const FaceTexdef& faceTexdef ){ - m_projection = faceTexdef.m_projection; -} + SavedState( const FaceTexdef& faceTexdef ){ + m_projection = faceTexdef.m_projection; + } -void exportState( FaceTexdef& faceTexdef ) const { - Texdef_Assign( faceTexdef.m_projection, m_projection ); -} -}; + void exportState( FaceTexdef& faceTexdef ) const { + Texdef_Assign( faceTexdef.m_projection, m_projection ); + } + }; -FaceShader& m_shader; -TextureProjection m_projection; -bool m_projectionInitialised; -bool m_scaleApplied; + FaceShader& m_shader; + TextureProjection m_projection; + bool m_projectionInitialised; + bool m_scaleApplied; -FaceTexdef( - FaceShader& shader, - const TextureProjection& projection, - bool projectionInitialised = true + FaceTexdef( + FaceShader& shader, + const TextureProjection& projection, + bool projectionInitialised = true ) : - m_shader( shader ), - m_projection( projection ), - m_projectionInitialised( projectionInitialised ), - m_scaleApplied( false ){ - m_shader.attach( *this ); -} -~FaceTexdef(){ - m_shader.detach( *this ); -} + m_shader( shader ), + m_projection( projection ), + m_projectionInitialised( projectionInitialised ), + m_scaleApplied( false ){ + m_shader.attach( *this ); + } + ~FaceTexdef(){ + m_shader.detach( *this ); + } -void addScale(){ - ASSERT_MESSAGE( !m_scaleApplied, "texture scale aready added" ); - m_scaleApplied = true; - m_projection.m_brushprimit_texdef.addScale( m_shader.width(), m_shader.height() ); -} -void removeScale(){ - ASSERT_MESSAGE( m_scaleApplied, "texture scale aready removed" ); - m_scaleApplied = false; - m_projection.m_brushprimit_texdef.removeScale( m_shader.width(), m_shader.height() ); -} + void addScale(){ + ASSERT_MESSAGE( !m_scaleApplied, "texture scale aready added" ); + m_scaleApplied = true; + m_projection.m_brushprimit_texdef.addScale( m_shader.width(), m_shader.height() ); + } + void removeScale(){ + ASSERT_MESSAGE( m_scaleApplied, "texture scale aready removed" ); + m_scaleApplied = false; + m_projection.m_brushprimit_texdef.removeScale( m_shader.width(), m_shader.height() ); + } -void realiseShader(){ - if ( m_projectionInitialised && !m_scaleApplied ) { + void realiseShader(){ + if ( m_projectionInitialised && !m_scaleApplied ) { + addScale(); + } + } + void unrealiseShader(){ + if ( m_projectionInitialised && m_scaleApplied ) { + removeScale(); + } + } + + void setTexdef( const TextureProjection& projection, bool setBasis ){ + removeScale(); + Texdef_Assign( m_projection, projection, setBasis ); addScale(); } -} -void unrealiseShader(){ - if ( m_projectionInitialised && m_scaleApplied ) { + + void setTexdef( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ){ removeScale(); + Texdef_Assign( m_projection, hShift, vShift, hScale, vScale, rotation ); +// if( hShift || vShift ){ +// Texdef_normalise( m_projection, m_shader.width(), m_shader.height() ); +// } + addScale(); } -} -void setTexdef( const TextureProjection& projection, bool setBasis ){ - removeScale(); - Texdef_Assign( m_projection, projection, setBasis ); - addScale(); -} - -void setTexdef( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ){ - removeScale(); - Texdef_Assign( m_projection, hShift, vShift, hScale, vScale, rotation ); -// if( hShift || vShift ){ + void shift( float s, float t ){ + ASSERT_MESSAGE( texdef_sane( m_projection.m_texdef ), "FaceTexdef::shift: bad texdef" ); + removeScale(); + Texdef_Shift( m_projection, s, t ); // Texdef_normalise( m_projection, m_shader.width(), m_shader.height() ); -// } - addScale(); -} + addScale(); + } -void shift( float s, float t ){ - ASSERT_MESSAGE( texdef_sane( m_projection.m_texdef ), "FaceTexdef::shift: bad texdef" ); - removeScale(); - Texdef_Shift( m_projection, s, t ); -// Texdef_normalise( m_projection, m_shader.width(), m_shader.height() ); - addScale(); -} + void scale( float s, float t ){ + removeScale(); + Texdef_Scale( m_projection, s, t ); + addScale(); + } -void scale( float s, float t ){ - removeScale(); - Texdef_Scale( m_projection, s, t ); - addScale(); -} - -void rotate( float angle ){ - removeScale(); - Texdef_Rotate( m_projection, angle ); - addScale(); -} + void rotate( float angle ){ + removeScale(); + Texdef_Rotate( m_projection, angle ); + addScale(); + } ///ProjectTexture along 'direction' with parameters, defined by texdef_t -void ProjectTexture( const Plane3& plane, const texdef_t& texdef, const Vector3* direction ){ - Texdef_ProjectTexture( m_projection, m_shader.width(), m_shader.height(), plane, texdef, direction ); -} + void ProjectTexture( const Plane3& plane, const texdef_t& texdef, const Vector3* direction ){ + Texdef_ProjectTexture( m_projection, m_shader.width(), m_shader.height(), plane, texdef, direction ); + } ///ProjectTexture along 'normal' with parameters, defined by TextureProjection -void ProjectTexture( const Plane3& plane, const TextureProjection& projection, const Vector3& normal ){ - Texdef_ProjectTexture( m_projection, m_shader.width(), m_shader.height(), plane, projection, normal ); -} + void ProjectTexture( const Plane3& plane, const TextureProjection& projection, const Vector3& normal ){ + Texdef_ProjectTexture( m_projection, m_shader.width(), m_shader.height(), plane, projection, normal ); + } -void Convert( TexdefTypeId in, TexdefTypeId out, const Plane3& plane ){ - Texdef_Convert( in, out, plane, m_projection, m_shader.width(), m_shader.height() ); - m_scaleApplied = true; -} + void Convert( TexdefTypeId in, TexdefTypeId out, const Plane3& plane ){ + Texdef_Convert( in, out, plane, m_projection, m_shader.width(), m_shader.height() ); + m_scaleApplied = true; + } -void fit( const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat, bool only_dimension ){ - Texdef_FitTexture( m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat, only_dimension ); -} + void fit( const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat, bool only_dimension ){ + Texdef_FitTexture( m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat, only_dimension ); + } -void emitTextureCoordinates( Winding& winding, const Vector3& normal, const Matrix4& localToWorld ){ - Texdef_EmitTextureCoordinates( m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld ); -} + void emitTextureCoordinates( Winding& winding, const Vector3& normal, const Matrix4& localToWorld ){ + Texdef_EmitTextureCoordinates( m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld ); + } -void transform( const Plane3& plane, const Matrix4& matrix ){ - removeScale(); - Texdef_transformLocked( m_projection, m_shader.width(), m_shader.height(), plane, matrix ); - addScale(); -} + void transform( const Plane3& plane, const Matrix4& matrix ){ + removeScale(); + Texdef_transformLocked( m_projection, m_shader.width(), m_shader.height(), plane, matrix ); + addScale(); + } -TextureProjection normalised() const { - brushprimit_texdef_t tmp( m_projection.m_brushprimit_texdef ); - tmp.removeScale( m_shader.width(), m_shader.height() ); - return TextureProjection( m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t ); -} + TextureProjection normalised() const { + brushprimit_texdef_t tmp( m_projection.m_brushprimit_texdef ); + tmp.removeScale( m_shader.width(), m_shader.height() ); + return TextureProjection( m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t ); + } #if 0 /* axial projection */ -void setBasis( const Vector3& normal ){ - Matrix4 basis; - Normal_GetTransform( normal, basis ); - m_projection.m_basis_s = Vector3( basis.xx(), basis.yx(), basis.zx() ); - m_projection.m_basis_t = Vector3( -basis.xy(), -basis.yy(), -basis.zy() ); -} + void setBasis( const Vector3& normal ){ + Matrix4 basis; + Normal_GetTransform( normal, basis ); + m_projection.m_basis_s = Vector3( basis.xx(), basis.yx(), basis.zx() ); + m_projection.m_basis_t = Vector3( -basis.xy(), -basis.yy(), -basis.zy() ); + } #else /* face projection */ -void setBasis( const Vector3& normal ){ - ComputeAxisBase( normal, m_projection.m_basis_s, m_projection.m_basis_t ); -} + void setBasis( const Vector3& normal ){ + ComputeAxisBase( normal, m_projection.m_basis_s, m_projection.m_basis_t ); + } #endif }; inline void planepts_print( const PlanePoints& planePoints, TextOutputStream& ostream ){ ostream << "( " << planePoints[0][0] << " " << planePoints[0][1] << " " << planePoints[0][2] << " ) " - << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) " - << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )"; + << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) " + << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )"; } @@ -651,202 +651,202 @@ inline Plane3 Plane3_applyTransform( const Plane3& plane, const Matrix4& matrix class FacePlane { -PlanePoints m_planepts; -Plane3 m_planeCached; -Plane3 m_plane; + PlanePoints m_planepts; + Plane3 m_planeCached; + Plane3 m_plane; public: -Vector3 m_funcStaticOrigin; + Vector3 m_funcStaticOrigin; -static EBrushType m_type; + static EBrushType m_type; -static bool isDoom3Plane(){ - return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4; -} - -class SavedState -{ -public: -PlanePoints m_planepts; -Plane3 m_plane; - -SavedState( const FacePlane& facePlane ){ - if ( facePlane.isDoom3Plane() ) { - m_plane = facePlane.m_plane; + static bool isDoom3Plane(){ + return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4; } - else + + class SavedState { - planepts_assign( m_planepts, facePlane.planePoints() ); - } -} + public: + PlanePoints m_planepts; + Plane3 m_plane; -void exportState( FacePlane& facePlane ) const { - if ( facePlane.isDoom3Plane() ) { - facePlane.m_plane = m_plane; - facePlane.updateTranslated(); - } - else - { - planepts_assign( facePlane.planePoints(), m_planepts ); - facePlane.MakePlane(); - } -} -}; - -FacePlane() : m_funcStaticOrigin( 0, 0, 0 ){ -} -FacePlane( const FacePlane& other ) : m_funcStaticOrigin( 0, 0, 0 ){ - if ( !isDoom3Plane() ) { - planepts_assign( m_planepts, other.m_planepts ); - MakePlane(); - } - else - { - m_plane = other.m_plane; - updateTranslated(); - } -} -FacePlane& operator=( const FacePlane& ) = default; - -void MakePlane(){ - if ( !isDoom3Plane() ) { -#if 0 - if ( check_plane_is_integer( m_planepts ) ) { - globalErrorStream() << "non-integer planepts: "; - planepts_print( m_planepts, globalErrorStream() ); - globalErrorStream() << "\n"; - } -#endif - m_planeCached = plane3_for_points( m_planepts ); - } -} - -void reverse(){ - if ( !isDoom3Plane() ) { - vector3_swap( m_planepts[0], m_planepts[2] ); - MakePlane(); - } - else - { - m_planeCached = plane3_flipped( m_plane ); - updateSource(); - } -} -void transform( const Matrix4& matrix, bool mirror ){ - if ( !isDoom3Plane() ) { - -#if 0 - bool off = check_plane_is_integer( planePoints() ); -#endif - - matrix4_transform_point( matrix, m_planepts[0] ); - matrix4_transform_point( matrix, m_planepts[1] ); - matrix4_transform_point( matrix, m_planepts[2] ); - - if ( mirror ) { - reverse(); - } - -#if 0 - if ( check_plane_is_integer( planePoints() ) ) { - if ( !off ) { - globalErrorStream() << "caused by transform\n"; + SavedState( const FacePlane& facePlane ){ + if ( facePlane.isDoom3Plane() ) { + m_plane = facePlane.m_plane; + } + else + { + planepts_assign( m_planepts, facePlane.planePoints() ); } } + + void exportState( FacePlane& facePlane ) const { + if ( facePlane.isDoom3Plane() ) { + facePlane.m_plane = m_plane; + facePlane.updateTranslated(); + } + else + { + planepts_assign( facePlane.planePoints(), m_planepts ); + facePlane.MakePlane(); + } + } + }; + + FacePlane() : m_funcStaticOrigin( 0, 0, 0 ){ + } + FacePlane( const FacePlane& other ) : m_funcStaticOrigin( 0, 0, 0 ){ + if ( !isDoom3Plane() ) { + planepts_assign( m_planepts, other.m_planepts ); + MakePlane(); + } + else + { + m_plane = other.m_plane; + updateTranslated(); + } + } + FacePlane& operator=( const FacePlane& ) = default; + + void MakePlane(){ + if ( !isDoom3Plane() ) { +#if 0 + if ( check_plane_is_integer( m_planepts ) ) { + globalErrorStream() << "non-integer planepts: "; + planepts_print( m_planepts, globalErrorStream() ); + globalErrorStream() << "\n"; + } #endif - MakePlane(); + m_planeCached = plane3_for_points( m_planepts ); + } } - else - { - m_planeCached = Plane3_applyTransform( m_planeCached, matrix ); - updateSource(); - } -} -void offset( float offset ){ - if ( !isDoom3Plane() ) { - Vector3 move( vector3_scaled( m_planeCached.normal(), -offset ) ); - vector3_subtract( m_planepts[0], move ); - vector3_subtract( m_planepts[1], move ); - vector3_subtract( m_planepts[2], move ); - - MakePlane(); + void reverse(){ + if ( !isDoom3Plane() ) { + vector3_swap( m_planepts[0], m_planepts[2] ); + MakePlane(); + } + else + { + m_planeCached = plane3_flipped( m_plane ); + updateSource(); + } } - else - { - m_planeCached.d += offset; - updateSource(); - } -} + void transform( const Matrix4& matrix, bool mirror ){ + if ( !isDoom3Plane() ) { -void updateTranslated(){ - m_planeCached = Plane3_applyTranslation( m_plane, m_funcStaticOrigin ); -} -void updateSource(){ - m_plane = Plane3_applyTranslation( m_planeCached, vector3_negated( m_funcStaticOrigin ) ); -} +#if 0 + bool off = check_plane_is_integer( planePoints() ); +#endif + + matrix4_transform_point( matrix, m_planepts[0] ); + matrix4_transform_point( matrix, m_planepts[1] ); + matrix4_transform_point( matrix, m_planepts[2] ); + + if ( mirror ) { + reverse(); + } + +#if 0 + if ( check_plane_is_integer( planePoints() ) ) { + if ( !off ) { + globalErrorStream() << "caused by transform\n"; + } + } +#endif + MakePlane(); + } + else + { + m_planeCached = Plane3_applyTransform( m_planeCached, matrix ); + updateSource(); + } + } + void offset( float offset ){ + if ( !isDoom3Plane() ) { + Vector3 move( vector3_scaled( m_planeCached.normal(), -offset ) ); + + vector3_subtract( m_planepts[0], move ); + vector3_subtract( m_planepts[1], move ); + vector3_subtract( m_planepts[2], move ); + + MakePlane(); + } + else + { + m_planeCached.d += offset; + updateSource(); + } + } + + void updateTranslated(){ + m_planeCached = Plane3_applyTranslation( m_plane, m_funcStaticOrigin ); + } + void updateSource(){ + m_plane = Plane3_applyTranslation( m_planeCached, vector3_negated( m_funcStaticOrigin ) ); + } -PlanePoints& planePoints(){ - return m_planepts; -} -const PlanePoints& planePoints() const { - return m_planepts; -} -const PlanePoints& getPlanePoints(){ - if( isDoom3Plane() ){ - m_planepts[0] = m_planeCached.normal() * m_planeCached.dist(); - ComputeAxisBase( m_planeCached.normal(), m_planepts[1], m_planepts[2] ); - m_planepts[1] = m_planepts[1] + m_planepts[0]; - m_planepts[2] = m_planepts[2] + m_planepts[0]; + PlanePoints& planePoints(){ + return m_planepts; + } + const PlanePoints& planePoints() const { + return m_planepts; + } + const PlanePoints& getPlanePoints(){ + if( isDoom3Plane() ){ + m_planepts[0] = m_planeCached.normal() * m_planeCached.dist(); + ComputeAxisBase( m_planeCached.normal(), m_planepts[1], m_planepts[2] ); + m_planepts[1] = m_planepts[1] + m_planepts[0]; + m_planepts[2] = m_planepts[2] + m_planepts[0]; + } + return m_planepts; + } + const Plane3& plane3() const { + return m_planeCached; + } + void setDoom3Plane( const Plane3& plane ){ + m_plane = plane; + updateTranslated(); + } + const Plane3& getDoom3Plane() const { + return m_plane; } - return m_planepts; -} -const Plane3& plane3() const { - return m_planeCached; -} -void setDoom3Plane( const Plane3& plane ){ - m_plane = plane; - updateTranslated(); -} -const Plane3& getDoom3Plane() const { - return m_plane; -} -void copy( const FacePlane& other ){ - if ( !isDoom3Plane() ) { - planepts_assign( m_planepts, other.m_planepts ); - MakePlane(); + void copy( const FacePlane& other ){ + if ( !isDoom3Plane() ) { + planepts_assign( m_planepts, other.m_planepts ); + MakePlane(); + } + else + { + m_planeCached = other.m_plane; + updateSource(); + } } - else - { - m_planeCached = other.m_plane; - updateSource(); + void copy( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ + if ( !isDoom3Plane() ) { + m_planepts[0] = p0; + m_planepts[1] = p1; + m_planepts[2] = p2; + MakePlane(); + } + else + { + m_planeCached = plane3_for_points( p0, p1, p2 ); + updateSource(); + } } -} -void copy( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ - if ( !isDoom3Plane() ) { - m_planepts[0] = p0; - m_planepts[1] = p1; - m_planepts[2] = p2; - MakePlane(); + void copy( const PlanePoints planepoints ){ + if ( !isDoom3Plane() ) { + planepts_assign( m_planepts, planepoints ); + MakePlane(); + } + else + { + m_planeCached = plane3_for_points( planepoints ); + updateSource(); + } } - else - { - m_planeCached = plane3_for_points( p0, p1, p2 ); - updateSource(); - } -} -void copy( const PlanePoints planepoints ){ - if ( !isDoom3Plane() ) { - planepts_assign( m_planepts, planepoints ); - MakePlane(); - } - else - { - m_planeCached = plane3_for_points( planepoints ); - updateSource(); - } -} }; inline void Winding_testSelect( Winding& winding, SelectionTest& test, SelectionIntersection& best, const DoubleVector3 planepoints[3] ){ @@ -870,7 +870,7 @@ class Face; class FaceFilter { public: -virtual bool filter( const Face& face ) const = 0; + virtual bool filter( const Face& face ) const = 0; }; bool face_filtered( Face& face ); @@ -901,10 +901,10 @@ inline TexdefTypeId BrushType_getTexdefType( EBrushType type ){ class FaceObserver { public: -virtual void planeChanged() = 0; -virtual void connectivityChanged() = 0; -virtual void shaderChanged() = 0; -virtual void evaluateTransform() = 0; + virtual void planeChanged() = 0; + virtual void connectivityChanged() = 0; + virtual void shaderChanged() = 0; + virtual void evaluateTransform() = 0; }; class Face : @@ -913,494 +913,496 @@ class Face : public Undoable, public FaceShaderObserver { -std::size_t m_refcount; + std::size_t m_refcount; -class SavedState : public UndoMemento -{ -public: -FacePlane::SavedState m_planeState; -FaceTexdef::SavedState m_texdefState; -FaceShader::SavedState m_shaderState; + class SavedState : public UndoMemento + { + public: + FacePlane::SavedState m_planeState; + FaceTexdef::SavedState m_texdefState; + FaceShader::SavedState m_shaderState; -SavedState( const Face& face ) : m_planeState( face.getPlane() ), m_texdefState( face.getTexdef() ), m_shaderState( face.getShader() ){ -} + SavedState( const Face& face ) : m_planeState( face.getPlane() ), m_texdefState( face.getTexdef() ), m_shaderState( face.getShader() ){ + } -void exportState( Face& face ) const { - m_planeState.exportState( face.getPlane() ); - m_shaderState.exportState( face.getShader() ); - m_texdefState.exportState( face.getTexdef() ); -} + void exportState( Face& face ) const { + m_planeState.exportState( face.getPlane() ); + m_shaderState.exportState( face.getShader() ); + m_texdefState.exportState( face.getTexdef() ); + } -void release(){ - delete this; -} -}; + void release(){ + delete this; + } + }; public: -static QuantiseFunc m_quantise; -static EBrushType m_type; + static QuantiseFunc m_quantise; + static EBrushType m_type; -PlanePoints m_move_planepts; -PlanePoints m_move_planeptsTransformed; + PlanePoints m_move_planepts; + PlanePoints m_move_planeptsTransformed; private: -FacePlane m_plane; -FacePlane m_planeTransformed; -FaceShader m_shader; -FaceTexdef m_texdef; -TextureProjection m_texdefTransformed; + FacePlane m_plane; + FacePlane m_planeTransformed; + FaceShader m_shader; + FaceTexdef m_texdef; + TextureProjection m_texdefTransformed; -Winding m_winding; -Vector3 m_centroid; -Vector3 m_centroid_cached; //this is far not pretty hack! (invariant point for texlock in AP) -bool m_filtered; + Winding m_winding; + Vector3 m_centroid; + Vector3 m_centroid_cached; //this is far not pretty hack! (invariant point for texlock in AP) + bool m_filtered; -FaceObserver* m_observer; -UndoObserver* m_undoable_observer; -MapFile* m_map; + FaceObserver* m_observer; + UndoObserver* m_undoable_observer; + MapFile* m_map; // assignment not supported -Face& operator=( const Face& other ); + Face& operator=( const Face& other ); // copy-construction not supported -Face( const Face& other ); + Face( const Face& other ); public: -Face( FaceObserver* observer ) : - m_refcount( 0 ), - m_shader( texdef_name_default() ), - m_texdef( m_shader, TextureProjection(), false ), - m_filtered( false ), - m_observer( observer ), - m_undoable_observer( 0 ), - m_map( 0 ){ - m_shader.attach( *this ); - m_plane.copy( Vector3( 0, 0, 0 ), Vector3( 64, 0, 0 ), Vector3( 0, 64, 0 ) ); - m_texdef.setBasis( m_plane.plane3().normal() ); - planeChanged(); -} -Face( - const Vector3& p0, - const Vector3& p1, - const Vector3& p2, - const char* shader, - const TextureProjection& projection, - FaceObserver* observer + Face( FaceObserver* observer ) : + m_refcount( 0 ), + m_shader( texdef_name_default() ), + m_texdef( m_shader, TextureProjection(), false ), + m_filtered( false ), + m_observer( observer ), + m_undoable_observer( 0 ), + m_map( 0 ){ + m_shader.attach( *this ); + m_plane.copy( Vector3( 0, 0, 0 ), Vector3( 64, 0, 0 ), Vector3( 0, 64, 0 ) ); + m_texdef.setBasis( m_plane.plane3().normal() ); + planeChanged(); + } + Face( + const Vector3& p0, + const Vector3& p1, + const Vector3& p2, + const char* shader, + const TextureProjection& projection, + FaceObserver* observer ) : - m_refcount( 0 ), - m_shader( shader ), - m_texdef( m_shader, projection ), - m_observer( observer ), - m_undoable_observer( 0 ), - m_map( 0 ){ - m_shader.attach( *this ); - m_plane.copy( p0, p1, p2 ); - m_texdef.setBasis( m_plane.plane3().normal() ); - planeChanged(); - updateFiltered(); -} -Face( const Face& other, FaceObserver* observer ) : - m_refcount( 0 ), - m_shader( other.m_shader.getShader(), other.m_shader.m_flags ), - m_texdef( m_shader, other.getTexdef().normalised() ), - m_observer( observer ), - m_undoable_observer( 0 ), - m_map( 0 ){ - m_shader.attach( *this ); - m_plane.copy( other.m_plane ); - planepts_assign( m_move_planepts, other.m_move_planepts ); -// m_texdef.setBasis( m_plane.plane3().normal() ); //don't reset basis on face clone - planeChanged(); - updateFiltered(); -} -~Face(){ - m_shader.detach( *this ); -} - -void planeChanged(){ - revertTransform(); - m_observer->planeChanged(); -} - -void realiseShader(){ - m_observer->shaderChanged(); -} -void unrealiseShader(){ -} - -void instanceAttach( MapFile* map ){ - m_shader.instanceAttach(); - m_map = map; - m_undoable_observer = GlobalUndoSystem().observer( this ); - GlobalFilterSystem().registerFilterable( *this ); -} -void instanceDetach( MapFile* map ){ - GlobalFilterSystem().unregisterFilterable( *this ); - m_undoable_observer = 0; - GlobalUndoSystem().release( this ); - m_map = 0; - m_shader.instanceDetach(); -} - -void render( RenderStateFlags state ) const { - Winding_Draw( m_winding, m_planeTransformed.plane3().normal(), state ); -} - -void updateFiltered(){ - m_filtered = face_filtered( *this ); -} -bool isFiltered() const { - return m_filtered; -} - -void undoSave(){ - if ( m_map != 0 ) { - m_map->changed(); + m_refcount( 0 ), + m_shader( shader ), + m_texdef( m_shader, projection ), + m_observer( observer ), + m_undoable_observer( 0 ), + m_map( 0 ){ + m_shader.attach( *this ); + m_plane.copy( p0, p1, p2 ); + m_texdef.setBasis( m_plane.plane3().normal() ); + planeChanged(); + updateFiltered(); } - if ( m_undoable_observer != 0 ) { - m_undoable_observer->save( this ); + Face( const Face& other, FaceObserver* observer ) : + m_refcount( 0 ), + m_shader( other.m_shader.getShader(), other.m_shader.m_flags ), + m_texdef( m_shader, other.getTexdef().normalised() ), + m_observer( observer ), + m_undoable_observer( 0 ), + m_map( 0 ){ + m_shader.attach( *this ); + m_plane.copy( other.m_plane ); + planepts_assign( m_move_planepts, other.m_move_planepts ); +// m_texdef.setBasis( m_plane.plane3().normal() ); //don't reset basis on face clone + planeChanged(); + updateFiltered(); + } + ~Face(){ + m_shader.detach( *this ); + } + + void planeChanged(){ + revertTransform(); + m_observer->planeChanged(); + } + + void realiseShader(){ + m_observer->shaderChanged(); + } + void unrealiseShader(){ + } + + void instanceAttach( MapFile* map ){ + m_shader.instanceAttach(); + m_map = map; + m_undoable_observer = GlobalUndoSystem().observer( this ); + GlobalFilterSystem().registerFilterable( *this ); + } + void instanceDetach( MapFile* map ){ + GlobalFilterSystem().unregisterFilterable( *this ); + m_undoable_observer = 0; + GlobalUndoSystem().release( this ); + m_map = 0; + m_shader.instanceDetach(); + } + + void render( RenderStateFlags state ) const { + Winding_Draw( m_winding, m_planeTransformed.plane3().normal(), state ); + } + + void updateFiltered(){ + m_filtered = face_filtered( *this ); + } + bool isFiltered() const { + return m_filtered; + } + + void undoSave(){ + if ( m_map != 0 ) { + m_map->changed(); + } + if ( m_undoable_observer != 0 ) { + m_undoable_observer->save( this ); + } } -} // undoable -UndoMemento* exportState() const { - return new SavedState( *this ); -} -void importState( const UndoMemento* data ){ - undoSave(); - - static_cast( data )->exportState( *this ); - - planeChanged(); - m_observer->connectivityChanged(); - texdefChanged(); - m_observer->shaderChanged(); - updateFiltered(); -} - -void IncRef(){ - ++m_refcount; -} -void DecRef(){ - if ( --m_refcount == 0 ) { - delete this; + UndoMemento* exportState() const { + return new SavedState( *this ); } -} + void importState( const UndoMemento* data ){ + undoSave(); -void flipWinding(){ - m_plane.reverse(); - planeChanged(); -} + static_cast( data )->exportState( *this ); -bool intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { - return volume.TestPlane( Plane3( plane3().normal(), -plane3().dist() ), localToWorld ); -} + planeChanged(); + m_observer->connectivityChanged(); + texdefChanged(); + m_observer->shaderChanged(); + updateFiltered(); + } -void render( Renderer& renderer, const Matrix4& localToWorld ) const { - renderer.SetState( m_shader.state(), Renderer::eFullMaterials ); - renderer.addRenderable( *this, localToWorld ); -} + void IncRef(){ + ++m_refcount; + } + void DecRef(){ + if ( --m_refcount == 0 ) { + delete this; + } + } -void texdef_from_points(){ - Matrix4 local2tex; - Texdef_Construct_local2tex( m_texdef.m_projection, m_shader.width(), m_shader.height(), m_plane.plane3().normal(), local2tex ); - DoubleVector3 st[3]; - for ( std::size_t i = 0; i < 3; ++i ) - st[i] = matrix4_transformed_point( local2tex, m_move_planepts[i] ); - Texdef_from_ST( m_texdefTransformed, m_move_planeptsTransformed, st, m_shader.width(), m_shader.height() ); + void flipWinding(){ + m_plane.reverse(); + planeChanged(); + } - Brush_textureChanged(); -} + bool intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { + return volume.TestPlane( Plane3( plane3().normal(), -plane3().dist() ), localToWorld ); + } -void transform_texdef( const Matrix4& matrix, const Vector3& invariant = g_vector3_identity ){ - revertTexdef(); -// Texdef_transformLocked( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, static_cast( m_plane.plane3().normal() * m_plane.plane3().dist() ) ); - Texdef_transform( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, invariant ); - EmitTextureCoordinates(); - Brush_textureChanged(); -} + void render( Renderer& renderer, const Matrix4& localToWorld ) const { + renderer.SetState( m_shader.state(), Renderer::eFullMaterials ); + renderer.addRenderable( *this, localToWorld ); + } + + void texdef_from_points(){ + Matrix4 local2tex; + Texdef_Construct_local2tex( m_texdef.m_projection, m_shader.width(), m_shader.height(), m_plane.plane3().normal(), local2tex ); + DoubleVector3 st[3]; + for ( std::size_t i = 0; i < 3; ++i ) + st[i] = matrix4_transformed_point( local2tex, m_move_planepts[i] ); + Texdef_from_ST( m_texdefTransformed, m_move_planeptsTransformed, st, m_shader.width(), m_shader.height() ); -void transform( const Matrix4& matrix, bool mirror ){ - if ( g_brush_texturelock_enabled ) { - Texdef_transformLocked( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, contributes() ? m_centroid_cached : static_cast( m_plane.plane3().normal() * m_plane.plane3().dist() ) ); Brush_textureChanged(); } - else if( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_VALVE ){ - const DoubleVector3 from = vector3_normalised( vector3_cross( m_texdefTransformed.m_basis_s, m_texdefTransformed.m_basis_t ) ); - const DoubleVector3 to = matrix4_transformed_normal( matrix, from ); - Quaternion quat = quaternion_for_unit_vectors( from, to ); - if( quat.w() != quat.w() ){ //handle 180` cases - if( vector3_max_abs_component_index( from ) == 2 ) - quat = Quaternion( g_vector3_axis_y, 0 ); - else - quat = Quaternion( g_vector3_axis_z, 0 ); - } - const Matrix4 mat = matrix4_rotation_for_quaternion( quat ); - m_texdefTransformed.m_basis_s = vector3_normalised( matrix4_transformed_direction( mat, m_texdefTransformed.m_basis_s ) ); - m_texdefTransformed.m_basis_t = vector3_normalised( matrix4_transformed_direction( mat, m_texdefTransformed.m_basis_t ) ); + + void transform_texdef( const Matrix4& matrix, const Vector3& invariant = g_vector3_identity ){ + revertTexdef(); +// Texdef_transformLocked( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, static_cast( m_plane.plane3().normal() * m_plane.plane3().dist() ) ); + Texdef_transform( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, invariant ); + EmitTextureCoordinates(); + Brush_textureChanged(); } - m_planeTransformed.transform( matrix, mirror ); + void transform( const Matrix4& matrix, bool mirror ){ + if ( g_brush_texturelock_enabled ) { + Texdef_transformLocked( m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix, + contributes() ? m_centroid_cached + : static_cast( m_plane.plane3().normal() * m_plane.plane3().dist() ) ); + Brush_textureChanged(); + } + else if( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_VALVE ){ + const DoubleVector3 from = vector3_normalised( vector3_cross( m_texdefTransformed.m_basis_s, m_texdefTransformed.m_basis_t ) ); + const DoubleVector3 to = matrix4_transformed_normal( matrix, from ); + Quaternion quat = quaternion_for_unit_vectors( from, to ); + if( quat.w() != quat.w() ){ //handle 180` cases + if( vector3_max_abs_component_index( from ) == 2 ) + quat = Quaternion( g_vector3_axis_y, 0 ); + else + quat = Quaternion( g_vector3_axis_z, 0 ); + } + const Matrix4 mat = matrix4_rotation_for_quaternion( quat ); + m_texdefTransformed.m_basis_s = vector3_normalised( matrix4_transformed_direction( mat, m_texdefTransformed.m_basis_s ) ); + m_texdefTransformed.m_basis_t = vector3_normalised( matrix4_transformed_direction( mat, m_texdefTransformed.m_basis_t ) ); + } + + m_planeTransformed.transform( matrix, mirror ); #if 0 - ASSERT_MESSAGE( projectionaxis_for_normal( normal ) == projectionaxis_for_normal( plane3().normal() ), "bleh" ); + ASSERT_MESSAGE( projectionaxis_for_normal( normal ) == projectionaxis_for_normal( plane3().normal() ), "bleh" ); #endif - m_observer->planeChanged(); -} + m_observer->planeChanged(); + } -void assign_planepts( const PlanePoints planepts ){ - m_planeTransformed.copy( planepts ); - m_observer->planeChanged(); -} + void assign_planepts( const PlanePoints planepts ){ + m_planeTransformed.copy( planepts ); + m_observer->planeChanged(); + } /// \brief Reverts the transformable state of the brush to identity. -void revertTransform(){ - m_planeTransformed = m_plane; - planepts_assign( m_move_planeptsTransformed, m_move_planepts ); - m_texdefTransformed = m_texdef.m_projection; -} -void freezeTransform(){ - undoSave(); - m_plane = m_planeTransformed; - planepts_assign( m_move_planepts, m_move_planeptsTransformed ); - m_texdef.m_projection = m_texdefTransformed; -} - -void update_move_planepts_vertex( std::size_t index, PlanePoints planePoints ){ - if( contributes() ){ - std::size_t numpoints = getWinding().numpoints; - ASSERT_MESSAGE( index < numpoints, "update_move_planepts_vertex: invalid index" ); - - std::size_t opposite = Winding_Opposite( getWinding(), index ); - std::size_t adjacent = Winding_wrap( getWinding(), opposite + numpoints - 1 ); - planePoints[0] = getWinding()[opposite].vertex; - planePoints[1] = getWinding()[index].vertex; - planePoints[2] = getWinding()[adjacent].vertex; - // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane -// planepts_quantise( planePoints, GRID_MIN ); + void revertTransform(){ + m_planeTransformed = m_plane; + planepts_assign( m_move_planeptsTransformed, m_move_planepts ); + m_texdefTransformed = m_texdef.m_projection; + } + void freezeTransform(){ + undoSave(); + m_plane = m_planeTransformed; + planepts_assign( m_move_planepts, m_move_planeptsTransformed ); + m_texdef.m_projection = m_texdefTransformed; } -} -void snapto( float snap ){ - if ( contributes() ) { + void update_move_planepts_vertex( std::size_t index, PlanePoints planePoints ){ + if( contributes() ){ + std::size_t numpoints = getWinding().numpoints; + ASSERT_MESSAGE( index < numpoints, "update_move_planepts_vertex: invalid index" ); + + std::size_t opposite = Winding_Opposite( getWinding(), index ); + std::size_t adjacent = Winding_wrap( getWinding(), opposite + numpoints - 1 ); + planePoints[0] = getWinding()[opposite].vertex; + planePoints[1] = getWinding()[index].vertex; + planePoints[2] = getWinding()[adjacent].vertex; + // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane +// planepts_quantise( planePoints, GRID_MIN ); + } + } + + void snapto( float snap ){ + if ( contributes() ) { #if 0 - ASSERT_MESSAGE( plane3_valid( m_plane.plane3() ), "invalid plane before snap to grid" ); - planepts_snap( m_plane.planePoints(), snap ); - ASSERT_MESSAGE( plane3_valid( m_plane.plane3() ), "invalid plane after snap to grid" ); + ASSERT_MESSAGE( plane3_valid( m_plane.plane3() ), "invalid plane before snap to grid" ); + planepts_snap( m_plane.planePoints(), snap ); + ASSERT_MESSAGE( plane3_valid( m_plane.plane3() ), "invalid plane after snap to grid" ); #else - PlanePoints planePoints; - update_move_planepts_vertex( 0, planePoints ); - vector3_snap( planePoints[0], snap ); - vector3_snap( planePoints[1], snap ); - vector3_snap( planePoints[2], snap ); - assign_planepts( planePoints ); - freezeTransform(); + PlanePoints planePoints; + update_move_planepts_vertex( 0, planePoints ); + vector3_snap( planePoints[0], snap ); + vector3_snap( planePoints[1], snap ); + vector3_snap( planePoints[2], snap ); + assign_planepts( planePoints ); + freezeTransform(); #endif + SceneChangeNotify(); + if ( !plane3_valid( m_plane.plane3() ) ) { + globalWarningStream() << "WARNING: invalid plane after snap to grid\n"; + } + } + } + + void testSelect( SelectionTest& test, SelectionIntersection& best ){ + Winding_testSelect( m_winding, test, best, m_plane.getPlanePoints() ); + } + + void testSelect_centroid( SelectionTest& test, SelectionIntersection& best ) const { + test.TestPoint( m_centroid, best ); + } + + void shaderChanged(){ + EmitTextureCoordinates(); + Brush_textureChanged(); + m_observer->shaderChanged(); + updateFiltered(); + planeChanged(); SceneChangeNotify(); - if ( !plane3_valid( m_plane.plane3() ) ) { - globalWarningStream() << "WARNING: invalid plane after snap to grid\n"; + } + + const char* GetShader() const { + return m_shader.getShader(); + } + void SetShader( const char* name ){ + undoSave(); + m_shader.setShader( name ); + shaderChanged(); + } + + void revertTexdef(){ + m_texdefTransformed = m_texdef.m_projection; + } + void texdefChanged(){ + revertTexdef(); + EmitTextureCoordinates(); + Brush_textureChanged(); + } + + void GetTexdef( TextureProjection& projection ) const { + projection = m_texdef.normalised(); + } + void SetTexdef( const TextureProjection& projection, bool setBasis = true, bool resetBasis = false ){ + undoSave(); + m_texdef.setTexdef( projection, setBasis ); + if( resetBasis ){ + m_texdef.setBasis( m_plane.plane3().normal() ); } + texdefChanged(); } -} -void testSelect( SelectionTest& test, SelectionIntersection& best ){ - Winding_testSelect( m_winding, test, best, m_plane.getPlanePoints() ); -} - -void testSelect_centroid( SelectionTest& test, SelectionIntersection& best ) const { - test.TestPoint( m_centroid, best ); -} - -void shaderChanged(){ - EmitTextureCoordinates(); - Brush_textureChanged(); - m_observer->shaderChanged(); - updateFiltered(); - planeChanged(); - SceneChangeNotify(); -} - -const char* GetShader() const { - return m_shader.getShader(); -} -void SetShader( const char* name ){ - undoSave(); - m_shader.setShader( name ); - shaderChanged(); -} - -void revertTexdef(){ - m_texdefTransformed = m_texdef.m_projection; -} -void texdefChanged(){ - revertTexdef(); - EmitTextureCoordinates(); - Brush_textureChanged(); -} - -void GetTexdef( TextureProjection& projection ) const { - projection = m_texdef.normalised(); -} -void SetTexdef( const TextureProjection& projection, bool setBasis = true, bool resetBasis = false ){ - undoSave(); - m_texdef.setTexdef( projection, setBasis ); - if( resetBasis ){ - m_texdef.setBasis( m_plane.plane3().normal() ); + void SetTexdef( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ){ + undoSave(); + m_texdef.setTexdef( hShift, vShift, hScale, vScale, rotation ); + texdefChanged(); } - texdefChanged(); -} -void SetTexdef( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ){ - undoSave(); - m_texdef.setTexdef( hShift, vShift, hScale, vScale, rotation ); - texdefChanged(); -} - -void GetFlags( ContentsFlagsValue& flags ) const { - flags = m_shader.getFlags(); -} -void SetFlags( const ContentsFlagsValue& flags ){ - undoSave(); - m_shader.setFlags( flags ); - m_observer->shaderChanged(); - updateFiltered(); -} - -void ShiftTexdef( float s, float t ){ - undoSave(); - m_texdef.shift( s, t ); - texdefChanged(); -} - -void ScaleTexdef( float s, float t ){ - undoSave(); - m_texdef.scale( s, t ); - texdefChanged(); -} - -void RotateTexdef( float angle ){ - undoSave(); - m_texdef.rotate( angle ); - texdefChanged(); -} - -void ProjectTexture( const texdef_t& texdef, const Vector3* direction ){ - undoSave(); - m_texdef.ProjectTexture( m_plane.plane3(), texdef, direction ); - texdefChanged(); -} - -void ProjectTexture( const TextureProjection& projection, const Vector3& normal ){ - undoSave(); - m_texdef.ProjectTexture( m_plane.plane3(), projection, normal ); - texdefChanged(); -} - -void Convert( TexdefTypeId in, TexdefTypeId out ){ - m_texdef.Convert( in, out, m_plane.plane3() ); - texdefChanged(); -} - -void FitTexture( float s_repeat, float t_repeat, bool only_dimension ){ - undoSave(); - m_texdef.fit( m_plane.plane3().normal(), m_winding, s_repeat, t_repeat, only_dimension ); - texdefChanged(); -} - -void EmitTextureCoordinates(){ - Texdef_EmitTextureCoordinates( m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity ); -} - - -const Vector3& centroid() const { - return m_centroid; -} - -void construct_centroid(){ - Winding_Centroid( m_winding, plane3(), m_centroid ); -} - -const Winding& getWinding() const { - return m_winding; -} -Winding& getWinding(){ - return m_winding; -} - -void cacheCentroid() { - m_centroid_cached = m_centroid; -} - -const Plane3& plane3() const { - m_observer->evaluateTransform(); - return m_planeTransformed.plane3(); -} -const Plane3& plane3_() const { - return m_planeTransformed.plane3(); -} -FacePlane& getPlane(){ - return m_plane; -} -const FacePlane& getPlane() const { - return m_plane; -} -FaceTexdef& getTexdef(){ - return m_texdef; -} -const FaceTexdef& getTexdef() const { - return m_texdef; -} -FaceShader& getShader(){ - return m_shader; -} -const FaceShader& getShader() const { - return m_shader; -} - -bool isDetail() const { - return ( m_shader.m_flags.m_contentFlags & BRUSH_DETAIL_MASK ) != 0; -} -void setDetail( bool detail ){ - undoSave(); - if ( detail && !isDetail() ) { - m_shader.m_flags.m_contentFlags |= BRUSH_DETAIL_MASK; + void GetFlags( ContentsFlagsValue& flags ) const { + flags = m_shader.getFlags(); } - else if ( !detail && isDetail() ) { - m_shader.m_flags.m_contentFlags &= ~BRUSH_DETAIL_MASK; + void SetFlags( const ContentsFlagsValue& flags ){ + undoSave(); + m_shader.setFlags( flags ); + m_observer->shaderChanged(); + updateFiltered(); } - m_observer->shaderChanged(); -} -bool contributes() const { - return m_winding.numpoints > 2; -} -bool is_bounded() const { - for ( Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i ) - { - if ( ( *i ).adjacent == c_brush_maxFaces ) { - return false; + void ShiftTexdef( float s, float t ){ + undoSave(); + m_texdef.shift( s, t ); + texdefChanged(); + } + + void ScaleTexdef( float s, float t ){ + undoSave(); + m_texdef.scale( s, t ); + texdefChanged(); + } + + void RotateTexdef( float angle ){ + undoSave(); + m_texdef.rotate( angle ); + texdefChanged(); + } + + void ProjectTexture( const texdef_t& texdef, const Vector3* direction ){ + undoSave(); + m_texdef.ProjectTexture( m_plane.plane3(), texdef, direction ); + texdefChanged(); + } + + void ProjectTexture( const TextureProjection& projection, const Vector3& normal ){ + undoSave(); + m_texdef.ProjectTexture( m_plane.plane3(), projection, normal ); + texdefChanged(); + } + + void Convert( TexdefTypeId in, TexdefTypeId out ){ + m_texdef.Convert( in, out, m_plane.plane3() ); + texdefChanged(); + } + + void FitTexture( float s_repeat, float t_repeat, bool only_dimension ){ + undoSave(); + m_texdef.fit( m_plane.plane3().normal(), m_winding, s_repeat, t_repeat, only_dimension ); + texdefChanged(); + } + + void EmitTextureCoordinates(){ + Texdef_EmitTextureCoordinates( m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity ); + } + + + const Vector3& centroid() const { + return m_centroid; + } + + void construct_centroid(){ + Winding_Centroid( m_winding, plane3(), m_centroid ); + } + + const Winding& getWinding() const { + return m_winding; + } + Winding& getWinding(){ + return m_winding; + } + + void cacheCentroid() { + m_centroid_cached = m_centroid; + } + + const Plane3& plane3() const { + m_observer->evaluateTransform(); + return m_planeTransformed.plane3(); + } + const Plane3& plane3_() const { + return m_planeTransformed.plane3(); + } + FacePlane& getPlane(){ + return m_plane; + } + const FacePlane& getPlane() const { + return m_plane; + } + FaceTexdef& getTexdef(){ + return m_texdef; + } + const FaceTexdef& getTexdef() const { + return m_texdef; + } + FaceShader& getShader(){ + return m_shader; + } + const FaceShader& getShader() const { + return m_shader; + } + + bool isDetail() const { + return ( m_shader.m_flags.m_contentFlags & BRUSH_DETAIL_MASK ) != 0; + } + void setDetail( bool detail ){ + undoSave(); + if ( detail && !isDetail() ) { + m_shader.m_flags.m_contentFlags |= BRUSH_DETAIL_MASK; } + else if ( !detail && isDetail() ) { + m_shader.m_flags.m_contentFlags &= ~BRUSH_DETAIL_MASK; + } + m_observer->shaderChanged(); + } + + bool contributes() const { + return m_winding.numpoints > 2; + } + bool is_bounded() const { + for ( Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i ) + { + if ( ( *i ).adjacent == c_brush_maxFaces ) { + return false; + } + } + return true; } - return true; -} }; class FaceVertexId { -std::size_t m_face; -std::size_t m_vertex; + std::size_t m_face; + std::size_t m_vertex; public: -FaceVertexId( std::size_t face, std::size_t vertex ) - : m_face( face ), m_vertex( vertex ){ -} + FaceVertexId( std::size_t face, std::size_t vertex ) + : m_face( face ), m_vertex( vertex ){ + } -std::size_t getFace() const { - return m_face; -} -std::size_t getVertex() const { - return m_vertex; -} + std::size_t getFace() const { + return m_face; + } + std::size_t getVertex() const { + return m_vertex; + } }; typedef std::size_t faceIndex_t; @@ -1434,24 +1436,24 @@ struct EdgeFaces class RenderableWireframe : public OpenGLRenderable { public: -void render( RenderStateFlags state ) const { + void render( RenderStateFlags state ) const { #if 1 - glVertexPointer( 3, GL_FLOAT, sizeof( DepthTestedPointVertex ), &m_vertices->vertex ); - glDrawElements( GL_LINES, GLsizei( m_size << 1 ), RenderIndexTypeID, m_faceVertex.data() ); + glVertexPointer( 3, GL_FLOAT, sizeof( DepthTestedPointVertex ), &m_vertices->vertex ); + glDrawElements( GL_LINES, GLsizei( m_size << 1 ), RenderIndexTypeID, m_faceVertex.data() ); #else - glBegin( GL_LINES ); - for ( std::size_t i = 0; i < m_size; ++i ) - { - glVertex3fv( &m_vertices[m_faceVertex[i].first].vertex.x ); - glVertex3fv( &m_vertices[m_faceVertex[i].second].vertex.x ); - } - glEnd(); + glBegin( GL_LINES ); + for ( std::size_t i = 0; i < m_size; ++i ) + { + glVertex3fv( &m_vertices[m_faceVertex[i].first].vertex.x ); + glVertex3fv( &m_vertices[m_faceVertex[i].second].vertex.x ); + } + glEnd(); #endif -} + } -Array m_faceVertex; -std::size_t m_size; -const DepthTestedPointVertex* m_vertices; + Array m_faceVertex; + std::size_t m_size; + const DepthTestedPointVertex* m_vertices; }; class Brush; @@ -1460,7 +1462,7 @@ typedef std::vector brush_vector_t; class BrushFilter { public: -virtual bool filter( const Brush& brush ) const = 0; + virtual bool filter( const Brush& brush ) const = 0; }; bool brush_filtered( Brush& brush ); @@ -1504,84 +1506,84 @@ inline FaceVertexId next_vertex( const Faces& faces, FaceVertexId faceVertex ){ class SelectableEdge { public: -Vector3 getEdge() const { - const Winding& winding = getFace().getWinding(); - return vector3_mid( winding[m_faceVertex.getVertex()].vertex, winding[Winding_next( winding, m_faceVertex.getVertex() )].vertex ); -} + Vector3 getEdge() const { + const Winding& winding = getFace().getWinding(); + return vector3_mid( winding[m_faceVertex.getVertex()].vertex, winding[Winding_next( winding, m_faceVertex.getVertex() )].vertex ); + } -Faces& m_faces; -FaceVertexId m_faceVertex; + Faces& m_faces; + FaceVertexId m_faceVertex; -SelectableEdge( Faces& faces, FaceVertexId faceVertex ) - : m_faces( faces ), m_faceVertex( faceVertex ){ -} -SelectableEdge& operator=( const SelectableEdge& other ){ - m_faceVertex = other.m_faceVertex; - return *this; -} + SelectableEdge( Faces& faces, FaceVertexId faceVertex ) + : m_faces( faces ), m_faceVertex( faceVertex ){ + } + SelectableEdge& operator=( const SelectableEdge& other ){ + m_faceVertex = other.m_faceVertex; + return *this; + } -Face& getFace() const { - return *m_faces[m_faceVertex.getFace()]; -} + Face& getFace() const { + return *m_faces[m_faceVertex.getFace()]; + } -void testSelect( SelectionTest& test, SelectionIntersection& best ){ - test.TestPoint( getEdge(), best ); -} + void testSelect( SelectionTest& test, SelectionIntersection& best ){ + test.TestPoint( getEdge(), best ); + } }; class SelectableVertex { public: -Vector3 getVertex() const { - return getFace().getWinding()[m_faceVertex.getVertex()].vertex; -} + Vector3 getVertex() const { + return getFace().getWinding()[m_faceVertex.getVertex()].vertex; + } -Faces& m_faces; -FaceVertexId m_faceVertex; + Faces& m_faces; + FaceVertexId m_faceVertex; -SelectableVertex( Faces& faces, FaceVertexId faceVertex ) - : m_faces( faces ), m_faceVertex( faceVertex ){ -} -SelectableVertex& operator=( const SelectableVertex& other ){ - m_faceVertex = other.m_faceVertex; - return *this; -} + SelectableVertex( Faces& faces, FaceVertexId faceVertex ) + : m_faces( faces ), m_faceVertex( faceVertex ){ + } + SelectableVertex& operator=( const SelectableVertex& other ){ + m_faceVertex = other.m_faceVertex; + return *this; + } -Face& getFace() const { - return *m_faces[m_faceVertex.getFace()]; -} + Face& getFace() const { + return *m_faces[m_faceVertex.getFace()]; + } -void testSelect( SelectionTest& test, SelectionIntersection& best ){ - test.TestPoint( getVertex(), best ); -} + void testSelect( SelectionTest& test, SelectionIntersection& best ){ + test.TestPoint( getVertex(), best ); + } }; class BrushObserver { public: -virtual void reserve( std::size_t size ) = 0; -virtual void clear() = 0; -virtual void push_back( Face& face ) = 0; -virtual void pop_back() = 0; -virtual void erase( std::size_t index ) = 0; -virtual void connectivityChanged() = 0; + virtual void reserve( std::size_t size ) = 0; + virtual void clear() = 0; + virtual void push_back( Face& face ) = 0; + virtual void pop_back() = 0; + virtual void erase( std::size_t index ) = 0; + virtual void connectivityChanged() = 0; -virtual void edge_clear() = 0; -virtual void edge_push_back( SelectableEdge& edge ) = 0; + virtual void edge_clear() = 0; + virtual void edge_push_back( SelectableEdge& edge ) = 0; -virtual void vertex_clear() = 0; -virtual void vertex_push_back( SelectableVertex& vertex ) = 0; + virtual void vertex_clear() = 0; + virtual void vertex_push_back( SelectableVertex& vertex ) = 0; -virtual void vertex_select() = 0; -virtual void vertex_snap( const float snap ) = 0; + virtual void vertex_select() = 0; + virtual void vertex_snap( const float snap ) = 0; -virtual void DEBUG_verify() const = 0; + virtual void DEBUG_verify() const = 0; }; class BrushVisitor { public: -virtual void visit( Face& face ) const = 0; + virtual void visit( Face& face ) const = 0; }; class Brush : @@ -1596,327 +1598,327 @@ class Brush : public BrushDoom3 { private: -scene::Node* m_node; -typedef UniqueSet Observers; -Observers m_observers; -UndoObserver* m_undoable_observer; -MapFile* m_map; + scene::Node* m_node; + typedef UniqueSet Observers; + Observers m_observers; + UndoObserver* m_undoable_observer; + MapFile* m_map; // state -Faces m_faces; + Faces m_faces; // ---- // cached data compiled from state -Array m_faceCentroidPoints; -RenderablePointArray m_render_faces; + Array m_faceCentroidPoints; + RenderablePointArray m_render_faces; -mutable Array m_uniqueVertexPoints; -typedef std::vector SelectableVertices; -SelectableVertices m_select_vertices; -RenderablePointArray m_render_vertices; -RenderableDepthTestedPointArray m_render_deepvertices; + mutable Array m_uniqueVertexPoints; + typedef std::vector SelectableVertices; + SelectableVertices m_select_vertices; + RenderablePointArray m_render_vertices; + RenderableDepthTestedPointArray m_render_deepvertices; -Array m_uniqueEdgePoints; -typedef std::vector SelectableEdges; -SelectableEdges m_select_edges; -RenderablePointArray m_render_edges; + Array m_uniqueEdgePoints; + typedef std::vector SelectableEdges; + SelectableEdges m_select_edges; + RenderablePointArray m_render_edges; -Array m_edge_indices; -Array m_edge_faces; + Array m_edge_indices; + Array m_edge_faces; -AABB m_aabb_local; + AABB m_aabb_local; // ---- -Callback m_evaluateTransform; -Callback m_boundsChanged; + Callback m_evaluateTransform; + Callback m_boundsChanged; -mutable bool m_planeChanged; // b-rep evaluation required -mutable bool m_transformChanged; // transform evaluation required -bool m_BRep_evaluation = false; //mutex for invalidation + mutable bool m_planeChanged; // b-rep evaluation required + mutable bool m_transformChanged; // transform evaluation required + bool m_BRep_evaluation = false; //mutex for invalidation // ---- public: -STRING_CONSTANT( Name, "Brush" ); + STRING_CONSTANT( Name, "Brush" ); -Callback m_lightsChanged; + Callback m_lightsChanged; // static data -static Shader* m_state_point; -static Shader* m_state_deeppoint; + static Shader* m_state_point; + static Shader* m_state_deeppoint; // ---- -static EBrushType m_type; -static double m_maxWorldCoord; + static EBrushType m_type; + static double m_maxWorldCoord; -Brush( scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : - m_node( &node ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_faces( m_faceCentroidPoints, GL_POINTS ), - m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_edges( m_uniqueEdgePoints, GL_POINTS ), - m_evaluateTransform( evaluateTransform ), - m_boundsChanged( boundsChanged ), - m_planeChanged( false ), - m_transformChanged( false ){ - planeChanged(); -} -Brush( const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : - m_node( &node ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_faces( m_faceCentroidPoints, GL_POINTS ), - m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_edges( m_uniqueEdgePoints, GL_POINTS ), - m_evaluateTransform( evaluateTransform ), - m_boundsChanged( boundsChanged ), - m_planeChanged( false ), - m_transformChanged( false ){ - copy( other ); -} -Brush( const Brush& other ) : - TransformNode( other ), - Bounded( other ), - Cullable( other ), - Snappable(), - Undoable( other ), - FaceObserver( other ), - Filterable( other ), - Nameable( other ), - BrushDoom3( other ), - m_node( 0 ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_faces( m_faceCentroidPoints, GL_POINTS ), - m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), - m_render_edges( m_uniqueEdgePoints, GL_POINTS ), - m_planeChanged( false ), - m_transformChanged( false ){ - copy( other ); -} -~Brush(){ - ASSERT_MESSAGE( m_observers.empty(), "Brush::~Brush: observers still attached" ); -} + Brush( scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : + m_node( &node ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_faces( m_faceCentroidPoints, GL_POINTS ), + m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_edges( m_uniqueEdgePoints, GL_POINTS ), + m_evaluateTransform( evaluateTransform ), + m_boundsChanged( boundsChanged ), + m_planeChanged( false ), + m_transformChanged( false ){ + planeChanged(); + } + Brush( const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : + m_node( &node ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_faces( m_faceCentroidPoints, GL_POINTS ), + m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_edges( m_uniqueEdgePoints, GL_POINTS ), + m_evaluateTransform( evaluateTransform ), + m_boundsChanged( boundsChanged ), + m_planeChanged( false ), + m_transformChanged( false ){ + copy( other ); + } + Brush( const Brush& other ) : + TransformNode( other ), + Bounded( other ), + Cullable( other ), + Snappable(), + Undoable( other ), + FaceObserver( other ), + Filterable( other ), + Nameable( other ), + BrushDoom3( other ), + m_node( 0 ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_faces( m_faceCentroidPoints, GL_POINTS ), + m_render_vertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_deepvertices( m_uniqueVertexPoints, GL_POINTS ), + m_render_edges( m_uniqueEdgePoints, GL_POINTS ), + m_planeChanged( false ), + m_transformChanged( false ){ + copy( other ); + } + ~Brush(){ + ASSERT_MESSAGE( m_observers.empty(), "Brush::~Brush: observers still attached" ); + } // assignment not supported -Brush& operator=( const Brush& other ); + Brush& operator=( const Brush& other ); -void setDoom3GroupOrigin( const Vector3& origin ){ - //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n"; - for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->getPlane().m_funcStaticOrigin = origin; - ( *i )->getPlane().updateTranslated(); - ( *i )->planeChanged(); - } - planeChanged(); -} - -void attach( BrushObserver& observer ){ - for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - observer.push_back( *( *i ) ); + void setDoom3GroupOrigin( const Vector3& origin ){ + //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n"; + for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->getPlane().m_funcStaticOrigin = origin; + ( *i )->getPlane().updateTranslated(); + ( *i )->planeChanged(); + } + planeChanged(); } - for ( SelectableEdges::iterator i = m_select_edges.begin(); i != m_select_edges.end(); ++i ) - { - observer.edge_push_back( *i ); + void attach( BrushObserver& observer ){ + for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + observer.push_back( *( *i ) ); + } + + for ( SelectableEdges::iterator i = m_select_edges.begin(); i != m_select_edges.end(); ++i ) + { + observer.edge_push_back( *i ); + } + + for ( SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i ) + { + observer.vertex_push_back( *i ); + } + + m_observers.insert( &observer ); + } + void detach( BrushObserver& observer ){ + m_observers.erase( &observer ); } - for ( SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i ) - { - observer.vertex_push_back( *i ); + void forEachFace( const BrushVisitor& visitor ) const { + for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + visitor.visit( *( *i ) ); + } } - m_observers.insert( &observer ); -} -void detach( BrushObserver& observer ){ - m_observers.erase( &observer ); -} + void forEachFace_instanceAttach( MapFile* map ) const { + for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->instanceAttach( map ); + } + } + void forEachFace_instanceDetach( MapFile* map ) const { + for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->instanceDetach( map ); + } + } -void forEachFace( const BrushVisitor& visitor ) const { - for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - visitor.visit( *( *i ) ); - } -} - -void forEachFace_instanceAttach( MapFile* map ) const { - for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->instanceAttach( map ); - } -} -void forEachFace_instanceDetach( MapFile* map ) const { - for ( Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->instanceDetach( map ); - } -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_map = path_find_mapfile( path.begin(), path.end() ); - m_undoable_observer = GlobalUndoSystem().observer( this ); - GlobalFilterSystem().registerFilterable( *this ); - forEachFace_instanceAttach( m_map ); - } - else - { - ASSERT_MESSAGE( path_find_mapfile( path.begin(), path.end() ) == m_map, "node is instanced across more than one file" ); - } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - forEachFace_instanceDetach( m_map ); - GlobalFilterSystem().unregisterFilterable( *this ); - m_map = 0; - m_undoable_observer = 0; - GlobalUndoSystem().release( this ); - } -} - -// nameable -const char* name() const { - return "brush"; -} -void attach( const NameCallback& callback ){ -} -void detach( const NameCallback& callback ){ -} - -// filterable -void updateFiltered(){ - if ( m_node != 0 ) { - if ( brush_filtered( *this ) ) { - m_node->enable( scene::Node::eFiltered ); + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_map = path_find_mapfile( path.begin(), path.end() ); + m_undoable_observer = GlobalUndoSystem().observer( this ); + GlobalFilterSystem().registerFilterable( *this ); + forEachFace_instanceAttach( m_map ); } else { - m_node->disable( scene::Node::eFiltered ); + ASSERT_MESSAGE( path_find_mapfile( path.begin(), path.end() ) == m_map, "node is instanced across more than one file" ); + } + } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + forEachFace_instanceDetach( m_map ); + GlobalFilterSystem().unregisterFilterable( *this ); + m_map = 0; + m_undoable_observer = 0; + GlobalUndoSystem().release( this ); + } + } + +// nameable + const char* name() const { + return "brush"; + } + void attach( const NameCallback& callback ){ + } + void detach( const NameCallback& callback ){ + } + +// filterable + void updateFiltered(){ + if ( m_node != 0 ) { + if ( brush_filtered( *this ) ) { + m_node->enable( scene::Node::eFiltered ); + } + else + { + m_node->disable( scene::Node::eFiltered ); + } } } -} // observer -void planeChanged(){ - /* m_BRep_evaluation mutex prevents cyclic dependency: - transformModifier.set ; transformChanged() ; planeChanged() ; pivotChanged() ; sceneChangeNotify() ; - sceneRender() ; localAABB ; evaluateBRep ; buildBRep() ; evaluateTransform ; !!!problem starts here!!!! planeChanged() ; pivotChanged() ; sceneChangeNotify() ; - sceneRender() ; localAABB ; evaluateBRep ; buildBRep() ; */ - if( !m_BRep_evaluation ){ - m_planeChanged = true; - aabbChanged(); - m_lightsChanged(); + void planeChanged(){ + /* m_BRep_evaluation mutex prevents cyclic dependency: + transformModifier.set ; transformChanged() ; planeChanged() ; pivotChanged() ; sceneChangeNotify() ; + sceneRender() ; localAABB ; evaluateBRep ; buildBRep() ; evaluateTransform ; !!!problem starts here!!!! planeChanged() ; pivotChanged() ; sceneChangeNotify() ; + sceneRender() ; localAABB ; evaluateBRep ; buildBRep() ; */ + if( !m_BRep_evaluation ){ + m_planeChanged = true; + aabbChanged(); + m_lightsChanged(); + } } -} -void shaderChanged(){ - updateFiltered(); - planeChanged(); ///isn't too much for shader changed only? -} - -void evaluateBRep() const { - if ( m_planeChanged ) { - m_planeChanged = false; - const_cast( this )->buildBRep(); + void shaderChanged(){ + updateFiltered(); + planeChanged(); ///isn't too much for shader changed only? } -} -void transformChanged(){ - planeChanged(); - m_transformChanged = true; -} -typedef MemberCaller TransformChangedCaller; - -void evaluateTransform(){ - if ( m_transformChanged ) { - revertTransform(); - m_evaluateTransform(); - m_transformChanged = false; + void evaluateBRep() const { + if ( m_planeChanged ) { + m_planeChanged = false; + const_cast( this )->buildBRep(); + } } -} -const Matrix4& localToParent() const { - return g_matrix4_identity; -} -void aabbChanged(){ - m_boundsChanged(); -} -const AABB& localAABB() const { - evaluateBRep(); - return m_aabb_local; -} -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} + void transformChanged(){ + planeChanged(); + m_transformChanged = true; + } + typedef MemberCaller TransformChangedCaller; -void renderComponents( SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - switch ( mode ) - { - case SelectionSystem::eVertex: + void evaluateTransform(){ + if ( m_transformChanged ) { + revertTransform(); + m_evaluateTransform(); + m_transformChanged = false; + } + } + const Matrix4& localToParent() const { + return g_matrix4_identity; + } + void aabbChanged(){ + m_boundsChanged(); + } + const AABB& localAABB() const { + evaluateBRep(); + return m_aabb_local; + } + + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } + + void renderComponents( SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + switch ( mode ) { - if( GlobalOpenGL().GL_1_5() ){ - if( volume.fill() ){ - renderer.SetState( m_state_deeppoint, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_deepvertices, localToWorld ); + case SelectionSystem::eVertex: + { + if( GlobalOpenGL().GL_1_5() ){ + if( volume.fill() ){ + renderer.SetState( m_state_deeppoint, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_deepvertices, localToWorld ); + } + else{ + for( auto& p : m_uniqueVertexPoints ) + p.colour = colour_vertex; + renderer.addRenderable( m_render_vertices, localToWorld ); + } } else{ - for( auto& p : m_uniqueVertexPoints ) - p.colour = colour_vertex; renderer.addRenderable( m_render_vertices, localToWorld ); } } - else{ - renderer.addRenderable( m_render_vertices, localToWorld ); - } + break; + case SelectionSystem::eEdge: + renderer.addRenderable( m_render_edges, localToWorld ); + break; + case SelectionSystem::eFace: + renderer.addRenderable( m_render_faces, localToWorld ); + break; + default: + break; } - break; - case SelectionSystem::eEdge: - renderer.addRenderable( m_render_edges, localToWorld ); - break; - case SelectionSystem::eFace: - renderer.addRenderable( m_render_faces, localToWorld ); - break; - default: - break; } -} -void transform( const Matrix4& matrix ){ - bool mirror = matrix4_handedness( matrix ) == MATRIX4_LEFTHANDED; + void transform( const Matrix4& matrix ){ + bool mirror = matrix4_handedness( matrix ) == MATRIX4_LEFTHANDED; - for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->transform( matrix, mirror ); + for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->transform( matrix, mirror ); + } } -} -void snapto( float snap ){ - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->vertex_snap( snap ); + void snapto( float snap ){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->vertex_snap( snap ); + } +// for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) +// { +// ( *i )->snapto( snap ); +// } } -// for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) -// { -// ( *i )->snapto( snap ); -// } -} -void revertTransform(){ - for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->revertTransform(); + void revertTransform(){ + for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->revertTransform(); + } } -} -void freezeTransform(){ - for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) - { - ( *i )->freezeTransform(); + void freezeTransform(){ + for ( Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i ) + { + ( *i )->freezeTransform(); + } + m_transformChanged = false; } - m_transformChanged = false; -} class VertexModeVertex { @@ -1931,364 +1933,242 @@ void freezeTransform(){ typedef std::vector VertexModeVertices; -VertexModeVertices m_vertexModeVertices; -bool m_vertexModeOn{false}; + VertexModeVertices m_vertexModeVertices; + bool m_vertexModeOn{false}; -void vertexModeInit(){ - m_vertexModeOn = true; - m_vertexModeVertices.clear(); - undoSave(); -} + void vertexModeInit(){ + m_vertexModeOn = true; + m_vertexModeVertices.clear(); + undoSave(); + } -void vertexModeFree(){ - m_vertexModeOn = false; -// m_vertexModeVertices.clear(); //keep, as it may be required by buildBRep() after this call -} + void vertexModeFree(){ + m_vertexModeOn = false; +// m_vertexModeVertices.clear(); //keep, as it may be required by buildBRep() after this call + } -void vertexModeTransform( const Matrix4& matrix ); -void vertexModeBuildHull( bool allTransformed = false ); -void vertexModeSnap( const float snap, bool all ); + void vertexModeTransform( const Matrix4& matrix ); + void vertexModeBuildHull( bool allTransformed = false ); + void vertexModeSnap( const float snap, bool all ); /// \brief Returns the absolute index of the \p faceVertex. -std::size_t absoluteIndex( FaceVertexId faceVertex ){ - std::size_t index = 0; - for ( std::size_t i = 0; i < faceVertex.getFace(); ++i ) - { - index += m_faces[i]->getWinding().numpoints; + std::size_t absoluteIndex( FaceVertexId faceVertex ){ + std::size_t index = 0; + for ( std::size_t i = 0; i < faceVertex.getFace(); ++i ) + { + index += m_faces[i]->getWinding().numpoints; + } + return index + faceVertex.getVertex(); } - return index + faceVertex.getVertex(); -} -void appendFaces( const Faces& other ){ - clear(); - for ( Faces::const_iterator i = other.begin(); i != other.end(); ++i ) - { - push_back( *i ); - } -} - -/// \brief The undo memento for a brush stores only the list of face references - the faces are not copied. -class BrushUndoMemento : public UndoMemento -{ -public: -BrushUndoMemento( const Faces& faces ) : m_faces( faces ){ -} -void release(){ - delete this; -} - -Faces m_faces; -}; - -void undoSave(){ - if ( m_map != 0 ) { - m_map->changed(); - } - if ( m_undoable_observer != 0 ) { - m_undoable_observer->save( this ); - } -} - -UndoMemento* exportState() const { - return new BrushUndoMemento( m_faces ); -} - -void importState( const UndoMemento* state ){ - undoSave(); - appendFaces( static_cast( state )->m_faces ); - planeChanged(); - - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->DEBUG_verify(); - } -} - -bool isDetail(){ - return !m_faces.empty() && m_faces.front()->isDetail(); -} - -/// \brief Appends a copy of \p face to the end of the face list. -Face* addFace( const Face& face ){ - if ( m_faces.size() == c_brush_maxFaces ) { - return 0; - } - undoSave(); - push_back( FaceSmartPointer( new Face( face, this ) ) ); - m_faces.back()->setDetail( isDetail() ); - planeChanged(); - return m_faces.back(); -} - -/// \brief Appends a new face constructed from the parameters to the end of the face list. -Face* addPlane( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection ){ - if ( m_faces.size() == c_brush_maxFaces ) { - return 0; - } - undoSave(); - push_back( FaceSmartPointer( new Face( p0, p1, p2, shader, projection, this ) ) ); - m_faces.back()->setDetail( isDetail() ); - planeChanged(); - return m_faces.back(); -} - -static void constructStatic( EBrushType type ){ - m_type = type; - Face::m_type = type; - FacePlane::m_type = type; - - g_bp_globals.m_texdefTypeId = BrushType_getTexdefType( type ); - - m_state_point = GlobalShaderCache().capture( "$POINT" ); - m_state_deeppoint = GlobalShaderCache().capture( "$DEEPPOINT" ); -} -static void destroyStatic(){ - GlobalShaderCache().release( "$POINT" ); - GlobalShaderCache().release( "$DEEPPOINT" ); -} - -std::size_t DEBUG_size(){ - return m_faces.size(); -} - -typedef Faces::const_iterator const_iterator; - -const_iterator begin() const { - return m_faces.begin(); -} -const_iterator end() const { - return m_faces.end(); -} - -Face* back(){ - return m_faces.back(); -} -const Face* back() const { - return m_faces.back(); -} -void reserve( std::size_t count ){ - m_faces.reserve( count ); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->reserve( count ); - } -} -void push_back( Faces::value_type face ){ - m_faces.push_back( face ); - if ( m_instanceCounter.m_count != 0 ) { - m_faces.back()->instanceAttach( m_map ); - } - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->push_back( *face ); - ( *i )->DEBUG_verify(); - } -} -void pop_back(){ - if ( m_instanceCounter.m_count != 0 ) { - m_faces.back()->instanceDetach( m_map ); - } - m_faces.pop_back(); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->pop_back(); - ( *i )->DEBUG_verify(); - } -} -void erase( std::size_t index ){ - if ( m_instanceCounter.m_count != 0 ) { - m_faces[index]->instanceDetach( m_map ); - } - m_faces.erase( m_faces.begin() + index ); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->erase( index ); - ( *i )->DEBUG_verify(); - } -} -void connectivityChanged(){ - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->connectivityChanged(); - } -} - - -void clear(){ - undoSave(); - if ( m_instanceCounter.m_count != 0 ) { - forEachFace_instanceDetach( m_map ); - } - m_faces.clear(); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->clear(); - ( *i )->DEBUG_verify(); - } -} -std::size_t size() const { - return m_faces.size(); -} -bool empty() const { - return m_faces.empty(); -} - -/// \brief Returns true if any face of the brush contributes to the final B-Rep. -bool hasContributingFaces() const { - for ( const_iterator i = begin(); i != end(); ++i ) - { - if ( ( *i )->contributes() ) { - return true; + void appendFaces( const Faces& other ){ + clear(); + for ( Faces::const_iterator i = other.begin(); i != other.end(); ++i ) + { + push_back( *i ); } } - return false; -} + +/// \brief The undo memento for a brush stores only the list of face references - the faces are not copied. + class BrushUndoMemento : public UndoMemento + { + public: + BrushUndoMemento( const Faces& faces ) : m_faces( faces ){ + } + void release(){ + delete this; + } + + Faces m_faces; + }; + + void undoSave(){ + if ( m_map != 0 ) { + m_map->changed(); + } + if ( m_undoable_observer != 0 ) { + m_undoable_observer->save( this ); + } + } + + UndoMemento* exportState() const { + return new BrushUndoMemento( m_faces ); + } + + void importState( const UndoMemento* state ){ + undoSave(); + appendFaces( static_cast( state )->m_faces ); + planeChanged(); + + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->DEBUG_verify(); + } + } + + bool isDetail(){ + return !m_faces.empty() && m_faces.front()->isDetail(); + } + +/// \brief Appends a copy of \p face to the end of the face list. + Face* addFace( const Face& face ){ + if ( m_faces.size() == c_brush_maxFaces ) { + return 0; + } + undoSave(); + push_back( FaceSmartPointer( new Face( face, this ) ) ); + m_faces.back()->setDetail( isDetail() ); + planeChanged(); + return m_faces.back(); + } + +/// \brief Appends a new face constructed from the parameters to the end of the face list. + Face* addPlane( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection ){ + if ( m_faces.size() == c_brush_maxFaces ) { + return 0; + } + undoSave(); + push_back( FaceSmartPointer( new Face( p0, p1, p2, shader, projection, this ) ) ); + m_faces.back()->setDetail( isDetail() ); + planeChanged(); + return m_faces.back(); + } + + static void constructStatic( EBrushType type ){ + m_type = type; + Face::m_type = type; + FacePlane::m_type = type; + + g_bp_globals.m_texdefTypeId = BrushType_getTexdefType( type ); + + m_state_point = GlobalShaderCache().capture( "$POINT" ); + m_state_deeppoint = GlobalShaderCache().capture( "$DEEPPOINT" ); + } + static void destroyStatic(){ + GlobalShaderCache().release( "$POINT" ); + GlobalShaderCache().release( "$DEEPPOINT" ); + } + + std::size_t DEBUG_size(){ + return m_faces.size(); + } + + typedef Faces::const_iterator const_iterator; + + const_iterator begin() const { + return m_faces.begin(); + } + const_iterator end() const { + return m_faces.end(); + } + + Face* back(){ + return m_faces.back(); + } + const Face* back() const { + return m_faces.back(); + } + void reserve( std::size_t count ){ + m_faces.reserve( count ); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->reserve( count ); + } + } + void push_back( Faces::value_type face ){ + m_faces.push_back( face ); + if ( m_instanceCounter.m_count != 0 ) { + m_faces.back()->instanceAttach( m_map ); + } + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->push_back( *face ); + ( *i )->DEBUG_verify(); + } + } + void pop_back(){ + if ( m_instanceCounter.m_count != 0 ) { + m_faces.back()->instanceDetach( m_map ); + } + m_faces.pop_back(); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->pop_back(); + ( *i )->DEBUG_verify(); + } + } + void erase( std::size_t index ){ + if ( m_instanceCounter.m_count != 0 ) { + m_faces[index]->instanceDetach( m_map ); + } + m_faces.erase( m_faces.begin() + index ); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->erase( index ); + ( *i )->DEBUG_verify(); + } + } + void connectivityChanged(){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->connectivityChanged(); + } + } + + + void clear(){ + undoSave(); + if ( m_instanceCounter.m_count != 0 ) { + forEachFace_instanceDetach( m_map ); + } + m_faces.clear(); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->clear(); + ( *i )->DEBUG_verify(); + } + } + std::size_t size() const { + return m_faces.size(); + } + bool empty() const { + return m_faces.empty(); + } + +/// \brief Returns true if any face of the brush contributes to the final B-Rep. + bool hasContributingFaces() const { + for ( const_iterator i = begin(); i != end(); ++i ) + { + if ( ( *i )->contributes() ) { + return true; + } + } + return false; + } /// \brief Removes faces that do not contribute to the brush. This is useful for cleaning up after CSG operations on the brush. /// Note: removal of empty faces is not performed during direct brush manipulations, because it would make a manipulation irreversible if it created an empty face. -void removeEmptyFaces(){ - evaluateBRep(); + void removeEmptyFaces(){ + evaluateBRep(); - { - std::size_t i = 0; - while ( i < m_faces.size() ) { - if ( !m_faces[i]->contributes() ) { - erase( i ); - planeChanged(); - } - else + std::size_t i = 0; + while ( i < m_faces.size() ) { - ++i; - } - } - } -} - -/// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush. -void windingForClipPlane( Winding& winding, const Plane3& plane ) const { - FixedWinding buffer[2]; - bool swap = false; - - // get a poly that covers an effectively infinite area - Winding_createInfinite( buffer[swap], plane, m_maxWorldCoord ); - - // chop the poly by all of the other faces - { - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - const Face& clip = *m_faces[i]; - - if ( plane3_equal( clip.plane3(), plane ) - || !plane3_valid( clip.plane3() ) || !plane_unique( i ) - || plane3_opposing( plane, clip.plane3() ) ) { - continue; - } - - if( buffer[swap].points.empty() ){ - //globalErrorStream() << "windingForClipPlane: about to feed empty winding to Winding_Clip\n"; - break; - } - - buffer[!swap].clear(); - -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "clip vs face: " << i << "\n"; -#endif - - { - // flip the plane, because we want to keep the back side - Plane3 clipPlane( vector3_negated( clip.plane3().normal() ), -clip.plane3().dist() ); - Winding_Clip( buffer[swap], plane, clipPlane, i, buffer[!swap] ); - } - -#if BRUSH_CONNECTIVITY_DEBUG - for ( FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k ) - { - if ( vector3_length_squared( vector3_subtracted( ( *k ).vertex, ( *j ).vertex ) ) < 1 ) { - globalOutputStream() << "v: " << std::distance( buffer[!swap].points.begin(), j ) << " tiny edge adjacent to face " << ( *j ).adjacent << "\n"; + if ( !m_faces[i]->contributes() ) { + erase( i ); + planeChanged(); + } + else + { + ++i; } } -#endif - - //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding"); - - swap = !swap; } } - Winding_forFixedWinding( winding, buffer[swap] ); - -#if BRUSH_CONNECTIVITY_DEBUG - Winding_printConnectivity( winding ); - - for ( Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i ) - { - if ( vector3_length_squared( vector3_subtracted( ( *i ).vertex, ( *j ).vertex ) ) < 1 ) { - globalOutputStream() << "v: " << std::distance( winding.begin(), j ) << " tiny edge adjacent to face " << ( *j ).adjacent << "\n"; - } - } -#endif -} - -void update_wireframe( RenderableWireframe& wire, const bool* faces_visible ) const { - wire.m_faceVertex.resize( m_edge_indices.size() ); - wire.m_vertices = m_uniqueVertexPoints.data(); - wire.m_size = 0; - for ( std::size_t i = 0; i < m_edge_faces.size(); ++i ) - { - if ( faces_visible[m_edge_faces[i].first] - || faces_visible[m_edge_faces[i].second] ) { - wire.m_faceVertex[wire.m_size++] = m_edge_indices[i]; - } - } -} - - -void update_faces_wireframe( Array& wire, const bool* faces_visible ) const { - std::size_t count = 0; - for ( std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i ) - { - if ( faces_visible[i] ) { - ++count; - } - } - - wire.resize( count ); - Array::iterator p = wire.begin(); - for ( std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i ) - { - if ( faces_visible[i] ) { - *p++ = m_faceCentroidPoints[i]; - } - } -} - -/// \brief Makes this brush a deep-copy of the \p other. -void copy( const Brush& other ){ - for ( Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i ) - { - addFace( *( *i ) ); - } - planeChanged(); -} - -/// for the only use to quickly check, if about to be transformed brush makes sense -bool contributes() const { - /* plane_unique() ripoff, calling no evaluation */ - auto plane_unique_ = [this]( std::size_t index ) -> bool { - // duplicate plane - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - if ( index != i && !plane3_inside( m_faces[index]->plane3_(), m_faces[i]->plane3_(), index < i ) ) { - return false; - } - } - return true; - }; - - /* windingForClipPlane() ripoff, calling no evaluation */ - auto windingForClipPlane_ = [this, &plane_unique_]( const Plane3& plane ) -> bool { +/// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush. + void windingForClipPlane( Winding& winding, const Plane3& plane ) const { FixedWinding buffer[2]; bool swap = false; @@ -2296,205 +2176,233 @@ bool contributes() const { Winding_createInfinite( buffer[swap], plane, m_maxWorldCoord ); // chop the poly by all of the other faces + { + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + const Face& clip = *m_faces[i]; + + if ( plane3_equal( clip.plane3(), plane ) + || !plane3_valid( clip.plane3() ) || !plane_unique( i ) + || plane3_opposing( plane, clip.plane3() ) ) { + continue; + } + + if( buffer[swap].points.empty() ){ + //globalErrorStream() << "windingForClipPlane: about to feed empty winding to Winding_Clip\n"; + break; + } + + buffer[!swap].clear(); + +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "clip vs face: " << i << "\n"; +#endif + + { + // flip the plane, because we want to keep the back side + Plane3 clipPlane( vector3_negated( clip.plane3().normal() ), -clip.plane3().dist() ); + Winding_Clip( buffer[swap], plane, clipPlane, i, buffer[!swap] ); + } + +#if BRUSH_CONNECTIVITY_DEBUG + for ( FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k ) + { + if ( vector3_length_squared( vector3_subtracted( ( *k ).vertex, ( *j ).vertex ) ) < 1 ) { + globalOutputStream() << "v: " << std::distance( buffer[!swap].points.begin(), j ) << " tiny edge adjacent to face " << ( *j ).adjacent << "\n"; + } + } +#endif + + //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding"); + + swap = !swap; + } + } + + Winding_forFixedWinding( winding, buffer[swap] ); + +#if BRUSH_CONNECTIVITY_DEBUG + Winding_printConnectivity( winding ); + + for ( Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i ) + { + if ( vector3_length_squared( vector3_subtracted( ( *i ).vertex, ( *j ).vertex ) ) < 1 ) { + globalOutputStream() << "v: " << std::distance( winding.begin(), j ) << " tiny edge adjacent to face " << ( *j ).adjacent << "\n"; + } + } +#endif + } + + void update_wireframe( RenderableWireframe& wire, const bool* faces_visible ) const { + wire.m_faceVertex.resize( m_edge_indices.size() ); + wire.m_vertices = m_uniqueVertexPoints.data(); + wire.m_size = 0; + for ( std::size_t i = 0; i < m_edge_faces.size(); ++i ) + { + if ( faces_visible[m_edge_faces[i].first] + || faces_visible[m_edge_faces[i].second] ) { + wire.m_faceVertex[wire.m_size++] = m_edge_indices[i]; + } + } + } + + + void update_faces_wireframe( Array& wire, const bool* faces_visible ) const { + std::size_t count = 0; + for ( std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i ) + { + if ( faces_visible[i] ) { + ++count; + } + } + + wire.resize( count ); + Array::iterator p = wire.begin(); + for ( std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i ) + { + if ( faces_visible[i] ) { + *p++ = m_faceCentroidPoints[i]; + } + } + } + +/// \brief Makes this brush a deep-copy of the \p other. + void copy( const Brush& other ){ + for ( Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i ) + { + addFace( *( *i ) ); + } + planeChanged(); + } + +/// for the only use to quickly check, if about to be transformed brush makes sense + bool contributes() const { + /* plane_unique() ripoff, calling no evaluation */ + auto plane_unique_ = [this]( std::size_t index ) -> bool { + // duplicate plane + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + if ( index != i && !plane3_inside( m_faces[index]->plane3_(), m_faces[i]->plane3_(), index < i ) ) { + return false; + } + } + return true; + }; + + /* windingForClipPlane() ripoff, calling no evaluation */ + auto windingForClipPlane_ = [this, &plane_unique_]( const Plane3& plane ) -> bool { + FixedWinding buffer[2]; + bool swap = false; + + // get a poly that covers an effectively infinite area + Winding_createInfinite( buffer[swap], plane, m_maxWorldCoord ); + + // chop the poly by all of the other faces + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + const Face& clip = *m_faces[i]; + + if ( plane3_equal( clip.plane3_(), plane ) + || !plane3_valid( clip.plane3_() ) || !plane_unique_( i ) + || plane3_opposing( plane, clip.plane3_() ) ) { + continue; + } + + if( buffer[swap].points.empty() ){ + break; + } + + buffer[!swap].clear(); + + { + // flip the plane, because we want to keep the back side + Plane3 clipPlane( vector3_negated( clip.plane3_().normal() ), -clip.plane3_().dist() ); + Winding_Clip( buffer[swap], plane, clipPlane, i, buffer[!swap] ); + } + swap = !swap; + } + + return buffer[swap].size() > 2; + }; + + + std::size_t contributing = 0; + for ( std::size_t i = 0; i < m_faces.size(); ++i ) { - const Face& clip = *m_faces[i]; + Face& f = *m_faces[i]; - if ( plane3_equal( clip.plane3_(), plane ) - || !plane3_valid( clip.plane3_() ) || !plane_unique_( i ) - || plane3_opposing( plane, clip.plane3_() ) ) { - continue; - } - - if( buffer[swap].points.empty() ){ - break; - } - - buffer[!swap].clear(); - - { - // flip the plane, because we want to keep the back side - Plane3 clipPlane( vector3_negated( clip.plane3_().normal() ), -clip.plane3_().dist() ); - Winding_Clip( buffer[swap], plane, clipPlane, i, buffer[!swap] ); - } - swap = !swap; - } - - return buffer[swap].size() > 2; - }; - - - std::size_t contributing = 0; - - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - Face& f = *m_faces[i]; - - if ( plane3_valid( f.plane3_() ) && plane_unique_( i ) ) { - if( windingForClipPlane_( f.plane3_() ) ){ - ++contributing; - if( contributing > 3 ) - return true; + if ( plane3_valid( f.plane3_() ) && plane_unique_( i ) ) { + if( windingForClipPlane_( f.plane3_() ) ){ + ++contributing; + if( contributing > 3 ) + return true; + } } } + return false; } - return false; -} private: -void edge_push_back( FaceVertexId faceVertex ){ - m_select_edges.push_back( SelectableEdge( m_faces, faceVertex ) ); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->edge_push_back( m_select_edges.back() ); + void edge_push_back( FaceVertexId faceVertex ){ + m_select_edges.push_back( SelectableEdge( m_faces, faceVertex ) ); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->edge_push_back( m_select_edges.back() ); + } } -} -void edge_clear(){ - m_select_edges.clear(); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->edge_clear(); + void edge_clear(){ + m_select_edges.clear(); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->edge_clear(); + } } -} -void vertex_push_back( FaceVertexId faceVertex ){ - m_select_vertices.push_back( SelectableVertex( m_faces, faceVertex ) ); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->vertex_push_back( m_select_vertices.back() ); + void vertex_push_back( FaceVertexId faceVertex ){ + m_select_vertices.push_back( SelectableVertex( m_faces, faceVertex ) ); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->vertex_push_back( m_select_vertices.back() ); + } } -} -void vertex_clear(){ - m_select_vertices.clear(); - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->vertex_clear(); + void vertex_clear(){ + m_select_vertices.clear(); + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->vertex_clear(); + } } -} /// \brief Returns true if the face identified by \p index is preceded by another plane that takes priority over it. -bool plane_unique( std::size_t index ) const { - // duplicate plane - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - if ( index != i && !plane3_inside( m_faces[index]->plane3(), m_faces[i]->plane3(), index < i ) ) { - return false; + bool plane_unique( std::size_t index ) const { + // duplicate plane + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + if ( index != i && !plane3_inside( m_faces[index]->plane3(), m_faces[i]->plane3(), index < i ) ) { + return false; + } } + return true; } - return true; -} /// \brief Removes edges that are smaller than the tolerance used when generating brush windings. -void removeDegenerateEdges(){ - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - Winding& winding = m_faces[i]->getWinding(); - for ( Winding::iterator j = winding.begin(); j != winding.end(); ) - { - std::size_t index = std::distance( winding.begin(), j ); - std::size_t next = Winding_next( winding, index ); - if ( Edge_isDegenerate( winding[index].vertex, winding[next].vertex ) ) { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n"; -#endif - Winding& other = m_faces[winding[index].adjacent]->getWinding(); - std::size_t adjacent = Winding_FindAdjacent( other, i ); - if ( adjacent != c_brush_maxFaces ) { - other.erase( other.begin() + adjacent ); - } - winding.erase( j ); - } - else - { - ++j; - } - } - } -} - -/// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information. -void removeDegenerateFaces(){ - // save adjacency info for degenerate faces - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - Winding& degen = m_faces[i]->getWinding(); - - if ( degen.numpoints == 2 ) { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n"; -#endif - // this is an "edge" face, where the plane touches the edge of the brush - { - Winding& winding = m_faces[degen[0].adjacent]->getWinding(); - std::size_t index = Winding_FindAdjacent( winding, i ); - if ( index != c_brush_maxFaces ) { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n"; -#endif - winding[index].adjacent = degen[1].adjacent; - } - } - - { - Winding& winding = m_faces[degen[1].adjacent]->getWinding(); - std::size_t index = Winding_FindAdjacent( winding, i ); - if ( index != c_brush_maxFaces ) { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n"; -#endif - winding[index].adjacent = degen[0].adjacent; - } - } - - degen.resize( 0 ); - } - } -} - -/// \brief Removes edges that have the same adjacent-face as their immediate neighbour. -void removeDuplicateEdges(){ - // verify face connectivity graph - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - //if(m_faces[i]->contributes()) - { - Winding& winding = m_faces[i]->getWinding(); - for ( std::size_t j = 0; j != winding.numpoints; ) - { - std::size_t next = Winding_next( winding, j ); - if ( winding[j].adjacent == winding[next].adjacent ) { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n"; -#endif - winding.erase( winding.begin() + next ); - } - else - { - ++j; - } - } - } - } -} - -/// \brief Removes edges that do not have a matching pair in their adjacent-face. -void verifyConnectivityGraph(){ - // verify face connectivity graph - for ( std::size_t i = 0; i < m_faces.size(); ++i ) - { - //if(m_faces[i]->contributes()) + void removeDegenerateEdges(){ + for ( std::size_t i = 0; i < m_faces.size(); ++i ) { Winding& winding = m_faces[i]->getWinding(); for ( Winding::iterator j = winding.begin(); j != winding.end(); ) { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << ( *j ).adjacent << "\n"; -#endif - // remove unidirectional graph edges - if ( ( *j ).adjacent == c_brush_maxFaces - || Winding_FindAdjacent( m_faces[( *j ).adjacent]->getWinding(), i ) == c_brush_maxFaces ) { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << ( *j ).adjacent << "\n"; + std::size_t index = std::distance( winding.begin(), j ); + std::size_t next = Winding_next( winding, index ); + if ( Edge_isDegenerate( winding[index].vertex, winding[next].vertex ) ) { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n"; #endif + Winding& other = m_faces[winding[index].adjacent]->getWinding(); + std::size_t adjacent = Winding_FindAdjacent( other, i ); + if ( adjacent != c_brush_maxFaces ) { + other.erase( other.begin() + adjacent ); + } winding.erase( j ); } else @@ -2504,71 +2412,165 @@ void verifyConnectivityGraph(){ } } } -} - -/// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid. -bool isBounded(){ - for ( const_iterator i = begin(); i != end(); ++i ) - { - if ( !( *i )->is_bounded() ) { - return false; - } - } - return true; -} - -/// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates. -bool buildWindings(){ - - { - m_aabb_local = AABB(); - - if( m_faces.size() ) - m_faces[0]->plane3(); //force evaluateTransform() first, as m_faces is changed during vertexModeTransform +/// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information. + void removeDegenerateFaces(){ + // save adjacency info for degenerate faces for ( std::size_t i = 0; i < m_faces.size(); ++i ) { - Face& f = *m_faces[i]; + Winding& degen = m_faces[i]->getWinding(); - if ( !plane3_valid( f.plane3() ) || !plane_unique( i ) ) { - f.getWinding().resize( 0 ); - } - else - { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "face: " << i << "\n"; + if ( degen.numpoints == 2 ) { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n"; #endif - windingForClipPlane( f.getWinding(), f.plane3() ); - - // update brush bounds - const Winding& winding = f.getWinding(); - for ( Winding::const_iterator i = winding.begin(); i != winding.end(); ++i ) + // this is an "edge" face, where the plane touches the edge of the brush { - aabb_extend_by_point_safe( m_aabb_local, ( *i ).vertex ); + Winding& winding = m_faces[degen[0].adjacent]->getWinding(); + std::size_t index = Winding_FindAdjacent( winding, i ); + if ( index != c_brush_maxFaces ) { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n"; +#endif + winding[index].adjacent = degen[1].adjacent; + } } - // update texture coordinates - f.EmitTextureCoordinates(); + { + Winding& winding = m_faces[degen[1].adjacent]->getWinding(); + std::size_t index = Winding_FindAdjacent( winding, i ); + if ( index != c_brush_maxFaces ) { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n"; +#endif + winding[index].adjacent = degen[0].adjacent; + } + } + + degen.resize( 0 ); } } } - bool degenerate = !isBounded(); - - if ( !degenerate ) { - // clean up connectivity information. - // these cleanups must be applied in a specific order. - removeDegenerateEdges(); - removeDegenerateFaces(); - removeDuplicateEdges(); - verifyConnectivityGraph(); +/// \brief Removes edges that have the same adjacent-face as their immediate neighbour. + void removeDuplicateEdges(){ + // verify face connectivity graph + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + //if(m_faces[i]->contributes()) + { + Winding& winding = m_faces[i]->getWinding(); + for ( std::size_t j = 0; j != winding.numpoints; ) + { + std::size_t next = Winding_next( winding, j ); + if ( winding[j].adjacent == winding[next].adjacent ) { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n"; +#endif + winding.erase( winding.begin() + next ); + } + else + { + ++j; + } + } + } + } } - return degenerate; -} +/// \brief Removes edges that do not have a matching pair in their adjacent-face. + void verifyConnectivityGraph(){ + // verify face connectivity graph + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + //if(m_faces[i]->contributes()) + { + Winding& winding = m_faces[i]->getWinding(); + for ( Winding::iterator j = winding.begin(); j != winding.end(); ) + { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << ( *j ).adjacent << "\n"; +#endif + // remove unidirectional graph edges + if ( ( *j ).adjacent == c_brush_maxFaces + || Winding_FindAdjacent( m_faces[( *j ).adjacent]->getWinding(), i ) == c_brush_maxFaces ) { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << ( *j ).adjacent << "\n"; +#endif + winding.erase( j ); + } + else + { + ++j; + } + } + } + } + } + +/// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid. + bool isBounded(){ + for ( const_iterator i = begin(); i != end(); ++i ) + { + if ( !( *i )->is_bounded() ) { + return false; + } + } + return true; + } + +/// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates. + bool buildWindings(){ + + { + m_aabb_local = AABB(); + + if( m_faces.size() ) + m_faces[0]->plane3(); //force evaluateTransform() first, as m_faces is changed during vertexModeTransform + + for ( std::size_t i = 0; i < m_faces.size(); ++i ) + { + Face& f = *m_faces[i]; + + if ( !plane3_valid( f.plane3() ) || !plane_unique( i ) ) { + f.getWinding().resize( 0 ); + } + else + { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "face: " << i << "\n"; +#endif + windingForClipPlane( f.getWinding(), f.plane3() ); + + // update brush bounds + const Winding& winding = f.getWinding(); + for ( Winding::const_iterator i = winding.begin(); i != winding.end(); ++i ) + { + aabb_extend_by_point_safe( m_aabb_local, ( *i ).vertex ); + } + + // update texture coordinates + f.EmitTextureCoordinates(); + } + } + } + + bool degenerate = !isBounded(); + + if ( !degenerate ) { + // clean up connectivity information. + // these cleanups must be applied in a specific order. + removeDegenerateEdges(); + removeDegenerateFaces(); + removeDuplicateEdges(); + verifyConnectivityGraph(); + } + + return degenerate; + } /// \brief Constructs the face windings and updates anything that depends on them. -void buildBRep(); + void buildBRep(); }; @@ -2577,30 +2579,30 @@ class FaceInstance; class FaceInstanceSet { -typedef SelectionList FaceInstances; -FaceInstances m_faceInstances; + typedef SelectionList FaceInstances; + FaceInstances m_faceInstances; public: -void insert( FaceInstance& faceInstance ){ - m_faceInstances.append( faceInstance ); -} -void erase( FaceInstance& faceInstance ){ - m_faceInstances.erase( faceInstance ); -} - -template -void foreach( Functor functor ){ - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - functor( *( *i ) ); + void insert( FaceInstance& faceInstance ){ + m_faceInstances.append( faceInstance ); + } + void erase( FaceInstance& faceInstance ){ + m_faceInstances.erase( faceInstance ); } -} -bool empty() const { - return m_faceInstances.empty(); -} -FaceInstance& last() const { - return m_faceInstances.back(); -} + template + void foreach( Functor functor ){ + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + functor( *( *i ) ); + } + } + + bool empty() const { + return m_faceInstances.empty(); + } + FaceInstance& last() const { + return m_faceInstances.back(); + } }; extern FaceInstanceSet g_SelectedFaceInstances; @@ -2645,514 +2647,514 @@ inline bool triangles_same_winding( const BasicVector3& x1, const Basic class VectorLightList : public LightList { -typedef std::vector Lights; -Lights m_lights; + typedef std::vector Lights; + Lights m_lights; public: -void addLight( const RendererLight& light ){ - m_lights.push_back( &light ); -} -void clear(){ - m_lights.clear(); -} -void evaluateLights() const { -} -void lightsChanged() const { -} -void forEachLight( const RendererLightCallback& callback ) const { - for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) - { - callback( *( *i ) ); + void addLight( const RendererLight& light ){ + m_lights.push_back( &light ); + } + void clear(){ + m_lights.clear(); + } + void evaluateLights() const { + } + void lightsChanged() const { + } + void forEachLight( const RendererLightCallback& callback ) const { + for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) + { + callback( *( *i ) ); + } } -} }; class FaceInstance { -Face* m_face; -ObservedSelectable m_selectable; -ObservedSelectable m_selectableVertices; -ObservedSelectable m_selectableEdges; -SelectionChangeCallback m_selectionChanged; + Face* m_face; + ObservedSelectable m_selectable; + ObservedSelectable m_selectableVertices; + ObservedSelectable m_selectableEdges; + SelectionChangeCallback m_selectionChanged; -VertexSelection m_vertexSelection; -VertexSelection m_edgeSelection; + VertexSelection m_vertexSelection; + VertexSelection m_edgeSelection; public: -mutable VectorLightList m_lights; + mutable VectorLightList m_lights; -FaceInstance( Face& face, const SelectionChangeCallback& observer ) : - m_face( &face ), - m_selectable( SelectedChangedCaller( *this ) ), - m_selectableVertices( observer ), - m_selectableEdges( observer ), - m_selectionChanged( observer ){ -} -FaceInstance( const FaceInstance& other ) : - m_face( other.m_face ), - m_selectable( SelectedChangedCaller( *this ) ), - m_selectableVertices( other.m_selectableVertices ), - m_selectableEdges( other.m_selectableEdges ), - m_selectionChanged( other.m_selectionChanged ){ -} -FaceInstance& operator=( const FaceInstance& other ){ - m_face = other.m_face; - return *this; -} - -Face& getFace(){ - return *m_face; -} -const Face& getFace() const { - return *m_face; -} - -void selectedChanged( const Selectable& selectable ){ - if ( selectable.isSelected() ) { - g_SelectedFaceInstances.insert( *this ); + FaceInstance( Face& face, const SelectionChangeCallback& observer ) : + m_face( &face ), + m_selectable( SelectedChangedCaller( *this ) ), + m_selectableVertices( observer ), + m_selectableEdges( observer ), + m_selectionChanged( observer ){ } - else - { - g_SelectedFaceInstances.erase( *this ); + FaceInstance( const FaceInstance& other ) : + m_face( other.m_face ), + m_selectable( SelectedChangedCaller( *this ) ), + m_selectableVertices( other.m_selectableVertices ), + m_selectableEdges( other.m_selectableEdges ), + m_selectionChanged( other.m_selectionChanged ){ } - m_selectionChanged( selectable ); -} -typedef MemberCaller1 SelectedChangedCaller; - -bool selectedVertices() const { - return !m_vertexSelection.empty(); -} -bool selectedEdges() const { - return !m_edgeSelection.empty(); -} -bool isSelected() const { - return m_selectable.isSelected(); -} - -bool selectedComponents() const { - return selectedVertices() || selectedEdges() || isSelected(); -} -bool selectedComponents( SelectionSystem::EComponentMode mode ) const { - switch ( mode ) - { - case SelectionSystem::eVertex: - return selectedVertices(); - case SelectionSystem::eEdge: - return selectedEdges(); - case SelectionSystem::eFace: - return isSelected(); - default: - return false; + FaceInstance& operator=( const FaceInstance& other ){ + m_face = other.m_face; + return *this; } -} -void setSelected( SelectionSystem::EComponentMode mode, bool select ){ - switch ( mode ) - { - case SelectionSystem::eFace: - m_selectable.setSelected( select ); - break; - case SelectionSystem::eVertex: - ASSERT_MESSAGE( !select, "select-all not supported" ); - m_vertexSelection.clear(); - m_selectableVertices.setSelected( false ); - break; - case SelectionSystem::eEdge: - ASSERT_MESSAGE( !select, "select-all not supported" ); - - m_edgeSelection.clear(); - m_selectableEdges.setSelected( false ); - break; - default: - break; + Face& getFace(){ + return *m_face; + } + const Face& getFace() const { + return *m_face; } -} -template -void SelectedVertices_foreach( Functor functor ) const { - for ( VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i ) - { - std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *i ); - if ( index != c_brush_maxFaces ) { - functor( getFace().getWinding()[index].vertex ); + void selectedChanged( const Selectable& selectable ){ + if ( selectable.isSelected() ) { + g_SelectedFaceInstances.insert( *this ); + } + else + { + g_SelectedFaceInstances.erase( *this ); + } + m_selectionChanged( selectable ); + } + typedef MemberCaller1 SelectedChangedCaller; + + bool selectedVertices() const { + return !m_vertexSelection.empty(); + } + bool selectedEdges() const { + return !m_edgeSelection.empty(); + } + bool isSelected() const { + return m_selectable.isSelected(); + } + + bool selectedComponents() const { + return selectedVertices() || selectedEdges() || isSelected(); + } + bool selectedComponents( SelectionSystem::EComponentMode mode ) const { + switch ( mode ) + { + case SelectionSystem::eVertex: + return selectedVertices(); + case SelectionSystem::eEdge: + return selectedEdges(); + case SelectionSystem::eFace: + return isSelected(); + default: + return false; } } -} -template -void SelectedEdges_foreach( Functor functor ) const { - for ( VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i ) + void setSelected( SelectionSystem::EComponentMode mode, bool select ){ + switch ( mode ) + { + case SelectionSystem::eFace: + m_selectable.setSelected( select ); + break; + case SelectionSystem::eVertex: + ASSERT_MESSAGE( !select, "select-all not supported" ); + + m_vertexSelection.clear(); + m_selectableVertices.setSelected( false ); + break; + case SelectionSystem::eEdge: + ASSERT_MESSAGE( !select, "select-all not supported" ); + + m_edgeSelection.clear(); + m_selectableEdges.setSelected( false ); + break; + default: + break; + } + } + + template + void SelectedVertices_foreach( Functor functor ) const { + for ( VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i ) + { + std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *i ); + if ( index != c_brush_maxFaces ) { + functor( getFace().getWinding()[index].vertex ); + } + } + } + template + void SelectedEdges_foreach( Functor functor ) const { + for ( VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i ) + { + std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *i ); + if ( index != c_brush_maxFaces ) { + const Winding& winding = getFace().getWinding(); + std::size_t adjacent = Winding_next( winding, index ); + functor( vector3_mid( winding[index].vertex, winding[adjacent].vertex ) ); + } + } + } + template + void SelectedFaces_foreach( Functor functor ) const { + if ( isSelected() ) { + functor( centroid() ); + } + } + + template + void SelectedComponents_foreach( Functor functor ) const { + SelectedVertices_foreach( functor ); + SelectedEdges_foreach( functor ); + SelectedFaces_foreach( functor ); + } + + void iterate_selected( AABB& aabb ) const { + SelectedComponents_foreach( AABBExtendByPoint( aabb ) ); + } + + void gatherSelectedComponents( const Vector3Callback& callback ) const { + const Winding& winding = getFace().getWinding(); + if( isSelected() ) + for ( std::size_t i = 0; i != winding.numpoints; ++i ) + callback( winding[i].vertex ); + for ( VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i ){ + std::size_t index = Winding_FindAdjacent( winding, *i ); + if ( index != c_brush_maxFaces ) { + callback( winding[index].vertex ); + } + } + for ( VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i ){ + std::size_t index = Winding_FindAdjacent( winding, *i ); + if ( index != c_brush_maxFaces ) { + std::size_t adjacent = Winding_next( winding, index ); + callback( winding[index].vertex ); + callback( winding[adjacent].vertex ); + } + } + } + + class RenderablePointVectorPushBack { - std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *i ); - if ( index != c_brush_maxFaces ) { - const Winding& winding = getFace().getWinding(); - std::size_t adjacent = Winding_next( winding, index ); - functor( vector3_mid( winding[index].vertex, winding[adjacent].vertex ) ); + RenderablePointVector& m_points; + public: + RenderablePointVectorPushBack( RenderablePointVector& points ) : m_points( points ){ + } + void operator()( const Vector3& point ) const { + m_points.push_back( pointvertex_for_windingpoint( point, colour_selected ) ); + } + }; + + void iterate_selected( RenderablePointVector& points ) const { + SelectedComponents_foreach( RenderablePointVectorPushBack( points ) ); + } + + bool intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { + return m_face->intersectVolume( volume, localToWorld ); + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + if ( !m_face->isFiltered() && m_face->contributes() && intersectVolume( volume, localToWorld ) ) { + renderer.PushState(); + renderer.Highlight( Renderer::ePrimitiveWire ); + if ( selectedComponents() ) { + renderer.Highlight( Renderer::EHighlightMode( Renderer::eFace | Renderer::eFaceWire ) ); + } + m_face->render( renderer, localToWorld ); + renderer.PopState(); } } -} -template -void SelectedFaces_foreach( Functor functor ) const { - if ( isSelected() ) { - functor( centroid() ); - } -} -template -void SelectedComponents_foreach( Functor functor ) const { - SelectedVertices_foreach( functor ); - SelectedEdges_foreach( functor ); - SelectedFaces_foreach( functor ); -} - -void iterate_selected( AABB& aabb ) const { - SelectedComponents_foreach( AABBExtendByPoint( aabb ) ); -} - -void gatherSelectedComponents( const Vector3Callback& callback ) const { - const Winding& winding = getFace().getWinding(); - if( isSelected() ) - for ( std::size_t i = 0; i != winding.numpoints; ++i ) - callback( winding[i].vertex ); - for ( VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i ){ - std::size_t index = Winding_FindAdjacent( winding, *i ); - if ( index != c_brush_maxFaces ) { - callback( winding[index].vertex ); + void testSelect( SelectionTest& test, SelectionIntersection& best ) const { + if ( !m_face->isFiltered() ) { + m_face->testSelect( test, best ); } } - for ( VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i ){ - std::size_t index = Winding_FindAdjacent( winding, *i ); - if ( index != c_brush_maxFaces ) { - std::size_t adjacent = Winding_next( winding, index ); - callback( winding[index].vertex ); - callback( winding[adjacent].vertex ); - } - } -} - -class RenderablePointVectorPushBack -{ -RenderablePointVector& m_points; -public: -RenderablePointVectorPushBack( RenderablePointVector& points ) : m_points( points ){ -} -void operator()( const Vector3& point ) const { - m_points.push_back( pointvertex_for_windingpoint( point, colour_selected ) ); -} -}; - -void iterate_selected( RenderablePointVector& points ) const { - SelectedComponents_foreach( RenderablePointVectorPushBack( points ) ); -} - -bool intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { - return m_face->intersectVolume( volume, localToWorld ); -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - if ( !m_face->isFiltered() && m_face->contributes() && intersectVolume( volume, localToWorld ) ) { - renderer.PushState(); - renderer.Highlight( Renderer::ePrimitiveWire ); - if ( selectedComponents() ) { - renderer.Highlight( Renderer::EHighlightMode( Renderer::eFace | Renderer::eFaceWire ) ); - } - m_face->render( renderer, localToWorld ); - renderer.PopState(); - } -} - -void testSelect( SelectionTest& test, SelectionIntersection& best ) const { - if ( !m_face->isFiltered() ) { - m_face->testSelect( test, best ); - } -} -void testSelect( Selector& selector, SelectionTest& test ){ - SelectionIntersection best; - testSelect( test, best ); - if ( best.valid() ) { - Selector_add( selector, m_selectable, best ); - } -} -void testSelect_centroid( Selector& selector, SelectionTest& test ){ - if ( m_face->contributes() && !m_face->isFiltered() ) { + void testSelect( Selector& selector, SelectionTest& test ){ SelectionIntersection best; - m_face->testSelect_centroid( test, best ); + testSelect( test, best ); if ( best.valid() ) { Selector_add( selector, m_selectable, best ); } } -} + void testSelect_centroid( Selector& selector, SelectionTest& test ){ + if ( m_face->contributes() && !m_face->isFiltered() ) { + SelectionIntersection best; + m_face->testSelect_centroid( test, best ); + if ( best.valid() ) { + Selector_add( selector, m_selectable, best ); + } + } + } -void addSelectable( Selector& selector ){ - Selector_add( selector, m_selectable ); -} - -void selectReversedPlane( Selector& selector, const SelectedPlanes& selectedPlanes ){ - if ( selectedPlanes.contains( plane3_flipped( getFace().plane3() ) ) ) { + void addSelectable( Selector& selector ){ Selector_add( selector, m_selectable ); } -} -bool trySelectPlane( const SelectionTest& test ){ - const Vector3 projected = vector4_projected( matrix4_transformed_vector4( test.getVolume().GetViewMatrix(), Vector4( getFace().centroid(), 1 ) ) ); - const Vector3 closest_point = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, projected[2], 1 ) ) ); - for ( Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i ){ - if ( vector3_dot( getFace().plane3().normal(), closest_point - ( *i ).vertex ) < 0.005 ) /* epsilon to prevent almost perpendicular faces pickup */ - return false; + void selectReversedPlane( Selector& selector, const SelectedPlanes& selectedPlanes ){ + if ( selectedPlanes.contains( plane3_flipped( getFace().plane3() ) ) ) { + Selector_add( selector, m_selectable ); + } } - return true; -} -void transformComponents( const Matrix4& matrix ){ - if ( isSelected() ) { - m_face->transform( matrix, false ); + bool trySelectPlane( const SelectionTest& test ){ + const Vector3 projected = vector4_projected( matrix4_transformed_vector4( test.getVolume().GetViewMatrix(), Vector4( getFace().centroid(), 1 ) ) ); + const Vector3 closest_point = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, projected[2], 1 ) ) ); + for ( Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i ){ + if ( vector3_dot( getFace().plane3().normal(), closest_point - ( *i ).vertex ) < 0.005 ) /* epsilon to prevent almost perpendicular faces pickup */ + return false; + } + return true; } - if ( selectedVertices() ) { - if ( m_vertexSelection.size() == 1 ) { - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); - m_face->assign_planepts( m_face->m_move_planeptsTransformed ); - } - else if ( m_vertexSelection.size() == 2 ) { - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); - m_face->assign_planepts( m_face->m_move_planeptsTransformed ); - } - else if ( m_vertexSelection.size() >= 3 ) { - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); - m_face->assign_planepts( m_face->m_move_planeptsTransformed ); - } - } - if ( selectedEdges() ) { - if ( m_edgeSelection.size() == 1 ) { - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); - m_face->assign_planepts( m_face->m_move_planeptsTransformed ); - } - else if ( m_edgeSelection.size() >= 2 ) { - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); - matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); - m_face->assign_planepts( m_face->m_move_planeptsTransformed ); - } - } - if ( g_brush_textureVertexlock_enabled && ( selectedVertices() || selectedEdges() ) ) { - m_face->texdef_from_points(); - } -} -void snapto( float snap ){ - m_face->snapto( snap ); -} + void transformComponents( const Matrix4& matrix ){ + if ( isSelected() ) { + m_face->transform( matrix, false ); + } + if ( selectedVertices() ) { + if ( m_vertexSelection.size() == 1 ) { + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); + m_face->assign_planepts( m_face->m_move_planeptsTransformed ); + } + else if ( m_vertexSelection.size() == 2 ) { + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); + m_face->assign_planepts( m_face->m_move_planeptsTransformed ); + } + else if ( m_vertexSelection.size() >= 3 ) { + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); + m_face->assign_planepts( m_face->m_move_planeptsTransformed ); + } + } + if ( selectedEdges() ) { + if ( m_edgeSelection.size() == 1 ) { + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); + m_face->assign_planepts( m_face->m_move_planeptsTransformed ); + } + else if ( m_edgeSelection.size() >= 2 ) { + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[0] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[1] ); + matrix4_transform_point( matrix, m_face->m_move_planeptsTransformed[2] ); + m_face->assign_planepts( m_face->m_move_planeptsTransformed ); + } + } + if ( g_brush_textureVertexlock_enabled && ( selectedVertices() || selectedEdges() ) ) { + m_face->texdef_from_points(); + } + } -void snapComponents( float snap ){ - if ( isSelected() ) { - snapto( snap ); + void snapto( float snap ){ + m_face->snapto( snap ); } - if ( selectedVertices() ) { - vector3_snap( m_face->m_move_planepts[0], snap ); - vector3_snap( m_face->m_move_planepts[1], snap ); - vector3_snap( m_face->m_move_planepts[2], snap ); - m_face->assign_planepts( m_face->m_move_planepts ); - planepts_assign( m_face->m_move_planeptsTransformed, m_face->m_move_planepts ); - m_face->freezeTransform(); + + void snapComponents( float snap ){ + if ( isSelected() ) { + snapto( snap ); + } + if ( selectedVertices() ) { + vector3_snap( m_face->m_move_planepts[0], snap ); + vector3_snap( m_face->m_move_planepts[1], snap ); + vector3_snap( m_face->m_move_planepts[2], snap ); + m_face->assign_planepts( m_face->m_move_planepts ); + planepts_assign( m_face->m_move_planeptsTransformed, m_face->m_move_planepts ); + m_face->freezeTransform(); + } + if ( selectedEdges() ) { + vector3_snap( m_face->m_move_planepts[0], snap ); + vector3_snap( m_face->m_move_planepts[1], snap ); + vector3_snap( m_face->m_move_planepts[2], snap ); + m_face->assign_planepts( m_face->m_move_planepts ); + planepts_assign( m_face->m_move_planeptsTransformed, m_face->m_move_planepts ); + m_face->freezeTransform(); + } } - if ( selectedEdges() ) { - vector3_snap( m_face->m_move_planepts[0], snap ); - vector3_snap( m_face->m_move_planepts[1], snap ); - vector3_snap( m_face->m_move_planepts[2], snap ); - m_face->assign_planepts( m_face->m_move_planepts ); - planepts_assign( m_face->m_move_planeptsTransformed, m_face->m_move_planepts ); - m_face->freezeTransform(); - } -} #if Update_move_planepts_vertex -void update_move_planepts_vertex( std::size_t index ){ - m_face->update_move_planepts_vertex( index, m_face->m_move_planepts ); -} -void update_move_planepts_vertex2( std::size_t index, std::size_t other ){ - if( m_face->contributes() ){ - const std::size_t numpoints = m_face->getWinding().numpoints; - ASSERT_MESSAGE( index < numpoints, "select_vertex: invalid index" ); + void update_move_planepts_vertex( std::size_t index ){ + m_face->update_move_planepts_vertex( index, m_face->m_move_planepts ); + } + void update_move_planepts_vertex2( std::size_t index, std::size_t other ){ + if( m_face->contributes() ){ + const std::size_t numpoints = m_face->getWinding().numpoints; + ASSERT_MESSAGE( index < numpoints, "select_vertex: invalid index" ); - const std::size_t opposite = Winding_Opposite( m_face->getWinding(), index, other ); + const std::size_t opposite = Winding_Opposite( m_face->getWinding(), index, other ); - if ( triangle_reversed( index, other, opposite ) ) { - std::swap( index, other ); - } + if ( triangle_reversed( index, other, opposite ) ) { + std::swap( index, other ); + } - ///! this actually happens with ON_EPSILON 1.0 / ( 1 << 8 ) - ASSERT_MESSAGE( - triangles_same_winding( - m_face->getWinding()[opposite].vertex, - m_face->getWinding()[index].vertex, - m_face->getWinding()[other].vertex, - m_face->getWinding()[0].vertex, - m_face->getWinding()[1].vertex, - m_face->getWinding()[2].vertex - ), - "update_move_planepts_vertex2: error" + ///! this actually happens with ON_EPSILON 1.0 / ( 1 << 8 ) + ASSERT_MESSAGE( + triangles_same_winding( + m_face->getWinding()[opposite].vertex, + m_face->getWinding()[index].vertex, + m_face->getWinding()[other].vertex, + m_face->getWinding()[0].vertex, + m_face->getWinding()[1].vertex, + m_face->getWinding()[2].vertex + ), + "update_move_planepts_vertex2: error" ); - m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex; - m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex; - m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex; - planepts_quantise( m_face->m_move_planepts, GRID_MIN ); // winding points are very inaccurate + m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex; + m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex; + m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex; + planepts_quantise( m_face->m_move_planepts, GRID_MIN ); // winding points are very inaccurate + } } -} #endif -void update_selection_vertex(){ - if ( m_vertexSelection.size() == 0 ) { - m_selectableVertices.setSelected( false ); - } - else - { - m_selectableVertices.setSelected( true ); + void update_selection_vertex(){ + if ( m_vertexSelection.size() == 0 ) { + m_selectableVertices.setSelected( false ); + } + else + { + m_selectableVertices.setSelected( true ); #if Update_move_planepts_vertex - if ( m_vertexSelection.size() == 1 ) { - std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_vertexSelection.begin() ); + if ( m_vertexSelection.size() == 1 ) { + std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_vertexSelection.begin() ); - if ( index != c_brush_maxFaces ) { - update_move_planepts_vertex( index ); + if ( index != c_brush_maxFaces ) { + update_move_planepts_vertex( index ); + } } - } - else if ( m_vertexSelection.size() == 2 ) { - std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_vertexSelection.begin() ); - std::size_t other = Winding_FindAdjacent( getFace().getWinding(), *( ++m_vertexSelection.begin() ) ); + else if ( m_vertexSelection.size() == 2 ) { + std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_vertexSelection.begin() ); + std::size_t other = Winding_FindAdjacent( getFace().getWinding(), *( ++m_vertexSelection.begin() ) ); - if ( index != c_brush_maxFaces - && other != c_brush_maxFaces ) { - update_move_planepts_vertex2( index, other ); + if ( index != c_brush_maxFaces + && other != c_brush_maxFaces ) { + update_move_planepts_vertex2( index, other ); + } } - } #endif + } } -} -void select_vertex( std::size_t index, bool select ){ - if ( select ) { - VertexSelection_insert( m_vertexSelection, getFace().getWinding()[index].adjacent ); - } - else - { - VertexSelection_erase( m_vertexSelection, getFace().getWinding()[index].adjacent ); + void select_vertex( std::size_t index, bool select ){ + if ( select ) { + VertexSelection_insert( m_vertexSelection, getFace().getWinding()[index].adjacent ); + } + else + { + VertexSelection_erase( m_vertexSelection, getFace().getWinding()[index].adjacent ); + } + + SceneChangeNotify(); + update_selection_vertex(); } - SceneChangeNotify(); - update_selection_vertex(); -} - -bool selected_vertex( std::size_t index ) const { - return VertexSelection_find( m_vertexSelection, getFace().getWinding()[index].adjacent ) != m_vertexSelection.end(); -} - -void update_move_planepts_edge( std::size_t index ){ - if( m_face->contributes() ){ - std::size_t numpoints = m_face->getWinding().numpoints; - ASSERT_MESSAGE( index < numpoints, "select_edge: invalid index" ); - - std::size_t adjacent = Winding_next( m_face->getWinding(), index ); - std::size_t opposite = Winding_Opposite( m_face->getWinding(), index ); - m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex; - m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex; - m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex; -// planepts_quantise( m_face->m_move_planepts, GRID_MIN ); // winding points are very inaccurate + bool selected_vertex( std::size_t index ) const { + return VertexSelection_find( m_vertexSelection, getFace().getWinding()[index].adjacent ) != m_vertexSelection.end(); } -} -void update_selection_edge(){ - if ( m_edgeSelection.size() == 0 ) { + + void update_move_planepts_edge( std::size_t index ){ + if( m_face->contributes() ){ + std::size_t numpoints = m_face->getWinding().numpoints; + ASSERT_MESSAGE( index < numpoints, "select_edge: invalid index" ); + + std::size_t adjacent = Winding_next( m_face->getWinding(), index ); + std::size_t opposite = Winding_Opposite( m_face->getWinding(), index ); + m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex; + m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex; + m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex; +// planepts_quantise( m_face->m_move_planepts, GRID_MIN ); // winding points are very inaccurate + } + } + void update_selection_edge(){ + if ( m_edgeSelection.size() == 0 ) { + m_selectableEdges.setSelected( false ); + } + else + { + m_selectableEdges.setSelected( true ); + + if ( m_edgeSelection.size() == 1 ) { + std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_edgeSelection.begin() ); + + if ( index != c_brush_maxFaces ) { + update_move_planepts_edge( index ); + } + } + } + } + void select_edge( std::size_t index, bool select ){ + if ( select ) { + VertexSelection_insert( m_edgeSelection, getFace().getWinding()[index].adjacent ); + } + else + { + VertexSelection_erase( m_edgeSelection, getFace().getWinding()[index].adjacent ); + } + + SceneChangeNotify(); + update_selection_edge(); + } + + bool selected_edge( std::size_t index ) const { + return VertexSelection_find( m_edgeSelection, getFace().getWinding()[index].adjacent ) != m_edgeSelection.end(); + } + + const Vector3& centroid() const { + return m_face->centroid(); + } + + void connectivityChanged(){ + // This occurs when a face is added or removed. + // The current vertex and edge selections no longer valid and must be cleared. + m_vertexSelection.clear(); + m_selectableVertices.setSelected( false ); + m_edgeSelection.clear(); m_selectableEdges.setSelected( false ); } - else - { - m_selectableEdges.setSelected( true ); - - if ( m_edgeSelection.size() == 1 ) { - std::size_t index = Winding_FindAdjacent( getFace().getWinding(), *m_edgeSelection.begin() ); - - if ( index != c_brush_maxFaces ) { - update_move_planepts_edge( index ); - } - } - } -} -void select_edge( std::size_t index, bool select ){ - if ( select ) { - VertexSelection_insert( m_edgeSelection, getFace().getWinding()[index].adjacent ); - } - else - { - VertexSelection_erase( m_edgeSelection, getFace().getWinding()[index].adjacent ); - } - - SceneChangeNotify(); - update_selection_edge(); -} - -bool selected_edge( std::size_t index ) const { - return VertexSelection_find( m_edgeSelection, getFace().getWinding()[index].adjacent ) != m_edgeSelection.end(); -} - -const Vector3& centroid() const { - return m_face->centroid(); -} - -void connectivityChanged(){ - // This occurs when a face is added or removed. - // The current vertex and edge selections no longer valid and must be cleared. - m_vertexSelection.clear(); - m_selectableVertices.setSelected( false ); - m_edgeSelection.clear(); - m_selectableEdges.setSelected( false ); -} }; class BrushClipPlane : public OpenGLRenderable { -Plane3 m_plane; -Winding m_winding; -static Shader* m_state; + Plane3 m_plane; + Winding m_winding; + static Shader* m_state; public: -static void constructStatic(){ - m_state = GlobalShaderCache().capture( "$CLIPPER_OVERLAY" ); -} -static void destroyStatic(){ - GlobalShaderCache().release( "$CLIPPER_OVERLAY" ); -} - -void setPlane( const Brush& brush, const Plane3& plane ){ - m_plane = plane; - if ( plane3_valid( m_plane ) ) { - brush.windingForClipPlane( m_winding, m_plane ); + static void constructStatic(){ + m_state = GlobalShaderCache().capture( "$CLIPPER_OVERLAY" ); } - else - { - m_winding.resize( 0 ); + static void destroyStatic(){ + GlobalShaderCache().release( "$CLIPPER_OVERLAY" ); } -} -void render( RenderStateFlags state ) const { - if ( ( state & RENDER_FILL ) != 0 ) { - Winding_Draw( m_winding, m_plane.normal(), state ); + void setPlane( const Brush& brush, const Plane3& plane ){ + m_plane = plane; + if ( plane3_valid( m_plane ) ) { + brush.windingForClipPlane( m_winding, m_plane ); + } + else + { + m_winding.resize( 0 ); + } } - else - { - Winding_DrawWireframe( m_winding ); - // also draw a line indicating the direction of the cut - Vector3 lineverts[2]; - Winding_Centroid( m_winding, m_plane, lineverts[0] ); - lineverts[1] = vector3_added( lineverts[0], vector3_scaled( m_plane.normal(), Brush::m_maxWorldCoord * 4 ) ); + void render( RenderStateFlags state ) const { + if ( ( state & RENDER_FILL ) != 0 ) { + Winding_Draw( m_winding, m_plane.normal(), state ); + } + else + { + Winding_DrawWireframe( m_winding ); - glVertexPointer( 3, GL_FLOAT, sizeof( Vector3 ), &lineverts[0] ); - glDrawArrays( GL_LINES, 0, GLsizei( 2 ) ); + // also draw a line indicating the direction of the cut + Vector3 lineverts[2]; + Winding_Centroid( m_winding, m_plane, lineverts[0] ); + lineverts[1] = vector3_added( lineverts[0], vector3_scaled( m_plane.normal(), Brush::m_maxWorldCoord * 4 ) ); + + glVertexPointer( 3, GL_FLOAT, sizeof( Vector3 ), &lineverts[0] ); + glDrawArrays( GL_LINES, 0, GLsizei( 2 ) ); + } } -} -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( m_state, Renderer::eWireframeOnly ); - renderer.SetState( m_state, Renderer::eFullMaterials ); - renderer.addRenderable( *this, localToWorld ); -} + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( m_state, Renderer::eWireframeOnly ); + renderer.SetState( m_state, Renderer::eFullMaterials ); + renderer.addRenderable( *this, localToWorld ); + } }; inline void Face_addLight( const FaceInstance& face, const Matrix4& localToWorld, const RendererLight& light ){ @@ -3160,7 +3162,7 @@ inline void Face_addLight( const FaceInstance& face, const Matrix4& localToWorld const Vector3& origin = light.aabb().origin; Plane3 tmp( plane3_transformed( Plane3( facePlane.normal(), -facePlane.dist() ), localToWorld ) ); if ( !plane3_test_point( tmp, origin ) - || !plane3_test_point( tmp, vector3_added( origin, light.offset() ) ) ) { + || !plane3_test_point( tmp, vector3_added( origin, light.offset() ) ) ) { face.m_lights.addLight( light ); } } @@ -3172,195 +3174,195 @@ typedef std::vector FaceInstances_ptrs; class EdgeInstance : public Selectable { -FaceInstances& m_faceInstances; -SelectableEdge* m_edge; + FaceInstances& m_faceInstances; + SelectableEdge* m_edge; -void select_edge( bool select ){ - FaceVertexId faceVertex = m_edge->m_faceVertex; - m_faceInstances[faceVertex.getFace()].select_edge( faceVertex.getVertex(), select ); - faceVertex = next_edge( m_edge->m_faces, faceVertex ); - m_faceInstances[faceVertex.getFace()].select_edge( faceVertex.getVertex(), select ); -} -bool selected_edge() const { - FaceVertexId faceVertex = m_edge->m_faceVertex; - if ( !m_faceInstances[faceVertex.getFace()].selected_edge( faceVertex.getVertex() ) ) { - return false; - } - faceVertex = next_edge( m_edge->m_faces, faceVertex ); - if ( !m_faceInstances[faceVertex.getFace()].selected_edge( faceVertex.getVertex() ) ) { - return false; + void select_edge( bool select ){ + FaceVertexId faceVertex = m_edge->m_faceVertex; + m_faceInstances[faceVertex.getFace()].select_edge( faceVertex.getVertex(), select ); + faceVertex = next_edge( m_edge->m_faces, faceVertex ); + m_faceInstances[faceVertex.getFace()].select_edge( faceVertex.getVertex(), select ); } + bool selected_edge() const { + FaceVertexId faceVertex = m_edge->m_faceVertex; + if ( !m_faceInstances[faceVertex.getFace()].selected_edge( faceVertex.getVertex() ) ) { + return false; + } + faceVertex = next_edge( m_edge->m_faces, faceVertex ); + if ( !m_faceInstances[faceVertex.getFace()].selected_edge( faceVertex.getVertex() ) ) { + return false; + } - return true; -} + return true; + } public: -EdgeInstance( FaceInstances& faceInstances, SelectableEdge& edge ) - : m_faceInstances( faceInstances ), m_edge( &edge ){ -} -EdgeInstance& operator=( const EdgeInstance& other ){ - m_edge = other.m_edge; - return *this; -} - -void setSelected( bool select ){ - select_edge( select ); -} -bool isSelected() const { - return selected_edge(); -} - - -void testSelect( Selector& selector, SelectionTest& test ){ - SelectionIntersection best; - m_edge->testSelect( test, best ); - if ( best.valid() ) { - Selector_add( selector, *this, best ); + EdgeInstance( FaceInstances& faceInstances, SelectableEdge& edge ) + : m_faceInstances( faceInstances ), m_edge( &edge ){ } -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test ) const { - SelectionIntersection best; - m_edge->testSelect( test, best ); - if ( SelectionIntersection_closer( best, intersection ) ) { - intersection = best; - polygons.clear(); - polygons.emplace_back( std::initializer_list( { m_edge->getEdge() } ) ); + EdgeInstance& operator=( const EdgeInstance& other ){ + m_edge = other.m_edge; + return *this; } -} -void bestPlaneIndirect( const SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist, float& dot ) const { - const Winding& winding = m_edge->getFace().getWinding(); - FaceVertexId faceVertex = m_edge->m_faceVertex; - Line line( winding[faceVertex.getVertex()].vertex, winding[Winding_next( winding, faceVertex.getVertex() )].vertex ); - if( matrix4_clip_line_by_nearplane( test.getVolume().GetViewMatrix(), line ) == 2 ){ - const Vector3 intersection_new = line_closest_point( line, g_vector3_identity ); - const float dist_new = vector3_length_squared( intersection_new ); - const float dot_new = fabs( vector3_dot( vector3_normalised( intersection_new ), vector3_normalised( line.end - line.start ) ) ); - if( dist - dist_new > 1e-6f // new dist noticeably smaller - || ( float_equal_epsilon( dist_new, dist, 1e-6f ) && dot_new < dot ) ){ // or ambiguous case. Resolve it by dot comparison - const Plane3& plane1 = m_faceInstances[faceVertex.getFace()].getFace().plane3(); - faceVertex = next_edge( m_edge->m_faces, faceVertex ); - const Plane3& plane2 = m_faceInstances[faceVertex.getFace()].getFace().plane3(); + void setSelected( bool select ){ + select_edge( select ); + } + bool isSelected() const { + return selected_edge(); + } - auto assign_plane = [&plane, &intersection, intersection_new, &dist, dist_new, &dot, dot_new]( const Plane3& plane_new ){ + + void testSelect( Selector& selector, SelectionTest& test ){ + SelectionIntersection best; + m_edge->testSelect( test, best ); + if ( best.valid() ) { + Selector_add( selector, *this, best ); + } + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test ) const { + SelectionIntersection best; + m_edge->testSelect( test, best ); + if ( SelectionIntersection_closer( best, intersection ) ) { + intersection = best; + polygons.clear(); + polygons.emplace_back( std::initializer_list( { m_edge->getEdge() } ) ); + } + } + + void bestPlaneIndirect( const SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist, float& dot ) const { + const Winding& winding = m_edge->getFace().getWinding(); + FaceVertexId faceVertex = m_edge->m_faceVertex; + Line line( winding[faceVertex.getVertex()].vertex, winding[Winding_next( winding, faceVertex.getVertex() )].vertex ); + if( matrix4_clip_line_by_nearplane( test.getVolume().GetViewMatrix(), line ) == 2 ){ + const Vector3 intersection_new = line_closest_point( line, g_vector3_identity ); + const float dist_new = vector3_length_squared( intersection_new ); + const float dot_new = fabs( vector3_dot( vector3_normalised( intersection_new ), vector3_normalised( line.end - line.start ) ) ); + if( dist - dist_new > 1e-6f // new dist noticeably smaller + || ( float_equal_epsilon( dist_new, dist, 1e-6f ) && dot_new < dot ) ){ // or ambiguous case. Resolve it by dot comparison + const Plane3& plane1 = m_faceInstances[faceVertex.getFace()].getFace().plane3(); + faceVertex = next_edge( m_edge->m_faces, faceVertex ); + const Plane3& plane2 = m_faceInstances[faceVertex.getFace()].getFace().plane3(); + + auto assign_plane = [&plane, &intersection, intersection_new, &dist, dist_new, &dot, dot_new]( const Plane3& plane_new ){ plane = plane_new; intersection = intersection_new; dist = dist_new; dot = dot_new; - }; + }; - if( test.getVolume().fill() ){ - if( plane3_distance_to_point( plane1, test.getVolume().getViewer() ) <= 0 ) - assign_plane( plane1 ); - else if( plane3_distance_to_point( plane2, test.getVolume().getViewer() ) <= 0 ) - assign_plane( plane2 ); - } - else if( fabs( vector3_length_squared( line.end - line.start ) ) > 1e-3 ){ - if( fabs( vector3_dot( plane1.normal(), test.getVolume().getViewDir() ) ) < fabs( vector3_dot( plane2.normal(), test.getVolume().getViewDir() ) ) ) - assign_plane( plane1 ); - else - assign_plane( plane2 ); + if( test.getVolume().fill() ){ + if( plane3_distance_to_point( plane1, test.getVolume().getViewer() ) <= 0 ) + assign_plane( plane1 ); + else if( plane3_distance_to_point( plane2, test.getVolume().getViewer() ) <= 0 ) + assign_plane( plane2 ); + } + else if( fabs( vector3_length_squared( line.end - line.start ) ) > 1e-3 ){ + if( fabs( vector3_dot( plane1.normal(), test.getVolume().getViewDir() ) ) < fabs( vector3_dot( plane2.normal(), test.getVolume().getViewDir() ) ) ) + assign_plane( plane1 ); + else + assign_plane( plane2 ); + } } } } -} }; class VertexInstance : public Selectable { -FaceInstances& m_faceInstances; -SelectableVertex* m_vertex; + FaceInstances& m_faceInstances; + SelectableVertex* m_vertex; -void select_vertex( bool select ){ - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - m_faceInstances[faceVertex.getFace()].select_vertex( faceVertex.getVertex(), select ); - faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); - } - while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); -} -bool selected_vertex() const { - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - if ( !m_faceInstances[faceVertex.getFace()].selected_vertex( faceVertex.getVertex() ) ) { - return false; + void select_vertex( bool select ){ + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + m_faceInstances[faceVertex.getFace()].select_vertex( faceVertex.getVertex(), select ); + faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); } - faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); + while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); } - while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); - return true; -} - -public: -VertexInstance( FaceInstances& faceInstances, SelectableVertex& vertex ) - : m_faceInstances( faceInstances ), m_vertex( &vertex ){ -} -VertexInstance& operator=( const VertexInstance& other ){ - m_vertex = other.m_vertex; - return *this; -} - -void setSelected( bool select ){ - select_vertex( select ); -} -bool isSelected() const { - return selected_vertex(); -} - -void testSelect( Selector& selector, SelectionTest& test ){ - SelectionIntersection best; - m_vertex->testSelect( test, best ); - if ( best.valid() ) { - Selector_add( selector, *this, best ); - } -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test ) const { - SelectionIntersection best; - m_vertex->testSelect( test, best ); - if ( SelectionIntersection_closer( best, intersection ) ) { - intersection = best; - polygons.clear(); - polygons.emplace_back( std::initializer_list( { m_vertex->getVertex() } ) ); - } -} - -void selectVerticesOfFace( const FaceInstance& faceinstance ){ - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - if( &faceinstance == &m_faceInstances[faceVertex.getFace()] ){ - setSelected( true ); - return; + bool selected_vertex() const { + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + if ( !m_faceInstances[faceVertex.getFace()].selected_vertex( faceVertex.getVertex() ) ) { + return false; + } + faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); } - faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); - } - while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); -} -void gather( Brush::VertexModeVertices& vertexModeVertices ) const { - vertexModeVertices.emplace_back( m_vertex->getVertex(), isSelected() ); - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - vertexModeVertices.back().m_faces.push_back( &m_faceInstances[faceVertex.getFace()].getFace() ); - faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); - } - while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); -} -bool vertex_select( const Vector3& vertex ){ - if( vector3_length_squared( vertex - m_vertex->getVertex() ) < ( 0.1 * 0.1 ) ){ - setSelected( true ); + while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); return true; } - return false; -} + +public: + VertexInstance( FaceInstances& faceInstances, SelectableVertex& vertex ) + : m_faceInstances( faceInstances ), m_vertex( &vertex ){ + } + VertexInstance& operator=( const VertexInstance& other ){ + m_vertex = other.m_vertex; + return *this; + } + + void setSelected( bool select ){ + select_vertex( select ); + } + bool isSelected() const { + return selected_vertex(); + } + + void testSelect( Selector& selector, SelectionTest& test ){ + SelectionIntersection best; + m_vertex->testSelect( test, best ); + if ( best.valid() ) { + Selector_add( selector, *this, best ); + } + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test ) const { + SelectionIntersection best; + m_vertex->testSelect( test, best ); + if ( SelectionIntersection_closer( best, intersection ) ) { + intersection = best; + polygons.clear(); + polygons.emplace_back( std::initializer_list( { m_vertex->getVertex() } ) ); + } + } + + void selectVerticesOfFace( const FaceInstance& faceinstance ){ + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + if( &faceinstance == &m_faceInstances[faceVertex.getFace()] ){ + setSelected( true ); + return; + } + faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); + } + while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); + } + void gather( Brush::VertexModeVertices& vertexModeVertices ) const { + vertexModeVertices.emplace_back( m_vertex->getVertex(), isSelected() ); + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + vertexModeVertices.back().m_faces.push_back( &m_faceInstances[faceVertex.getFace()].getFace() ); + faceVertex = next_vertex( m_vertex->m_faces, faceVertex ); + } + while ( faceVertex.getFace() != m_vertex->m_faceVertex.getFace() ); + } + bool vertex_select( const Vector3& vertex ){ + if( vector3_length_squared( vertex - m_vertex->getVertex() ) < ( 0.1 * 0.1 ) ){ + setSelected( true ); + return true; + } + return false; + } }; class BrushInstanceVisitor { public: -virtual void visit( FaceInstance& face ) const = 0; + virtual void visit( FaceInstance& face ) const = 0; }; class BrushInstance : @@ -3375,763 +3377,763 @@ class BrushInstance : public PlaneSelectable, public LightCullable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceStaticCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + + + Brush& m_brush; + + FaceInstances m_faceInstances; + + typedef std::vector EdgeInstances; + EdgeInstances m_edgeInstances; + typedef std::vector VertexInstances; + VertexInstances m_vertexInstances; + + ObservedSelectable m_selectable; + + mutable RenderableWireframe m_render_wireframe; + mutable RenderablePointVector m_render_selected; + mutable AABB m_aabb_component; + mutable Array m_faceCentroidPointsCulled; + RenderablePointArray m_render_faces_wireframe; + mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data + + BrushClipPlane m_clipPlane; + + static Shader* m_state_selpoint; + + const LightList* m_lightList; + + BrushTransformModifier m_transform; + + BrushInstance( const BrushInstance& other ); // NOT COPYABLE + BrushInstance& operator=( const BrushInstance& other ); // NOT ASSIGNABLE public: -TypeCasts(){ - InstanceStaticCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + static Counter* m_counter; + typedef LazyStatic StaticTypeCasts; -Brush& m_brush; - -FaceInstances m_faceInstances; - -typedef std::vector EdgeInstances; -EdgeInstances m_edgeInstances; -typedef std::vector VertexInstances; -VertexInstances m_vertexInstances; - -ObservedSelectable m_selectable; - -mutable RenderableWireframe m_render_wireframe; -mutable RenderablePointVector m_render_selected; -mutable AABB m_aabb_component; -mutable Array m_faceCentroidPointsCulled; -RenderablePointArray m_render_faces_wireframe; -mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data - -BrushClipPlane m_clipPlane; - -static Shader* m_state_selpoint; - -const LightList* m_lightList; - -BrushTransformModifier m_transform; - -BrushInstance( const BrushInstance& other ); // NOT COPYABLE -BrushInstance& operator=( const BrushInstance& other ); // NOT ASSIGNABLE -public: -static Counter* m_counter; - -typedef LazyStatic StaticTypeCasts; - -void lightsChanged(){ - m_lightList->lightsChanged(); -} -typedef MemberCaller LightsChangedCaller; - -STRING_CONSTANT( Name, "BrushInstance" ); - -BrushInstance( const scene::Path& path, scene::Instance* parent, Brush& brush ) : - Instance( path, parent, this, StaticTypeCasts::instance().get() ), - m_brush( brush ), - m_selectable( SelectedChangedCaller( *this ) ), - m_render_selected( GL_POINTS ), - m_render_faces_wireframe( m_faceCentroidPointsCulled, GL_POINTS ), - m_viewChanged( false ), - m_transform( Brush::TransformChangedCaller( m_brush ), ApplyTransformCaller( *this ) ){ - m_brush.instanceAttach( Instance::path() ); - m_brush.attach( *this ); - m_counter->increment(); - - m_lightList = &GlobalShaderCache().attach( *this ); - m_brush.m_lightsChanged = LightsChangedCaller( *this ); ///\todo Make this work with instancing. - - Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); -} -~BrushInstance(){ - Instance::setTransformChangedCallback( Callback() ); - - m_brush.m_lightsChanged = Callback(); - GlobalShaderCache().detach( *this ); - - m_counter->decrement(); - m_brush.detach( *this ); - m_brush.instanceDetach( Instance::path() ); -} - -Brush& getBrush(){ - return m_brush; -} -const Brush& getBrush() const { - return m_brush; -} - -Bounded& get( NullType){ - return m_brush; -} -Cullable& get( NullType){ - return m_brush; -} -Transformable& get( NullType){ - return m_transform; -} - -void selectedChanged( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); - GlobalSelectionSystem().onSelectedChanged( *this, selectable ); - - Instance::selectedChanged(); -} -typedef MemberCaller1 SelectedChangedCaller; - -void selectedChangedComponent( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); - GlobalSelectionSystem().onComponentSelection( *this, selectable ); -} -typedef MemberCaller1 SelectedChangedComponentCaller; - -const BrushInstanceVisitor& forEachFaceInstance( const BrushInstanceVisitor& visitor ){ - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - visitor.visit( *i ); + void lightsChanged(){ + m_lightList->lightsChanged(); } - return visitor; -} + typedef MemberCaller LightsChangedCaller; -static void constructStatic(){ - m_state_selpoint = GlobalShaderCache().capture( "$SELPOINT" ); -} -static void destroyStatic(){ - GlobalShaderCache().release( "$SELPOINT" ); -} + STRING_CONSTANT( Name, "BrushInstance" ); -void clear(){ - m_faceInstances.clear(); -} -void reserve( std::size_t size ){ - m_faceInstances.reserve( size ); -} + BrushInstance( const scene::Path& path, scene::Instance* parent, Brush& brush ) : + Instance( path, parent, this, StaticTypeCasts::instance().get() ), + m_brush( brush ), + m_selectable( SelectedChangedCaller( *this ) ), + m_render_selected( GL_POINTS ), + m_render_faces_wireframe( m_faceCentroidPointsCulled, GL_POINTS ), + m_viewChanged( false ), + m_transform( Brush::TransformChangedCaller( m_brush ), ApplyTransformCaller( *this ) ){ + m_brush.instanceAttach( Instance::path() ); + m_brush.attach( *this ); + m_counter->increment(); -void push_back( Face& face ){ - m_faceInstances.push_back( FaceInstance( face, SelectedChangedComponentCaller( *this ) ) ); -} -void pop_back(){ - ASSERT_MESSAGE( !m_faceInstances.empty(), "erasing invalid element" ); - m_faceInstances.pop_back(); -} -void erase( std::size_t index ){ - ASSERT_MESSAGE( index < m_faceInstances.size(), "erasing invalid element" ); - m_faceInstances.erase( m_faceInstances.begin() + index ); -} -void connectivityChanged(){ - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).connectivityChanged(); + m_lightList = &GlobalShaderCache().attach( *this ); + m_brush.m_lightsChanged = LightsChangedCaller( *this ); ///\todo Make this work with instancing. + + Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); } -} + ~BrushInstance(){ + Instance::setTransformChangedCallback( Callback() ); -void edge_clear(){ - m_edgeInstances.clear(); -} -void edge_push_back( SelectableEdge& edge ){ - m_edgeInstances.push_back( EdgeInstance( m_faceInstances, edge ) ); -} + m_brush.m_lightsChanged = Callback(); + GlobalShaderCache().detach( *this ); -void vertex_clear(){ - m_vertexInstances.clear(); -} -void vertex_push_back( SelectableVertex& vertex ){ - m_vertexInstances.push_back( VertexInstance( m_faceInstances, vertex ) ); -} - -void vertex_select(){ - bool src_selected = false; - bool dst_selected = false; - for( const auto& v : m_brush.m_vertexModeVertices ) - if( v.m_selected ){ - src_selected = true; - for( auto& i : m_vertexInstances ) - dst_selected |= i.vertex_select( v.m_vertexTransformed ); - } - if( src_selected && !dst_selected && !m_vertexInstances.empty() ) - m_vertexInstances[0].setSelected( true ); //select at least something to prevent transform interruption after removing all selected vertices during vertexModeTransform -} - -void vertex_snap( const float snap, bool all ){ - m_brush.vertexModeInit(); - m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() ); - for ( const auto& i : m_vertexInstances ){ - i.gather( m_brush.m_vertexModeVertices ); - } - m_brush.vertexModeSnap( snap, all ); - m_brush.evaluateBRep(); - m_brush.vertexModeFree(); - m_brush.freezeTransform(); -} - -void vertex_snap( const float snap ){ - vertex_snap( snap, true ); -} - -void DEBUG_verify() const { - ASSERT_MESSAGE( m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch" ); -} - -bool isSelected() const { - return m_selectable.isSelected(); -} -void setSelected( bool select ){ - m_selectable.setSelected( select ); - if ( !select && parent() ){ - Selectable* sel_parent = Instance_getSelectable( *parent() ); - if ( sel_parent && sel_parent->isSelected() ) - sel_parent->setSelected( false ); - } -} - -void update_selected() const { - m_render_selected.clear(); - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - if ( ( *i ).getFace().contributes() ) { - ( *i ).iterate_selected( m_render_selected ); - } - } -} - -void evaluateViewDependent( const VolumeTest& volume, const Matrix4& localToWorld ) const { - if ( m_viewChanged ) { - m_viewChanged = false; - - bool faces_visible[c_brush_maxFaces]; - { - bool* j = faces_visible; - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j ) - { - *j = ( *i ).intersectVolume( volume, localToWorld ); - } - } - - m_brush.update_wireframe( m_render_wireframe, faces_visible ); - m_brush.update_faces_wireframe( m_faceCentroidPointsCulled, faces_visible ); - } -} - -void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - m_brush.evaluateBRep(); - - update_selected(); - if ( !m_render_selected.empty() ) { - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.SetState( m_state_selpoint, Renderer::eWireframeOnly ); - renderer.SetState( m_state_selpoint, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_selected, localToWorld ); - } -} - -void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { - m_brush.evaluateBRep(); - - const Matrix4& localToWorld = Instance::localToWorld(); - - renderer.SetState( m_brush.m_state_point, Renderer::eWireframeOnly ); - renderer.SetState( m_brush.m_state_point, Renderer::eFullMaterials ); - - if ( volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace ) { - evaluateViewDependent( volume, localToWorld ); - renderer.addRenderable( m_render_faces_wireframe, localToWorld ); - } - else - { - m_brush.renderComponents( GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld ); - } -} - -void renderClipPlane( Renderer& renderer, const VolumeTest& volume ) const { - if ( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected() ) { - m_clipPlane.render( renderer, volume, localToWorld() ); - } -} - -void renderCommon( Renderer& renderer, const VolumeTest& volume ) const { - bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent; - - if ( componentMode && isSelected() ) { - renderComponents( renderer, volume ); + m_counter->decrement(); + m_brush.detach( *this ); + m_brush.instanceDetach( Instance::path() ); } - if ( parentSelected() ) { - if ( !componentMode ) { - renderer.Highlight( Renderer::eFace ); - } - renderer.Highlight( Renderer::ePrimitive ); + Brush& getBrush(){ + return m_brush; } -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - //renderCommon(renderer, volume); - - m_lightList->evaluateLights(); - - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - renderer.setLights( ( *i ).m_lights ); - ( *i ).render( renderer, volume, localToWorld ); + const Brush& getBrush() const { + return m_brush; } - renderComponentsSelected( renderer, volume, localToWorld ); -} - -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - //renderCommon(renderer, volume); - - evaluateViewDependent( volume, localToWorld ); - - if ( m_render_wireframe.m_size != 0 ) { - renderer.addRenderable( m_render_wireframe, localToWorld ); + Bounded& get( NullType){ + return m_brush; + } + Cullable& get( NullType){ + return m_brush; + } + Transformable& get( NullType){ + return m_transform; } - renderComponentsSelected( renderer, volume, localToWorld ); -} + void selectedChanged( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); + GlobalSelectionSystem().onSelectedChanged( *this, selectable ); -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_brush.evaluateBRep(); + Instance::selectedChanged(); + } + typedef MemberCaller1 SelectedChangedCaller; - renderClipPlane( renderer, volume ); + void selectedChangedComponent( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); + GlobalSelectionSystem().onComponentSelection( *this, selectable ); + } + typedef MemberCaller1 SelectedChangedComponentCaller; - renderSolid( renderer, volume, localToWorld() ); -} - -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_brush.evaluateBRep(); - - renderClipPlane( renderer, volume ); - - renderWireframe( renderer, volume, localToWorld() ); -} - -void viewChanged() const { - m_viewChanged = true; -} - -void testSelect( Selector& selector, SelectionTest& test ){ - test.BeginMesh( localToWorld() ); - - SelectionIntersection best; - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).testSelect( test, best ); - } - if ( best.valid() ) { - selector.addIntersection( best ); - } -} - -bool isSelectedComponents() const { - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - if ( ( *i ).selectedComponents() ) { - return true; - } - } - return false; -} -void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).setSelected( mode, select ); - } -} -void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ - test.BeginMesh( localToWorld() ); - - switch ( mode ) - { - case SelectionSystem::eVertex: - { - for ( VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i ) - { - ( *i ).testSelect( selector, test ); - } - } - break; - case SelectionSystem::eEdge: - { - for ( EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i ) - { - ( *i ).testSelect( selector, test ); - } - } - break; - case SelectionSystem::eFace: - { - if ( test.getVolume().fill() ) { - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).testSelect( selector, test ); - } - } - else - { - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).testSelect_centroid( selector, test ); - } - } - } - break; - default: - break; - } -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { - test.BeginMesh( localToWorld() ); - - switch ( mode ) - { - case SelectionSystem::eVertex: - { - for ( const VertexInstance& i : m_vertexInstances ) - { - i.gatherComponentsHighlight( polygons, intersection, test ); - } - } - break; - case SelectionSystem::eEdge: - { - for ( const EdgeInstance& i : m_edgeInstances ) - { - i.gatherComponentsHighlight( polygons, intersection, test ); - } - } - break; - case SelectionSystem::eFace: - { - if ( test.getVolume().fill() ) { - const Plane3* plane = nullptr; - bool newint = false; - for ( const FaceInstance& i : m_faceInstances ) - { - SelectionIntersection best; - i.testSelect( test, best ); - if( best.valid() && intersection.equalEpsilon( best, 0.25f, 2e-6f ) ){ - plane = &i.getFace().plane3(); - } - else if ( SelectionIntersection_closer( best, intersection ) ) { - intersection = best; - newint = true; - plane = &i.getFace().plane3(); - } - } - if( plane ){ - if( newint || ( !polygons.empty() && polygons.back().size() >= 3 && !plane3_equal( *plane, plane3_for_points( polygons.back().data() ) ) ) ){ - polygons.clear(); - } - gatherPolygonsByPlane( *plane, polygons, false ); - } - } - else - { - for ( const FaceInstance& i : m_faceInstances ) - { - SelectionIntersection best; - i.getFace().testSelect_centroid( test, best ); - if ( SelectionIntersection_closer( best, intersection ) ) { - intersection = best; - polygons.clear(); - polygons.emplace_back( std::initializer_list( { i.getFace().centroid() } ) ); - } - } - } - } - break; - default: - break; - } -} - -void invertComponentSelection( SelectionSystem::EComponentMode mode ){ - switch ( mode ) - { - case SelectionSystem::eVertex: - { - for ( VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i ) - { - ( *i ).setSelected( !( *i ).isSelected() ); - } - } - break; - case SelectionSystem::eEdge: - { - for ( EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i ) - { - ( *i ).setSelected( !( *i ).isSelected() ); - } - } - break; - case SelectionSystem::eFace: - { + const BrushInstanceVisitor& forEachFaceInstance( const BrushInstanceVisitor& visitor ){ for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) { - if( !( *i ).getFace().isFiltered() ) - ( *i ).setSelected( mode, !( *i ).isSelected() ); + visitor.visit( *i ); + } + return visitor; + } + + static void constructStatic(){ + m_state_selpoint = GlobalShaderCache().capture( "$SELPOINT" ); + } + static void destroyStatic(){ + GlobalShaderCache().release( "$SELPOINT" ); + } + + void clear(){ + m_faceInstances.clear(); + } + void reserve( std::size_t size ){ + m_faceInstances.reserve( size ); + } + + void push_back( Face& face ){ + m_faceInstances.push_back( FaceInstance( face, SelectedChangedComponentCaller( *this ) ) ); + } + void pop_back(){ + ASSERT_MESSAGE( !m_faceInstances.empty(), "erasing invalid element" ); + m_faceInstances.pop_back(); + } + void erase( std::size_t index ){ + ASSERT_MESSAGE( index < m_faceInstances.size(), "erasing invalid element" ); + m_faceInstances.erase( m_faceInstances.begin() + index ); + } + void connectivityChanged(){ + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).connectivityChanged(); } } - break; - default: - break; - } -} -void selectPlanes( SelectionTest& test, FaceInstances_ptrs& bestInstances ){ - test.BeginMesh( localToWorld() ); + void edge_clear(){ + m_edgeInstances.clear(); + } + void edge_push_back( SelectableEdge& edge ){ + m_edgeInstances.push_back( EdgeInstance( m_faceInstances, edge ) ); + } - const Vector3 viewdir( test.getVolume().getViewDir() ); - double bestDot = 1; + void vertex_clear(){ + m_vertexInstances.clear(); + } + void vertex_push_back( SelectableVertex& vertex ){ + m_vertexInstances.push_back( VertexInstance( m_faceInstances, vertex ) ); + } - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - if( !( *i ).trySelectPlane( test ) ){ - continue; - } - const double dot = fabs( vector3_dot( ( *i ).getFace().plane3().normal(), viewdir ) ); - const double diff = bestDot - dot; - if( diff > 0.03 ){ - bestDot = dot; - bestInstances.clear(); - bestInstances.push_back( &( *i ) ); - } - else if( fabs( diff ) <= 0.03 ){ - bestInstances.push_back( &( *i ) ); - } - } -} -void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ - FaceInstances_ptrs bestInstances; - selectPlanes( test, bestInstances ); - - for ( FaceInstances_ptrs::iterator i = bestInstances.begin(); i != bestInstances.end(); ++i ){ - ( *i )->addSelectable( selector ); - selectedPlaneCallback( ( *i )->getFace().plane3() ); - if( test.getVolume().fill() ) - return; // select only plane in camera - } -} -void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ - for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).selectReversedPlane( selector, selectedPlanes ); - } -} - -void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { - test.BeginMesh( localToWorld() ); - for ( const FaceInstance& fi : m_faceInstances ) - { - SelectionIntersection intersection_new; - fi.testSelect( test, intersection_new ); - if( SelectionIntersection_closer( intersection_new, intersection ) ){ - intersection = intersection_new; - plane = fi.getFace().plane3(); - } - } -} -void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { - test.BeginMesh( localToWorld() ); - float dot = 1; - for ( const EdgeInstance& ei : m_edgeInstances ) - { - ei.bestPlaneIndirect( test, plane, intersection, dist, dot ); - } -} -void selectByPlane( const Plane3& plane ){ - for ( FaceInstance& fi : m_faceInstances ) - if( plane3_equal( plane, fi.getFace().plane3() ) || plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) - fi.setSelected( SelectionSystem::eFace, true ); -} -void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { - gatherPolygonsByPlane( plane, polygons, true ); -} -void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons, const bool reversed_plane_also ) const { - for ( const FaceInstance& fi : m_faceInstances ) - if( plane3_equal( plane, fi.getFace().plane3() ) || ( reversed_plane_also && plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) ) - if( fi.getFace().contributes() ){ - const Winding& winding = fi.getFace().getWinding(); - polygons.emplace_back( winding.numpoints ); - for( std::size_t i = 0; i < winding.numpoints; ++i ){ - polygons.back()[i] = winding[i].vertex; - } + void vertex_select(){ + bool src_selected = false; + bool dst_selected = false; + for( const auto& v : m_brush.m_vertexModeVertices ) + if( v.m_selected ){ + src_selected = true; + for( auto& i : m_vertexInstances ) + dst_selected |= i.vertex_select( v.m_vertexTransformed ); } -} - -void selectVerticesOnPlane( const Plane3& plane ){ - for ( FaceInstance& fi : m_faceInstances ) - if( plane3_equal( plane, fi.getFace().plane3() ) || plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) - for ( VertexInstance& vi : m_vertexInstances ) - vi.selectVerticesOfFace( fi ); -} - -void transformComponents( const Matrix4& matrix ); - -const AABB& getSelectedComponentsBounds() const { - m_aabb_component = AABB(); - - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).iterate_selected( m_aabb_component ); + if( src_selected && !dst_selected && !m_vertexInstances.empty() ) + m_vertexInstances[0].setSelected( true ); //select at least something to prevent transform interruption after removing all selected vertices during vertexModeTransform } - return m_aabb_component; -} -void gatherSelectedComponents( const Vector3Callback& callback ) const { - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).gatherSelectedComponents( callback ); - } -} - -void insert_vertices( const Brush::VertexModeVertices& vertexModeVertices ){ - if( !m_vertexInstances.empty() ){ + void vertex_snap( const float snap, bool all ){ m_brush.vertexModeInit(); - m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() + 2 ); + m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() ); for ( const auto& i : m_vertexInstances ){ i.gather( m_brush.m_vertexModeVertices ); } - for ( const auto& i : vertexModeVertices ){ - m_brush.m_vertexModeVertices.push_back( i ); - if( i.m_faces.empty() ) - m_brush.m_vertexModeVertices.back().m_faces.push_back( m_brush.m_vertexModeVertices[0].m_faces[0] ); - } - m_transform.m_transformFrozen = false; - m_transform.setType( TRANSFORM_COMPONENT ); - m_brush.transformChanged(); - m_brush.evaluateBRep(); - } -} - -void remove_vertices(){ - if( !m_vertexInstances.empty() ){ - m_brush.vertexModeInit(); - Brush::VertexModeVertices v; - v.reserve( m_vertexInstances.size() ); - for ( const auto& i : m_vertexInstances ){ - i.gather( v ); - if( v.back().m_selected ) - v.pop_back(); - } - std::vector ok( v.size(), true ); - gatherSelectedComponents( [&]( const Vector3 & value ) { - for( std::size_t i = 0; i < v.size(); ++i ) - if( vector3_length_squared( v[i].m_vertex - value ) < 0.05 * 0.05 ) - ok[i] = false; - } ); - - m_brush.m_vertexModeVertices.reserve( v.size() ); - for( std::size_t i = 0; i < v.size(); ++i ){ - if( ok[i] ) - m_brush.m_vertexModeVertices.push_back( v[i] ); - } - m_brush.vertexModeBuildHull(); + m_brush.vertexModeSnap( snap, all ); m_brush.evaluateBRep(); m_brush.vertexModeFree(); m_brush.freezeTransform(); } -} -void snapComponents( float snap ){ - for ( const auto& fi : m_faceInstances ){ - if( fi.selectedComponents( SelectionSystem::eVertex ) ){ - vertex_snap( snap, false ); - return; + void vertex_snap( const float snap ){ + vertex_snap( snap, true ); + } + + void DEBUG_verify() const { + ASSERT_MESSAGE( m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch" ); + } + + bool isSelected() const { + return m_selectable.isSelected(); + } + void setSelected( bool select ){ + m_selectable.setSelected( select ); + if ( !select && parent() ){ + Selectable* sel_parent = Instance_getSelectable( *parent() ); + if ( sel_parent && sel_parent->isSelected() ) + sel_parent->setSelected( false ); } } - for ( auto& fi : m_faceInstances ) - fi.snapComponents( snap ); -} -void evaluateTransform(){ - if( m_transform.m_transformFrozen && m_transform.isIdentity() ) - return; - if( m_transform.m_transformFrozen && !m_transform.isIdentity() ){ /* new transform */ - m_transform.m_transformFrozen = false; - for( auto& i : m_faceInstances ) - i.getFace().cacheCentroid(); - - if( m_transform.getType() == TRANSFORM_COMPONENT ){ - for ( const auto& i : m_faceInstances ){ - if( i.selectedComponents( SelectionSystem::eVertex ) ){ - m_brush.vertexModeInit(); - m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() ); - for ( const auto& i : m_vertexInstances ){ - i.gather( m_brush.m_vertexModeVertices ); - } - break; - } + void update_selected() const { + m_render_selected.clear(); + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + if ( ( *i ).getFace().contributes() ) { + ( *i ).iterate_selected( m_render_selected ); } } } - const Matrix4 matrix( m_transform.calculateTransform() ); + void evaluateViewDependent( const VolumeTest& volume, const Matrix4& localToWorld ) const { + if ( m_viewChanged ) { + m_viewChanged = false; - if ( m_transform.getType() == TRANSFORM_PRIMITIVE ) { - m_brush.transform( matrix ); - } - else - { - if( m_brush.m_vertexModeOn ){ - m_brush.vertexModeTransform( matrix ); - } - else{ - const bool tmp = g_brush_texturelock_enabled; - /* do not want texture projection transformation while resizing brush */ - if( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) - g_brush_texturelock_enabled = false; - transformComponents( matrix ); - g_brush_texturelock_enabled = tmp; + bool faces_visible[c_brush_maxFaces]; + { + bool* j = faces_visible; + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j ) + { + *j = ( *i ).intersectVolume( volume, localToWorld ); + } + } + + m_brush.update_wireframe( m_render_wireframe, faces_visible ); + m_brush.update_faces_wireframe( m_faceCentroidPointsCulled, faces_visible ); } } -} -void applyTransform(){ - if( !m_transform.isIdentity() ){ - if( m_transform.m_transformFrozen ){ //not yet unfrozen by evaluateTransform(), so evaluate -// m_brush.revertTransform(); -// evaluateTransform(); + + void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + m_brush.evaluateBRep(); + + update_selected(); + if ( !m_render_selected.empty() ) { + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.SetState( m_state_selpoint, Renderer::eWireframeOnly ); + renderer.SetState( m_state_selpoint, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_selected, localToWorld ); + } + } + + void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { + m_brush.evaluateBRep(); + + const Matrix4& localToWorld = Instance::localToWorld(); + + renderer.SetState( m_brush.m_state_point, Renderer::eWireframeOnly ); + renderer.SetState( m_brush.m_state_point, Renderer::eFullMaterials ); + + if ( volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace ) { + evaluateViewDependent( volume, localToWorld ); + renderer.addRenderable( m_render_faces_wireframe, localToWorld ); + } + else + { + m_brush.renderComponents( GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld ); + } + } + + void renderClipPlane( Renderer& renderer, const VolumeTest& volume ) const { + if ( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected() ) { + m_clipPlane.render( renderer, volume, localToWorld() ); + } + } + + void renderCommon( Renderer& renderer, const VolumeTest& volume ) const { + bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent; + + if ( componentMode && isSelected() ) { + renderComponents( renderer, volume ); + } + + if ( parentSelected() ) { + if ( !componentMode ) { + renderer.Highlight( Renderer::eFace ); + } + renderer.Highlight( Renderer::ePrimitive ); + } + } + + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + //renderCommon(renderer, volume); + + m_lightList->evaluateLights(); + + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + renderer.setLights( ( *i ).m_lights ); + ( *i ).render( renderer, volume, localToWorld ); + } + + renderComponentsSelected( renderer, volume, localToWorld ); + } + + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + //renderCommon(renderer, volume); + + evaluateViewDependent( volume, localToWorld ); + + if ( m_render_wireframe.m_size != 0 ) { + renderer.addRenderable( m_render_wireframe, localToWorld ); + } + + renderComponentsSelected( renderer, volume, localToWorld ); + } + + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_brush.evaluateBRep(); + + renderClipPlane( renderer, volume ); + + renderSolid( renderer, volume, localToWorld() ); + } + + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_brush.evaluateBRep(); + + renderClipPlane( renderer, volume ); + + renderWireframe( renderer, volume, localToWorld() ); + } + + void viewChanged() const { + m_viewChanged = true; + } + + void testSelect( Selector& selector, SelectionTest& test ){ + test.BeginMesh( localToWorld() ); + + SelectionIntersection best; + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).testSelect( test, best ); + } + if ( best.valid() ) { + selector.addIntersection( best ); + } + } + + bool isSelectedComponents() const { + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + if ( ( *i ).selectedComponents() ) { + return true; + } + } + return false; + } + void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).setSelected( mode, select ); + } + } + void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ + test.BeginMesh( localToWorld() ); + + switch ( mode ) + { + case SelectionSystem::eVertex: + { + for ( VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i ) + { + ( *i ).testSelect( selector, test ); + } + } + break; + case SelectionSystem::eEdge: + { + for ( EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i ) + { + ( *i ).testSelect( selector, test ); + } + } + break; + case SelectionSystem::eFace: + { + if ( test.getVolume().fill() ) { + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).testSelect( selector, test ); + } + } + else + { + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).testSelect_centroid( selector, test ); + } + } + } + break; + default: + break; + } + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { + test.BeginMesh( localToWorld() ); + + switch ( mode ) + { + case SelectionSystem::eVertex: + { + for ( const VertexInstance& i : m_vertexInstances ) + { + i.gatherComponentsHighlight( polygons, intersection, test ); + } + } + break; + case SelectionSystem::eEdge: + { + for ( const EdgeInstance& i : m_edgeInstances ) + { + i.gatherComponentsHighlight( polygons, intersection, test ); + } + } + break; + case SelectionSystem::eFace: + { + if ( test.getVolume().fill() ) { + const Plane3* plane = nullptr; + bool newint = false; + for ( const FaceInstance& i : m_faceInstances ) + { + SelectionIntersection best; + i.testSelect( test, best ); + if( best.valid() && intersection.equalEpsilon( best, 0.25f, 2e-6f ) ){ + plane = &i.getFace().plane3(); + } + else if ( SelectionIntersection_closer( best, intersection ) ) { + intersection = best; + newint = true; + plane = &i.getFace().plane3(); + } + } + if( plane ){ + if( newint || ( !polygons.empty() && polygons.back().size() >= 3 && !plane3_equal( *plane, plane3_for_points( polygons.back().data() ) ) ) ){ + polygons.clear(); + } + gatherPolygonsByPlane( *plane, polygons, false ); + } + } + else + { + for ( const FaceInstance& i : m_faceInstances ) + { + SelectionIntersection best; + i.getFace().testSelect_centroid( test, best ); + if ( SelectionIntersection_closer( best, intersection ) ) { + intersection = best; + polygons.clear(); + polygons.emplace_back( std::initializer_list( { i.getFace().centroid() } ) ); + } + } + } + } + break; + default: + break; + } + } + + void invertComponentSelection( SelectionSystem::EComponentMode mode ){ + switch ( mode ) + { + case SelectionSystem::eVertex: + { + for ( VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i ) + { + ( *i ).setSelected( !( *i ).isSelected() ); + } + } + break; + case SelectionSystem::eEdge: + { + for ( EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i ) + { + ( *i ).setSelected( !( *i ).isSelected() ); + } + } + break; + case SelectionSystem::eFace: + { + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + if( !( *i ).getFace().isFiltered() ) + ( *i ).setSelected( mode, !( *i ).isSelected() ); + } + } + break; + default: + break; + } + } + + void selectPlanes( SelectionTest& test, FaceInstances_ptrs& bestInstances ){ + test.BeginMesh( localToWorld() ); + + const Vector3 viewdir( test.getVolume().getViewDir() ); + double bestDot = 1; + + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + if( !( *i ).trySelectPlane( test ) ){ + continue; + } + const double dot = fabs( vector3_dot( ( *i ).getFace().plane3().normal(), viewdir ) ); + const double diff = bestDot - dot; + if( diff > 0.03 ){ + bestDot = dot; + bestInstances.clear(); + bestInstances.push_back( &( *i ) ); + } + else if( fabs( diff ) <= 0.03 ){ + bestInstances.push_back( &( *i ) ); + } + } + } + void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ + FaceInstances_ptrs bestInstances; + selectPlanes( test, bestInstances ); + + for ( FaceInstances_ptrs::iterator i = bestInstances.begin(); i != bestInstances.end(); ++i ){ + ( *i )->addSelectable( selector ); + selectedPlaneCallback( ( *i )->getFace().plane3() ); + if( test.getVolume().fill() ) + return; // select only plane in camera + } + } + void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ + for ( FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).selectReversedPlane( selector, selectedPlanes ); + } + } + + void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { + test.BeginMesh( localToWorld() ); + for ( const FaceInstance& fi : m_faceInstances ) + { + SelectionIntersection intersection_new; + fi.testSelect( test, intersection_new ); + if( SelectionIntersection_closer( intersection_new, intersection ) ){ + intersection = intersection_new; + plane = fi.getFace().plane3(); + } + } + } + void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { + test.BeginMesh( localToWorld() ); + float dot = 1; + for ( const EdgeInstance& ei : m_edgeInstances ) + { + ei.bestPlaneIndirect( test, plane, intersection, dist, dot ); + } + } + void selectByPlane( const Plane3& plane ){ + for ( FaceInstance& fi : m_faceInstances ) + if( plane3_equal( plane, fi.getFace().plane3() ) || plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) + fi.setSelected( SelectionSystem::eFace, true ); + } + void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { + gatherPolygonsByPlane( plane, polygons, true ); + } + void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons, const bool reversed_plane_also ) const { + for ( const FaceInstance& fi : m_faceInstances ) + if( plane3_equal( plane, fi.getFace().plane3() ) || ( reversed_plane_also && plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) ) + if( fi.getFace().contributes() ){ + const Winding& winding = fi.getFace().getWinding(); + polygons.emplace_back( winding.numpoints ); + for( std::size_t i = 0; i < winding.numpoints; ++i ){ + polygons.back()[i] = winding[i].vertex; + } + } + } + + void selectVerticesOnPlane( const Plane3& plane ){ + for ( FaceInstance& fi : m_faceInstances ) + if( plane3_equal( plane, fi.getFace().plane3() ) || plane3_equal( plane, plane3_flipped( fi.getFace().plane3() ) ) ) + for ( VertexInstance& vi : m_vertexInstances ) + vi.selectVerticesOfFace( fi ); + } + + void transformComponents( const Matrix4& matrix ); + + const AABB& getSelectedComponentsBounds() const { + m_aabb_component = AABB(); + + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).iterate_selected( m_aabb_component ); + } + + return m_aabb_component; + } + void gatherSelectedComponents( const Vector3Callback& callback ) const { + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).gatherSelectedComponents( callback ); + } + } + + void insert_vertices( const Brush::VertexModeVertices& vertexModeVertices ){ + if( !m_vertexInstances.empty() ){ + m_brush.vertexModeInit(); + m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() + 2 ); + for ( const auto& i : m_vertexInstances ){ + i.gather( m_brush.m_vertexModeVertices ); + } + for ( const auto& i : vertexModeVertices ){ + m_brush.m_vertexModeVertices.push_back( i ); + if( i.m_faces.empty() ) + m_brush.m_vertexModeVertices.back().m_faces.push_back( m_brush.m_vertexModeVertices[0].m_faces[0] ); + } + m_transform.m_transformFrozen = false; + m_transform.setType( TRANSFORM_COMPONENT ); + m_brush.transformChanged(); m_brush.evaluateBRep(); } - m_brush.freezeTransform(); - m_transform.setIdentity(); } - m_brush.vertexModeFree(); -} -typedef MemberCaller ApplyTransformCaller; -void setClipPlane( const Plane3& plane ){ - m_clipPlane.setPlane( m_brush, plane ); -} + void remove_vertices(){ + if( !m_vertexInstances.empty() ){ + m_brush.vertexModeInit(); + Brush::VertexModeVertices v; + v.reserve( m_vertexInstances.size() ); + for ( const auto& i : m_vertexInstances ){ + i.gather( v ); + if( v.back().m_selected ) + v.pop_back(); + } + std::vector ok( v.size(), true ); + gatherSelectedComponents( [&]( const Vector3 & value ) { + for( std::size_t i = 0; i < v.size(); ++i ) + if( vector3_length_squared( v[i].m_vertex - value ) < 0.05 * 0.05 ) + ok[i] = false; + } ); -bool testLight( const RendererLight& light ) const { - return light.testAABB( worldAABB() ); -} -void insertLight( const RendererLight& light ){ - const Matrix4& localToWorld = Instance::localToWorld(); - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - Face_addLight( *i, localToWorld, light ); + m_brush.m_vertexModeVertices.reserve( v.size() ); + for( std::size_t i = 0; i < v.size(); ++i ){ + if( ok[i] ) + m_brush.m_vertexModeVertices.push_back( v[i] ); + } + m_brush.vertexModeBuildHull(); + m_brush.evaluateBRep(); + m_brush.vertexModeFree(); + m_brush.freezeTransform(); + } } -} -void clearLights(){ - for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) - { - ( *i ).m_lights.clear(); + + void snapComponents( float snap ){ + for ( const auto& fi : m_faceInstances ){ + if( fi.selectedComponents( SelectionSystem::eVertex ) ){ + vertex_snap( snap, false ); + return; + } + } + + for ( auto& fi : m_faceInstances ) + fi.snapComponents( snap ); + } + void evaluateTransform(){ + if( m_transform.m_transformFrozen && m_transform.isIdentity() ) + return; + if( m_transform.m_transformFrozen && !m_transform.isIdentity() ){ /* new transform */ + m_transform.m_transformFrozen = false; + for( auto& i : m_faceInstances ) + i.getFace().cacheCentroid(); + + if( m_transform.getType() == TRANSFORM_COMPONENT ){ + for ( const auto& i : m_faceInstances ){ + if( i.selectedComponents( SelectionSystem::eVertex ) ){ + m_brush.vertexModeInit(); + m_brush.m_vertexModeVertices.reserve( m_vertexInstances.size() ); + for ( const auto& i : m_vertexInstances ){ + i.gather( m_brush.m_vertexModeVertices ); + } + break; + } + } + } + } + + const Matrix4 matrix( m_transform.calculateTransform() ); + + if ( m_transform.getType() == TRANSFORM_PRIMITIVE ) { + m_brush.transform( matrix ); + } + else + { + if( m_brush.m_vertexModeOn ){ + m_brush.vertexModeTransform( matrix ); + } + else{ + const bool tmp = g_brush_texturelock_enabled; + /* do not want texture projection transformation while resizing brush */ + if( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) + g_brush_texturelock_enabled = false; + transformComponents( matrix ); + g_brush_texturelock_enabled = tmp; + } + } + } + void applyTransform(){ + if( !m_transform.isIdentity() ){ + if( m_transform.m_transformFrozen ){ //not yet unfrozen by evaluateTransform(), so evaluate +// m_brush.revertTransform(); +// evaluateTransform(); + m_brush.evaluateBRep(); + } + m_brush.freezeTransform(); + m_transform.setIdentity(); + } + m_brush.vertexModeFree(); + } + typedef MemberCaller ApplyTransformCaller; + + void setClipPlane( const Plane3& plane ){ + m_clipPlane.setPlane( m_brush, plane ); + } + + bool testLight( const RendererLight& light ) const { + return light.testAABB( worldAABB() ); + } + void insertLight( const RendererLight& light ){ + const Matrix4& localToWorld = Instance::localToWorld(); + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + Face_addLight( *i, localToWorld, light ); + } + } + void clearLights(){ + for ( FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i ) + { + ( *i ).m_lights.clear(); + } } -} }; inline BrushInstance* Instance_getBrush( scene::Instance& instance ){ @@ -4142,16 +4144,16 @@ inline BrushInstance* Instance_getBrush( scene::Instance& instance ){ template class BrushSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -BrushSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - BrushInstance* brush = Instance_getBrush( instance ); - if ( brush != 0 ) { - m_functor( *brush ); + BrushSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + BrushInstance* brush = Instance_getBrush( instance ); + if ( brush != 0 ) { + m_functor( *brush ); + } } -} }; template @@ -4163,17 +4165,17 @@ inline const Functor& Scene_forEachSelectedBrush( const Functor& functor ){ template class BrushVisibleSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -BrushVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - BrushInstance* brush = Instance_getBrush( instance ); - if ( brush != 0 - && instance.path().top().get().visible() ) { - m_functor( *brush ); + BrushVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + BrushInstance* brush = Instance_getBrush( instance ); + if ( brush != 0 + && instance.path().top().get().visible() ) { + m_functor( *brush ); + } } -} }; template @@ -4184,26 +4186,26 @@ inline const Functor& Scene_forEachVisibleSelectedBrush( const Functor& functor class BrushForEachFace { -const BrushInstanceVisitor& m_visitor; + const BrushInstanceVisitor& m_visitor; public: -BrushForEachFace( const BrushInstanceVisitor& visitor ) : m_visitor( visitor ){ -} -void operator()( BrushInstance& brush ) const { - brush.forEachFaceInstance( m_visitor ); -} + BrushForEachFace( const BrushInstanceVisitor& visitor ) : m_visitor( visitor ){ + } + void operator()( BrushInstance& brush ) const { + brush.forEachFaceInstance( m_visitor ); + } }; template class FaceInstanceVisitFace : public BrushInstanceVisitor { -const Functor& functor; + const Functor& functor; public: -FaceInstanceVisitFace( const Functor& functor ) - : functor( functor ){ -} -void visit( FaceInstance& face ) const { - functor( face.getFace() ); -} + FaceInstanceVisitFace( const Functor& functor ) + : functor( functor ){ + } + void visit( FaceInstance& face ) const { + functor( face.getFace() ); + } }; template @@ -4215,14 +4217,14 @@ inline const Functor& Brush_forEachFace( BrushInstance& brush, const Functor& fu template class FaceVisitAll : public BrushVisitor { -const Functor& functor; + const Functor& functor; public: -FaceVisitAll( const Functor& functor ) - : functor( functor ){ -} -void visit( Face& face ) const { - functor( face ); -} + FaceVisitAll( const Functor& functor ) + : functor( functor ){ + } + void visit( Face& face ) const { + functor( face ); + } }; template @@ -4240,14 +4242,14 @@ inline const Functor& Brush_forEachFace( Brush& brush, const Functor& functor ){ template class FaceInstanceVisitAll : public BrushInstanceVisitor { -const Functor& functor; + const Functor& functor; public: -FaceInstanceVisitAll( const Functor& functor ) - : functor( functor ){ -} -void visit( FaceInstance& face ) const { - functor( face ); -} + FaceInstanceVisitAll( const Functor& functor ) + : functor( functor ){ + } + void visit( FaceInstance& face ) const { + functor( face ); + } }; template @@ -4266,32 +4268,32 @@ template class InstanceIfVisible : public Functor { public: -InstanceIfVisible( const Functor& functor ) : Functor( functor ){ -} -void operator()( scene::Instance& instance ){ - if ( instance.path().top().get().visible() ) { - Functor::operator()( instance ); + InstanceIfVisible( const Functor& functor ) : Functor( functor ){ + } + void operator()( scene::Instance& instance ){ + if ( instance.path().top().get().visible() ) { + Functor::operator()( instance ); + } } -} }; template class BrushVisibleWalker : public scene::Graph::Walker { -const Functor& m_functor; + const Functor& m_functor; public: -BrushVisibleWalker( const Functor& functor ) : m_functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - BrushInstance* brush = Instance_getBrush( instance ); - if ( brush != 0 ) { - m_functor( *brush ); - } - return true; + BrushVisibleWalker( const Functor& functor ) : m_functor( functor ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + BrushInstance* brush = Instance_getBrush( instance ); + if ( brush != 0 ) { + m_functor( *brush ); + } + return true; + } + return false; } - return false; -} }; template @@ -4328,14 +4330,14 @@ inline const Functor& Scene_ForEachSelectedBrush_ForEachFaceInstance( scene::Gra template class FaceVisitorWrapper { -const Functor& functor; + const Functor& functor; public: -FaceVisitorWrapper( const Functor& functor ) : functor( functor ){ -} + FaceVisitorWrapper( const Functor& functor ) : functor( functor ){ + } -void operator()( FaceInstance& faceInstance ) const { - functor( faceInstance.getFace() ); -} + void operator()( FaceInstance& faceInstance ) const { + functor( faceInstance.getFace() ); + } }; template diff --git a/radiant/brush_primit.cpp b/radiant/brush_primit.cpp index 39c60f23..3ab13194 100644 --- a/radiant/brush_primit.cpp +++ b/radiant/brush_primit.cpp @@ -202,7 +202,7 @@ inline void BPTexdef_fromTransform( brushprimit_texdef_t& bp_texdef, const Matri inline void Texdef_fromTransform( TextureProjection& projection, float width, float height, const Matrix4& transform ){ ASSERT_MESSAGE( ( transform[0] != 0 || transform[4] != 0 ) - && ( transform[1] != 0 || transform[5] != 0 ), "invalid texture matrix" ); + && ( transform[1] != 0 || transform[5] != 0 ), "invalid texture matrix" ); if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) { BPTexdef_fromTransform( projection.m_brushprimit_texdef, transform ); @@ -448,10 +448,10 @@ void AddPointToBounds( const Vector3& v, Vector3& mins, Vector3& maxs ){ template inline BasicVector3 vector3_inverse( const BasicVector3& self ){ return BasicVector3( - Element( 1.0 / self.x() ), - Element( 1.0 / self.y() ), - Element( 1.0 / self.z() ) - ); + Element( 1.0 / self.x() ), + Element( 1.0 / self.y() ), + Element( 1.0 / self.z() ) + ); } #endif @@ -461,7 +461,7 @@ inline BasicVector3 vector3_inverse( const BasicVector3& self // NOTE : the three vectors are understood as columns of the matrix inline float SarrusDet( const Vector3& a, const Vector3& b, const Vector3& c ){ return a[0] * b[1] * c[2] + b[0] * c[1] * a[2] + c[0] * a[1] * b[2] - - c[0] * b[1] * a[2] - a[1] * b[0] * c[2] - a[0] * b[2] * c[1]; + - c[0] * b[1] * a[2] - a[1] * b[0] * c[2] - a[0] * b[2] * c[1]; } // in many case we know three points A,B,C in two axis base B1 and B2 @@ -513,9 +513,9 @@ void FaceToBrushPrimitFace( face_t *f ){ float ST[3][5]; // [ point index ] [ xyz ST ] //++timo not used as long as brushprimit_texdef and texdef are static /* f->brushprimit_texdef.contents=f->texdef.contents; - f->brushprimit_texdef.flags=f->texdef.flags; - f->brushprimit_texdef.value=f->texdef.value; - strcpy(f->brushprimit_texdef.name,f->texdef.name); */ + f->brushprimit_texdef.flags=f->texdef.flags; + f->brushprimit_texdef.value=f->texdef.value; + strcpy(f->brushprimit_texdef.name,f->texdef.name); */ #ifdef DBG_BP if ( f->plane.normal[0] == 0.0f && f->plane.normal[1] == 0.0f && f->plane.normal[2] == 0.0f ) { globalWarningStream() << "Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n"; @@ -613,7 +613,7 @@ void TexMat_Assign( texmat_t texmat, const texmat_t other ){ } void ConvertTexMatWithDimensions( const texmat_t texmat1, std::size_t w1, std::size_t h1, - texmat_t texmat2, std::size_t w2, std::size_t h2 ){ + texmat_t texmat2, std::size_t w2, std::size_t h2 ){ TexMat_Assign( texmat2, texmat1 ); TexMat_Scale( texmat2, static_cast( w1 ) / static_cast( w2 ), static_cast( h1 ) / static_cast( h2 ) ); } @@ -622,7 +622,7 @@ void ConvertTexMatWithDimensions( const texmat_t texmat1, std::size_t w1, std::s // if 0 for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates ) void ConvertTexMatWithQTexture( const float texMat1[2][3], const qtexture_t *qtex1, float texMat2[2][3], const qtexture_t *qtex2 ){ ConvertTexMatWithDimensions( texMat1, ( qtex1 ) ? qtex1->width : 2, ( qtex1 ) ? qtex1->height : 2, - texMat2, ( qtex2 ) ? qtex2->width : 2, ( qtex2 ) ? qtex2->height : 2 ); + texMat2, ( qtex2 ) ? qtex2->width : 2, ( qtex2 ) ? qtex2->height : 2 ); } void ConvertTexMatWithQTexture( const brushprimit_texdef_t *texMat1, const qtexture_t *qtex1, brushprimit_texdef_t *texMat2, const qtexture_t *qtex2 ){ @@ -933,12 +933,12 @@ void BPMatMul( float A[2][3], float B[2][3], float C[2][3] ){ void BPMatDump( float A[2][3] ){ globalOutputStream() << "" << A[0][0] - << " " << A[0][1] - << " " << A[0][2] - << "\n" << A[1][0] - << " " << A[1][2] - << " " << A[1][2] - << "\n0 0 1\n"; + << " " << A[0][1] + << " " << A[0][2] + << "\n" << A[1][0] + << " " << A[1][2] + << " " << A[1][2] + << "\n0 0 1\n"; } void BPMatRotate( float A[2][3], float theta ){ @@ -1339,18 +1339,18 @@ inline void print_vector3( const Vector3& v ){ inline void print_3x3( const Matrix4& m ){ globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) " - << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " - << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; + << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " + << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; } inline Matrix4 matrix4_rotation_for_vector3( const Vector3& x, const Vector3& y, const Vector3& z ){ return Matrix4( - x.x(), x.y(), x.z(), 0, - y.x(), y.y(), y.z(), 0, - z.x(), z.y(), z.z(), 0, - 0, 0, 0, 1 - ); + x.x(), x.y(), x.z(), 0, + y.x(), y.y(), y.z(), 0, + z.x(), z.y(), z.z(), 0, + 0, 0, 0, 1 + ); } inline Matrix4 matrix4_swap_axes( const Vector3& from, const Vector3& to ){ @@ -1385,23 +1385,23 @@ inline Matrix4 matrix4_swap_axes( const Vector3& from, const Vector3& to ){ inline Matrix4 matrix4_reflection_for_plane( const Plane3& plane ){ return Matrix4( - static_cast( 1 - ( 2 * plane.a * plane.a ) ), - static_cast( -2 * plane.a * plane.b ), - static_cast( -2 * plane.a * plane.c ), - 0, - static_cast( -2 * plane.b * plane.a ), - static_cast( 1 - ( 2 * plane.b * plane.b ) ), - static_cast( -2 * plane.b * plane.c ), - 0, - static_cast( -2 * plane.c * plane.a ), - static_cast( -2 * plane.c * plane.b ), - static_cast( 1 - ( 2 * plane.c * plane.c ) ), - 0, - static_cast( -2 * plane.d * plane.a ), - static_cast( -2 * plane.d * plane.b ), - static_cast( -2 * plane.d * plane.c ), - 1 - ); + static_cast( 1 - ( 2 * plane.a * plane.a ) ), + static_cast( -2 * plane.a * plane.b ), + static_cast( -2 * plane.a * plane.c ), + 0, + static_cast( -2 * plane.b * plane.a ), + static_cast( 1 - ( 2 * plane.b * plane.b ) ), + static_cast( -2 * plane.b * plane.c ), + 0, + static_cast( -2 * plane.c * plane.a ), + static_cast( -2 * plane.c * plane.b ), + static_cast( 1 - ( 2 * plane.c * plane.c ) ), + 0, + static_cast( -2 * plane.d * plane.a ), + static_cast( -2 * plane.d * plane.b ), + static_cast( -2 * plane.d * plane.c ), + 1 + ); } inline Matrix4 matrix4_reflection_for_plane45( const Plane3& plane, const Vector3& from, const Vector3& to ){ @@ -1524,12 +1524,12 @@ void Texdef_transformLocked_original( TextureProjection& projection, std::size_t #endif double Det3x3( double a00, double a01, double a02, - double a10, double a11, double a12, - double a20, double a21, double a22 ){ + double a10, double a11, double a12, + double a20, double a21, double a22 ){ return - a00 * ( a11 * a22 - a12 * a21 ) - - a01 * ( a10 * a22 - a12 * a20 ) - + a02 * ( a10 * a21 - a11 * a20 ); + a00 * ( a11 * a22 - a12 * a21 ) + - a01 * ( a10 * a22 - a12 * a20 ) + + a02 * ( a10 * a21 - a11 * a20 ); } void BP_from_ST( brushprimit_texdef_t& bp, const DoubleVector3 points[3], const DoubleVector3 st[3], const DoubleVector3& normal, const bool normalize = true ){ @@ -1554,28 +1554,28 @@ void BP_from_ST( brushprimit_texdef_t& bp, const DoubleVector3 points[3], const // - st[i] = texMat[i][0]*x + texMat[i][1]*y + texMat[i][2] // (for three vertices) D = Det3x3( - xyI[0], xyI[1], 1, - xyJ[0], xyJ[1], 1, - xyK[0], xyK[1], 1 - ); + xyI[0], xyI[1], 1, + xyJ[0], xyJ[1], 1, + xyK[0], xyK[1], 1 + ); if ( D != 0 ) { for ( std::size_t i = 0; i < 2; ++i ) { D0 = Det3x3( - stI[i], xyI[1], 1, - stJ[i], xyJ[1], 1, - stK[i], xyK[1], 1 - ); + stI[i], xyI[1], 1, + stJ[i], xyJ[1], 1, + stK[i], xyK[1], 1 + ); D1 = Det3x3( - xyI[0], stI[i], 1, - xyJ[0], stJ[i], 1, - xyK[0], stK[i], 1 - ); + xyI[0], stI[i], 1, + xyJ[0], stJ[i], 1, + xyK[0], stK[i], 1 + ); D2 = Det3x3( - xyI[0], xyI[1], stI[i], - xyJ[0], xyJ[1], stJ[i], - xyK[0], xyK[1], stK[i] - ); + xyI[0], xyI[1], stI[i], + xyJ[0], xyJ[1], stJ[i], + xyK[0], xyK[1], stK[i] + ); bp.coords[i][0] = D0 / D; bp.coords[i][1] = D1 / D; bp.coords[i][2] = normalize? fmod( D2 / D, 1.0 ) : ( D2 / D ); @@ -1585,13 +1585,13 @@ void BP_from_ST( brushprimit_texdef_t& bp, const DoubleVector3 points[3], const } const Vector3 BaseAxes[] = { - Vector3( 0.0, 0.0, 1.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, -1.0, 0.0), - Vector3( 0.0, 0.0, -1.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, -1.0, 0.0), - Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 1.0, 0.0), Vector3( 0.0, 0.0, -1.0), - Vector3(-1.0, 0.0, 0.0), Vector3( 0.0, 1.0, 0.0), Vector3( 0.0, 0.0, -1.0), - Vector3( 0.0, 1.0, 0.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 0.0, -1.0), - Vector3( 0.0, -1.0, 0.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 0.0, -1.0), - }; + Vector3( 0.0, 0.0, 1.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, -1.0, 0.0), + Vector3( 0.0, 0.0, -1.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, -1.0, 0.0), + Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 1.0, 0.0), Vector3( 0.0, 0.0, -1.0), + Vector3(-1.0, 0.0, 0.0), Vector3( 0.0, 1.0, 0.0), Vector3( 0.0, 0.0, -1.0), + Vector3( 0.0, 1.0, 0.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 0.0, -1.0), + Vector3( 0.0, -1.0, 0.0), Vector3( 1.0, 0.0, 0.0), Vector3( 0.0, 0.0, -1.0), +}; std::size_t planeNormalIndex( const Vector3& normal ) { #if 0 @@ -1663,7 +1663,7 @@ void AP_from_axes( const Vector3& axisX, const Vector3& axisY, const DoubleVecto // finally compute the scaling factors Vector2 scale( vector3_length( projectedXAxis ), - vector3_length( projectedYAxis ) ); + vector3_length( projectedYAxis ) ); // the sign of the scaling factors depends on the angle between the new texture axis and the projected transformed axis if( vector3_dot( xAxis, normalizedXAxis ) < 0 ) @@ -1673,7 +1673,7 @@ void AP_from_axes( const Vector3& axisX, const Vector3& axisY, const DoubleVecto // determine the new texture coordinates of the transformed center of the face, sans offsets const Vector2 newInvariantTexCoords( vector3_dot( xAxis / scale[0], invariant ), - vector3_dot( yAxis / scale[1], invariant ) ); + vector3_dot( yAxis / scale[1], invariant ) ); // globalOutputStream() << "newInvariantTexCoords: " << newInvariantTexCoords[0] << " " << newInvariantTexCoords[1] << "\n"; // since the center should be invariant, the offsets are determined by the difference of the current and // the original texture coordinates of the center @@ -1711,7 +1711,7 @@ void Texdef_transformLocked( TextureProjection& projection, std::size_t width, s #if 0 const DoubleVector3 normalTransformed( matrix4_transformed_normal( identity2transformed, plane.normal() ) ); #else - /* this is also handling scale = 0 case */ + /* this is also handling scale = 0 case */ DoubleVector3 normalTransformed( plane3_for_points( points ).normal() ); if( matrix4_handedness( identity2transformed ) == MATRIX4_LEFTHANDED ) vector3_negate( normalTransformed ); @@ -1732,7 +1732,7 @@ void Texdef_transformLocked( TextureProjection& projection, std::size_t width, s #elif 0 const Vector3 newNormal( matrix4_transformed_normal( identity2transformed, plane.normal() ) ); #elif 1 - /* this is also handling scale = 0 case */ + /* this is also handling scale = 0 case */ DoubleVector3 texX, texY; ComputeAxisBase( plane.normal(), texX, texY ); const DoubleVector3 anchor = plane.normal() * plane.dist(); @@ -1755,12 +1755,12 @@ void Texdef_transformLocked( TextureProjection& projection, std::size_t width, s Vector3 yAxis = BaseAxes[index * 3 + 2]; Vector3 zAxis = BaseAxes[( index / 2 ) * 6]; // globalOutputStream() << xAxis << " " << yAxis << " " << zAxis << "\n"; - Matrix4 rotmat = matrix4_rotation_for_axisangle( vector3_cross( yAxis, xAxis ), degrees_to_radians( projection.m_texdef.rotate ) ); - matrix4_transform_direction( rotmat, xAxis ); - matrix4_transform_direction( rotmat, yAxis ); + Matrix4 rotmat = matrix4_rotation_for_axisangle( vector3_cross( yAxis, xAxis ), degrees_to_radians( projection.m_texdef.rotate ) ); + matrix4_transform_direction( rotmat, xAxis ); + matrix4_transform_direction( rotmat, yAxis ); const Vector2 invariantTexCoords( vector3_dot( xAxis / projection.m_texdef.scale[0], invariant ) + projection.m_texdef.shift[0], - vector3_dot( yAxis / projection.m_texdef.scale[1], invariant ) + projection.m_texdef.shift[1] ); + vector3_dot( yAxis / projection.m_texdef.scale[1], invariant ) + projection.m_texdef.shift[1] ); // globalOutputStream() << "invariantTexCoords: " << invariantTexCoords[0] << " " << invariantTexCoords[1] << "\n"; // project the texture axes onto the boundary plane along the texture Z axis const Vector3 boundaryOffset = plane3_project_point( plane, Vector3( 0, 0, 0 ), zAxis ); @@ -1833,7 +1833,7 @@ void Texdef_transform( TextureProjection& projection, std::size_t width, std::si return; //TODO FIXME !!! this (and whole pipeline?) is called with g_matrix4_identity after every transform //now only on freezeTransform, it seems } if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES || - g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_VALVE ) { + g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_VALVE ) { Texdef_transformLocked( projection, width, height, plane, identity2transformed, invariant ); } else if( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_QUAKE ) { @@ -1850,12 +1850,12 @@ void Texdef_transform( TextureProjection& projection, std::size_t width, std::si Vector3 yAxis = BaseAxes[index * 3 + 2]; Vector3 zAxis = BaseAxes[( index / 2 ) * 6]; // globalOutputStream() << xAxis << " " << yAxis << " " << zAxis << "\n"; - Matrix4 rotmat = matrix4_rotation_for_axisangle( vector3_cross( yAxis, xAxis ), degrees_to_radians( projection.m_texdef.rotate ) ); - matrix4_transform_direction( rotmat, xAxis ); - matrix4_transform_direction( rotmat, yAxis ); + Matrix4 rotmat = matrix4_rotation_for_axisangle( vector3_cross( yAxis, xAxis ), degrees_to_radians( projection.m_texdef.rotate ) ); + matrix4_transform_direction( rotmat, xAxis ); + matrix4_transform_direction( rotmat, yAxis ); const Vector2 invariantTexCoords( vector3_dot( xAxis / projection.m_texdef.scale[0], invariant ) + projection.m_texdef.shift[0], - vector3_dot( yAxis / projection.m_texdef.scale[1], invariant ) + projection.m_texdef.shift[1] ); + vector3_dot( yAxis / projection.m_texdef.scale[1], invariant ) + projection.m_texdef.shift[1] ); // globalOutputStream() << "invariantTexCoords: " << invariantTexCoords[0] << " " << invariantTexCoords[1] << "\n"; // project the texture axes onto the boundary plane along the texture Z axis const Vector3 boundaryOffset = plane3_project_point( plane, Vector3( 0, 0, 0 ), zAxis ); @@ -1994,8 +1994,8 @@ void Texdef_ProjectTexture( TextureProjection& projection, std::size_t width, st inline bool BP_degenerate( const brushprimit_texdef_t& bp ){ return vector2_cross( Vector2( bp.coords[0][0], bp.coords[0][1] ), - Vector2( bp.coords[1][0], bp.coords[1][1] ) ) == 0 - || bp.coords[0][0] != bp.coords[0][0]; + Vector2( bp.coords[1][0], bp.coords[1][1] ) ) == 0 + || bp.coords[0][0] != bp.coords[0][0]; } /// g_bp_globals.m_texdefTypeId must be == TEXDEFTYPEID_BRUSHPRIMITIVES during this @@ -2064,29 +2064,30 @@ void Valve220_from_BP( TextureProjection& projection, const Plane3& plane, std:: /// g_bp_globals.m_texdefTypeId == 'in' during this void Texdef_Convert( TexdefTypeId in, TexdefTypeId out, const Plane3& plane, TextureProjection& projection, std::size_t width, std::size_t height ) { switch( out ) { - case TEXDEFTYPEID_QUAKE: { - if( in == TEXDEFTYPEID_VALVE ){ + case TEXDEFTYPEID_QUAKE: + { + if( in == TEXDEFTYPEID_VALVE ){ + Matrix4 local2tex; + Texdef_Construct_local2tex( projection, width, height, plane.normal(), local2tex ); + BPTexdef_fromST011( projection, plane, local2tex ); + + const TexdefTypeId tmp = g_bp_globals.m_texdefTypeId; + g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES; + AP_from_BP( projection, plane, width, height ); + g_bp_globals.m_texdefTypeId = tmp; + } + else if( in == TEXDEFTYPEID_BRUSHPRIMITIVES ){ + AP_from_BP( projection, plane, width, height ); + } + } + break; + case TEXDEFTYPEID_BRUSHPRIMITIVES: + { Matrix4 local2tex; Texdef_Construct_local2tex( projection, width, height, plane.normal(), local2tex ); BPTexdef_fromST011( projection, plane, local2tex ); - - const TexdefTypeId tmp = g_bp_globals.m_texdefTypeId; - g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES; - AP_from_BP( projection, plane, width, height ); - g_bp_globals.m_texdefTypeId = tmp; } - else if( in == TEXDEFTYPEID_BRUSHPRIMITIVES ){ - AP_from_BP( projection, plane, width, height ); - } - } - break; - case TEXDEFTYPEID_BRUSHPRIMITIVES: - { - Matrix4 local2tex; - Texdef_Construct_local2tex( projection, width, height, plane.normal(), local2tex ); - BPTexdef_fromST011( projection, plane, local2tex ); - } - break; + break; case TEXDEFTYPEID_VALVE: if( in == TEXDEFTYPEID_QUAKE ) { Matrix4 basis; diff --git a/radiant/brush_primit.h b/radiant/brush_primit.h index cdf0cb40..e5ba745d 100644 --- a/radiant/brush_primit.h +++ b/radiant/brush_primit.h @@ -65,24 +65,24 @@ struct brushprimit_texdef_t class TextureProjection { public: -texdef_t m_texdef; -brushprimit_texdef_t m_brushprimit_texdef; -Vector3 m_basis_s; -Vector3 m_basis_t; + texdef_t m_texdef; + brushprimit_texdef_t m_brushprimit_texdef; + Vector3 m_basis_s; + Vector3 m_basis_t; -TextureProjection(){ -} -TextureProjection( - const texdef_t& texdef, - const brushprimit_texdef_t& brushprimit_texdef, - const Vector3& basis_s, - const Vector3& basis_t + TextureProjection(){ + } + TextureProjection( + const texdef_t& texdef, + const brushprimit_texdef_t& brushprimit_texdef, + const Vector3& basis_s, + const Vector3& basis_t ) : - m_texdef( texdef ), - m_brushprimit_texdef( brushprimit_texdef ), - m_basis_s( basis_s ), - m_basis_t( basis_t ){ -} + m_texdef( texdef ), + m_brushprimit_texdef( brushprimit_texdef ), + m_basis_s( basis_s ), + m_basis_t( basis_t ){ + } }; float Texdef_getDefaultTextureScale(); diff --git a/radiant/brushmanip.cpp b/radiant/brushmanip.cpp index b04fa2ca..3589ffe5 100644 --- a/radiant/brushmanip.cpp +++ b/radiant/brushmanip.cpp @@ -418,58 +418,58 @@ void Brush_ConstructPrefab( Brush& brush, EBrushPrefab type, const AABB& bounds, switch ( type ) { case eBrushCuboid: - { - UndoableCommand undo( "brushCuboid" ); + { + UndoableCommand undo( "brushCuboid" ); - Brush_ConstructCuboid( brush, bounds, shader, projection ); - } - break; + Brush_ConstructCuboid( brush, bounds, shader, projection ); + } + break; case eBrushPrism: - { - const int axis = GlobalXYWnd_getCurrentViewType(); - StringOutputStream command; - command << c_brushPrism_name << " -sides " << Unsigned( sides ) << " -axis " << axis; - UndoableCommand undo( command.c_str() ); + { + const int axis = GlobalXYWnd_getCurrentViewType(); + StringOutputStream command; + command << c_brushPrism_name << " -sides " << Unsigned( sides ) << " -axis " << axis; + UndoableCommand undo( command.c_str() ); - Brush_ConstructPrism( brush, bounds, sides, axis, shader, projection ); - } - break; + Brush_ConstructPrism( brush, bounds, sides, axis, shader, projection ); + } + break; case eBrushCone: - { - StringOutputStream command; - command << c_brushCone_name << " -sides " << Unsigned( sides ); - UndoableCommand undo( command.c_str() ); + { + StringOutputStream command; + command << c_brushCone_name << " -sides " << Unsigned( sides ); + UndoableCommand undo( command.c_str() ); - Brush_ConstructCone( brush, bounds, sides, shader, projection ); - } - break; + Brush_ConstructCone( brush, bounds, sides, shader, projection ); + } + break; case eBrushSphere: - { - StringOutputStream command; - command << c_brushSphere_name << " -sides " << Unsigned( sides ); - UndoableCommand undo( command.c_str() ); + { + StringOutputStream command; + command << c_brushSphere_name << " -sides " << Unsigned( sides ); + UndoableCommand undo( command.c_str() ); - Brush_ConstructSphere( brush, bounds, sides, shader, projection ); - } - break; + Brush_ConstructSphere( brush, bounds, sides, shader, projection ); + } + break; case eBrushRock: - { - StringOutputStream command; - command << c_brushRock_name << " -sides " << Unsigned( sides ); - UndoableCommand undo( command.c_str() ); + { + StringOutputStream command; + command << c_brushRock_name << " -sides " << Unsigned( sides ); + UndoableCommand undo( command.c_str() ); - Brush_ConstructRock( brush, bounds, sides, shader, projection ); - } - break; + Brush_ConstructRock( brush, bounds, sides, shader, projection ); + } + break; case eBrushIcosahedron: - { - StringOutputStream command; - command << "brushIcosahedron" << " -subdivisions " << Unsigned( sides ); - UndoableCommand undo( command.c_str() ); + { + StringOutputStream command; + command << "brushIcosahedron" << " -subdivisions " << Unsigned( sides ); + UndoableCommand undo( command.c_str() ); - icosahedron::Brush_ConstructIcosahedron( brush, bounds, sides, option, shader, projection ); - } - break; + icosahedron::Brush_ConstructIcosahedron( brush, bounds, sides, option, shader, projection ); + } + break; } } @@ -505,15 +505,15 @@ void ConstructRegionBrushes( scene::Node* brushes[6], const Vector3& region_mins class FaceSetTexdef { -const TextureProjection& m_projection; -const bool m_setBasis; -const bool m_resetBasis; + const TextureProjection& m_projection; + const bool m_setBasis; + const bool m_resetBasis; public: -FaceSetTexdef( const TextureProjection& projection, bool setBasis, bool resetBasis ) : m_projection( projection ), m_setBasis( setBasis ), m_resetBasis( resetBasis ){ -} -void operator()( Face& face ) const { - face.SetTexdef( m_projection, m_setBasis, m_resetBasis ); -} + FaceSetTexdef( const TextureProjection& projection, bool setBasis, bool resetBasis ) : m_projection( projection ), m_setBasis( setBasis ), m_resetBasis( resetBasis ){ + } + void operator()( Face& face ) const { + face.SetTexdef( m_projection, m_setBasis, m_resetBasis ); + } }; void Scene_BrushSetTexdef_Selected( scene::Graph& graph, const TextureProjection& projection, bool setBasis, bool resetBasis ){ @@ -528,18 +528,18 @@ void Scene_BrushSetTexdef_Component_Selected( scene::Graph& graph, const Texture class FaceSetTexdef_ { -const float* m_hShift; -const float* m_vShift; -const float* m_hScale; -const float* m_vScale; -const float* m_rotation; + const float* m_hShift; + const float* m_vShift; + const float* m_hScale; + const float* m_vScale; + const float* m_rotation; public: -FaceSetTexdef_( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ) : - m_hShift( hShift ), m_vShift( vShift ), m_hScale( hScale ), m_vScale( vScale ), m_rotation( rotation ) { -} -void operator()( Face& face ) const { - face.SetTexdef( m_hShift, m_vShift, m_hScale, m_vScale, m_rotation ); -} + FaceSetTexdef_( const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ) : + m_hShift( hShift ), m_vShift( vShift ), m_hScale( hScale ), m_vScale( vScale ), m_rotation( rotation ) { + } + void operator()( Face& face ) const { + face.SetTexdef( m_hShift, m_vShift, m_hScale, m_vScale, m_rotation ); + } }; void Scene_BrushSetTexdef_Selected( scene::Graph& graph, const float* hShift, const float* vShift, const float* hScale, const float* vScale, const float* rotation ){ @@ -555,13 +555,13 @@ void Scene_BrushSetTexdef_Component_Selected( scene::Graph& graph, const float* class FaceSetFlags { -const ContentsFlagsValue& m_flags; + const ContentsFlagsValue& m_flags; public: -FaceSetFlags( const ContentsFlagsValue& flags ) : m_flags( flags ){ -} -void operator()( Face& face ) const { - face.SetFlags( m_flags ); -} + FaceSetFlags( const ContentsFlagsValue& flags ) : m_flags( flags ){ + } + void operator()( Face& face ) const { + face.SetFlags( m_flags ); + } }; void Scene_BrushSetFlags_Selected( scene::Graph& graph, const ContentsFlagsValue& flags ){ @@ -576,13 +576,13 @@ void Scene_BrushSetFlags_Component_Selected( scene::Graph& graph, const Contents class FaceShiftTexdef { -float m_s, m_t; + float m_s, m_t; public: -FaceShiftTexdef( float s, float t ) : m_s( s ), m_t( t ){ -} -void operator()( Face& face ) const { - face.ShiftTexdef( m_s, m_t ); -} + FaceShiftTexdef( float s, float t ) : m_s( s ), m_t( t ){ + } + void operator()( Face& face ) const { + face.ShiftTexdef( m_s, m_t ); + } }; void Scene_BrushShiftTexdef_Selected( scene::Graph& graph, float s, float t ){ @@ -597,13 +597,13 @@ void Scene_BrushShiftTexdef_Component_Selected( scene::Graph& graph, float s, fl class FaceScaleTexdef { -float m_s, m_t; + float m_s, m_t; public: -FaceScaleTexdef( float s, float t ) : m_s( s ), m_t( t ){ -} -void operator()( Face& face ) const { - face.ScaleTexdef( m_s, m_t ); -} + FaceScaleTexdef( float s, float t ) : m_s( s ), m_t( t ){ + } + void operator()( Face& face ) const { + face.ScaleTexdef( m_s, m_t ); + } }; void Scene_BrushScaleTexdef_Selected( scene::Graph& graph, float s, float t ){ @@ -618,13 +618,13 @@ void Scene_BrushScaleTexdef_Component_Selected( scene::Graph& graph, float s, fl class FaceRotateTexdef { -float m_angle; + float m_angle; public: -FaceRotateTexdef( float angle ) : m_angle( angle ){ -} -void operator()( Face& face ) const { - face.RotateTexdef( m_angle ); -} + FaceRotateTexdef( float angle ) : m_angle( angle ){ + } + void operator()( Face& face ) const { + face.RotateTexdef( m_angle ); + } }; void Scene_BrushRotateTexdef_Selected( scene::Graph& graph, float angle ){ @@ -640,12 +640,12 @@ void Scene_BrushRotateTexdef_Component_Selected( scene::Graph& graph, float angl class FaceSetShader { -const char* m_name; + const char* m_name; public: -FaceSetShader( const char* name ) : m_name( name ) {} -void operator()( Face& face ) const { - face.SetShader( m_name ); -} + FaceSetShader( const char* name ) : m_name( name ) {} + void operator()( Face& face ) const { + face.SetShader( m_name ); + } }; void Scene_BrushSetShader_Selected( scene::Graph& graph, const char* name ){ @@ -660,13 +660,13 @@ void Scene_BrushSetShader_Component_Selected( scene::Graph& graph, const char* n class FaceSetDetail { -bool m_detail; + bool m_detail; public: -FaceSetDetail( bool detail ) : m_detail( detail ){ -} -void operator()( Face& face ) const { - face.setDetail( m_detail ); -} + FaceSetDetail( bool detail ) : m_detail( detail ){ + } + void operator()( Face& face ) const { + face.setDetail( m_detail ); + } }; void Scene_BrushSetDetail_Selected( scene::Graph& graph, bool detail ){ @@ -684,28 +684,28 @@ bool Face_FindReplaceShader( Face& face, const char* find, const char* replace ) class FaceFindReplaceShader { -const char* m_find; -const char* m_replace; + const char* m_find; + const char* m_replace; public: -FaceFindReplaceShader( const char* find, const char* replace ) : m_find( find ), m_replace( replace ){ -} -void operator()( Face& face ) const { - Face_FindReplaceShader( face, m_find, m_replace ); -} + FaceFindReplaceShader( const char* find, const char* replace ) : m_find( find ), m_replace( replace ){ + } + void operator()( Face& face ) const { + Face_FindReplaceShader( face, m_find, m_replace ); + } }; class FaceSelectByShader { -const char* m_name; + const char* m_name; public: -FaceSelectByShader( const char* name ) - : m_name( name ){ -} -void operator()( FaceInstance& face ) const { - if ( shader_equal( face.getFace().GetShader(), m_name ) ) { - face.setSelected( SelectionSystem::eFace, true ); + FaceSelectByShader( const char* name ) + : m_name( name ){ + } + void operator()( FaceInstance& face ) const { + if ( shader_equal( face.getFace().GetShader(), m_name ) ) { + face.setSelected( SelectionSystem::eFace, true ); + } } -} }; void Scene_BrushFacesSelectByShader( scene::Graph& graph, const char* name ){ @@ -724,13 +724,11 @@ void Scene_BrushFindReplaceShader( scene::Graph& graph, const char* find, const void Scene_BrushFindReplaceShader_Selected( scene::Graph& graph, const char* find, const char* replace ){ if ( !replace ) { - Scene_ForEachSelectedBrush_ForEachFaceInstance( graph, - FaceSelectByShader( find ) ); + Scene_ForEachSelectedBrush_ForEachFaceInstance( graph, FaceSelectByShader( find ) ); } else { - Scene_ForEachSelectedBrush_ForEachFace( graph, - FaceFindReplaceShader( find, replace ) ); + Scene_ForEachSelectedBrush_ForEachFace( graph, FaceFindReplaceShader( find, replace ) ); } } @@ -738,8 +736,7 @@ void Scene_BrushFindReplaceShader_Selected( scene::Graph& graph, const char* fin // d1223m: dont even know what they are... void Scene_BrushFindReplaceShader_Component_Selected( scene::Graph& graph, const char* find, const char* replace ){ if ( !replace ) { - Scene_ForEachSelectedBrush_ForEachFaceInstance( graph, - FaceSelectByShader( find ) ); + Scene_ForEachSelectedBrush_ForEachFaceInstance( graph, FaceSelectByShader( find ) ); } else { @@ -795,14 +792,14 @@ void Scene_BrushProjectTexture_Component_Selected( scene::Graph& graph, const Te class FaceFitTexture { -const float m_s_repeat, m_t_repeat; -const bool m_only_dimension; + const float m_s_repeat, m_t_repeat; + const bool m_only_dimension; public: -FaceFitTexture( float s_repeat, float t_repeat, bool only_dimension ) : m_s_repeat( s_repeat ), m_t_repeat( t_repeat ), m_only_dimension( only_dimension ) { -} -void operator()( Face& face ) const { - face.FitTexture( m_s_repeat, m_t_repeat, m_only_dimension ); -} + FaceFitTexture( float s_repeat, float t_repeat, bool only_dimension ) : m_s_repeat( s_repeat ), m_t_repeat( t_repeat ), m_only_dimension( only_dimension ) { + } + void operator()( Face& face ) const { + face.FitTexture( m_s_repeat, m_t_repeat, m_only_dimension ); + } }; void Scene_BrushFitTexture_Selected( scene::Graph& graph, float s_repeat, float t_repeat, bool only_dimension ){ @@ -853,8 +850,8 @@ void Scene_BrushResize_Cuboid( scene::Node*& node, const AABB& bounds ){ Brush* brush = Node_getBrush( *node ); if ( brush != 0 ) { const char* shader = g_brush_always_caulk? - GetCaulkShader() - : TextureBrowser_GetSelectedShader(); + GetCaulkShader() + : TextureBrowser_GetSelectedShader(); Brush_ConstructCuboid( *brush, bounds, shader, TextureTransform_getDefault() ); SceneChangeNotify(); } @@ -878,23 +875,23 @@ bool Brush_hasShader( const Brush& brush, const char* name ){ class BrushSelectByShaderWalker : public scene::Graph::Walker { -const char* m_name; + const char* m_name; public: -BrushSelectByShaderWalker( const char* name ) - : m_name( name ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 && Brush_hasShader( *brush, m_name ) ) { - Instance_getSelectable( instance )->setSelected( true ); + BrushSelectByShaderWalker( const char* name ) + : m_name( name ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 && Brush_hasShader( *brush, m_name ) ) { + Instance_getSelectable( instance )->setSelected( true ); + } } + else{ + return false; + } + return true; } - else{ - return false; - } - return true; -} }; void Scene_BrushSelectByShader( scene::Graph& graph, const char* name ){ @@ -907,18 +904,18 @@ void Scene_BrushSelectByShader_Component( scene::Graph& graph, const char* name class FaceGetTexdef { -TextureProjection& m_projection; -mutable bool m_done; + TextureProjection& m_projection; + mutable bool m_done; public: -FaceGetTexdef( TextureProjection& projection ) - : m_projection( projection ), m_done( false ){ -} -void operator()( Face& face ) const { - if ( !m_done ) { - m_done = true; - face.GetTexdef( m_projection ); + FaceGetTexdef( TextureProjection& projection ) + : m_projection( projection ), m_done( false ){ + } + void operator()( Face& face ) const { + if ( !m_done ) { + m_done = true; + face.GetTexdef( m_projection ); + } } -} }; @@ -949,18 +946,18 @@ void Scene_BrushGetShaderSize_Component_Selected( scene::Graph& graph, size_t& w class FaceGetFlags { -ContentsFlagsValue& m_flags; -mutable bool m_done; + ContentsFlagsValue& m_flags; + mutable bool m_done; public: -FaceGetFlags( ContentsFlagsValue& flags ) - : m_flags( flags ), m_done( false ){ -} -void operator()( Face& face ) const { - if ( !m_done ) { - m_done = true; - face.GetFlags( m_flags ); + FaceGetFlags( ContentsFlagsValue& flags ) + : m_flags( flags ), m_done( false ){ + } + void operator()( Face& face ) const { + if ( !m_done ) { + m_done = true; + face.GetFlags( m_flags ); + } } -} }; @@ -991,18 +988,18 @@ void Scene_BrushGetFlags_Component_Selected( scene::Graph& graph, ContentsFlagsV class FaceGetShader { -CopiedString& m_shader; -mutable bool m_done; + CopiedString& m_shader; + mutable bool m_done; public: -FaceGetShader( CopiedString& shader ) - : m_shader( shader ), m_done( false ){ -} -void operator()( Face& face ) const { - if ( !m_done ) { - m_done = true; - m_shader = face.GetShader(); + FaceGetShader( CopiedString& shader ) + : m_shader( shader ), m_done( false ){ + } + void operator()( Face& face ) const { + if ( !m_done ) { + m_done = true; + m_shader = face.GetShader(); + } } -} }; void Scene_BrushGetShader_Selected( scene::Graph& graph, CopiedString& shader ){ @@ -1033,104 +1030,104 @@ void Scene_BrushGetShader_Component_Selected( scene::Graph& graph, CopiedString& class filter_face_shader : public FaceFilter { -const char* m_shader; + const char* m_shader; public: -filter_face_shader( const char* shader ) : m_shader( shader ){ -} -bool filter( const Face& face ) const { - return shader_equal( face.GetShader(), m_shader ); -} + filter_face_shader( const char* shader ) : m_shader( shader ){ + } + bool filter( const Face& face ) const { + return shader_equal( face.GetShader(), m_shader ); + } }; class filter_face_shader_prefix : public FaceFilter { -const char* m_prefix; + const char* m_prefix; public: -filter_face_shader_prefix( const char* prefix ) : m_prefix( prefix ){ -} -bool filter( const Face& face ) const { - return shader_equal_n( face.GetShader(), m_prefix, strlen( m_prefix ) ); -} + filter_face_shader_prefix( const char* prefix ) : m_prefix( prefix ){ + } + bool filter( const Face& face ) const { + return shader_equal_n( face.GetShader(), m_prefix, strlen( m_prefix ) ); + } }; class filter_face_flags : public FaceFilter { -int m_flags; + int m_flags; public: -filter_face_flags( int flags ) : m_flags( flags ){ -} -bool filter( const Face& face ) const { - return ( face.getShader().shaderFlags() & m_flags ) != 0; -} + filter_face_flags( int flags ) : m_flags( flags ){ + } + bool filter( const Face& face ) const { + return ( face.getShader().shaderFlags() & m_flags ) != 0; + } }; class filter_face_contents : public FaceFilter { -int m_contents; + int m_contents; public: -filter_face_contents( int contents ) : m_contents( contents ){ -} -bool filter( const Face& face ) const { - return ( face.getShader().m_flags.m_contentFlags & m_contents ) != 0; -} + filter_face_contents( int contents ) : m_contents( contents ){ + } + bool filter( const Face& face ) const { + return ( face.getShader().m_flags.m_contentFlags & m_contents ) != 0; + } }; class FaceFilterAny { -FaceFilter* m_filter; -bool& m_filtered; + FaceFilter* m_filter; + bool& m_filtered; public: -FaceFilterAny( FaceFilter* filter, bool& filtered ) : m_filter( filter ), m_filtered( filtered ){ - m_filtered = false; -} -void operator()( Face& face ) const { - if ( m_filter->filter( face ) ) { - m_filtered = true; + FaceFilterAny( FaceFilter* filter, bool& filtered ) : m_filter( filter ), m_filtered( filtered ){ + m_filtered = false; + } + void operator()( Face& face ) const { + if ( m_filter->filter( face ) ) { + m_filtered = true; + } } -} }; class filter_brush_any_face : public BrushFilter { -FaceFilter* m_filter; + FaceFilter* m_filter; public: -filter_brush_any_face( FaceFilter* filter ) : m_filter( filter ){ -} -bool filter( const Brush& brush ) const { - bool filtered; - Brush_forEachFace( brush, FaceFilterAny( m_filter, filtered ) ); - return filtered; -} + filter_brush_any_face( FaceFilter* filter ) : m_filter( filter ){ + } + bool filter( const Brush& brush ) const { + bool filtered; + Brush_forEachFace( brush, FaceFilterAny( m_filter, filtered ) ); + return filtered; + } }; class FaceFilterAll { -FaceFilter* m_filter; -bool& m_filtered; + FaceFilter* m_filter; + bool& m_filtered; public: -FaceFilterAll( FaceFilter* filter, bool& filtered ) : m_filter( filter ), m_filtered( filtered ){ - m_filtered = true; -} -void operator()( Face& face ) const { - if ( !m_filter->filter( face ) ) { - m_filtered = false; + FaceFilterAll( FaceFilter* filter, bool& filtered ) : m_filter( filter ), m_filtered( filtered ){ + m_filtered = true; + } + void operator()( Face& face ) const { + if ( !m_filter->filter( face ) ) { + m_filtered = false; + } } -} }; class filter_brush_all_faces : public BrushFilter { -FaceFilter* m_filter; + FaceFilter* m_filter; public: -filter_brush_all_faces( FaceFilter* filter ) : m_filter( filter ){ -} -bool filter( const Brush& brush ) const { - bool filtered; - Brush_forEachFace( brush, FaceFilterAll( m_filter, filtered ) ); - return filtered; -} + filter_brush_all_faces( FaceFilter* filter ) : m_filter( filter ){ + } + bool filter( const Brush& brush ) const { + bool filtered; + Brush_forEachFace( brush, FaceFilterAll( m_filter, filtered ) ); + return filtered; + } }; @@ -1246,10 +1243,10 @@ void normalquantisation_draw(){ for ( std::size_t j = 0; j <= c_quantise_normal; ++j ) { Normal3f vertex( normal3f_normalised( Normal3f( - static_cast( c_quantise_normal - j - i ), - static_cast( i ), - static_cast( j ) - ) ) ); + static_cast( c_quantise_normal - j - i ), + static_cast( i ), + static_cast( j ) + ) ) ); VectorScale( normal3f_to_array( vertex ), 64.f, normal3f_to_array( vertex ) ); glVertex3fv( normal3f_to_array( vertex ) ); vertex.x = -vertex.x; @@ -1262,115 +1259,115 @@ void normalquantisation_draw(){ class RenderableNormalQuantisation : public OpenGLRenderable { public: -void render( RenderStateFlags state ) const { - normalquantisation_draw(); -} + void render( RenderStateFlags state ) const { + normalquantisation_draw(); + } }; const float g_test_quantise_normal = 1.f / static_cast( 1 << 3 ); class TestNormalQuantisation { -void check_normal( const Normal3f& normal, const Normal3f& other ){ - spherical_t spherical = spherical_from_normal3f( normal ); - double longditude = RAD2DEG( spherical.longditude ); - double latitude = RAD2DEG( spherical.latitude ); - double x = cos( spherical.longditude ) * sin( spherical.latitude ); - double y = sin( spherical.longditude ) * sin( spherical.latitude ); - double z = cos( spherical.latitude ); + void check_normal( const Normal3f& normal, const Normal3f& other ){ + spherical_t spherical = spherical_from_normal3f( normal ); + double longditude = RAD2DEG( spherical.longditude ); + double latitude = RAD2DEG( spherical.latitude ); + double x = cos( spherical.longditude ) * sin( spherical.latitude ); + double y = sin( spherical.longditude ) * sin( spherical.latitude ); + double z = cos( spherical.latitude ); - ASSERT_MESSAGE( normal3f_dot( normal, other ) > 0.99, "bleh" ); -} - -void test_normal( const Normal3f& normal ){ - Normal3f test = normal3f_from_spherical( spherical_from_normal3f( normal ) ); - check_normal( normal, test ); - - EOctant octant = normal3f_classify_octant( normal ); - Normal3f folded = normal3f_fold_octant( normal, octant ); - ESextant sextant = normal3f_classify_sextant( folded ); - folded = normal3f_fold_sextant( folded, sextant ); - - double scale = static_cast( c_quantise_normal ) / ( folded.x + folded.y + folded.z ); - - double zbits = folded.z * scale; - double ybits = folded.y * scale; - - std::size_t zbits_q = static_cast( zbits ); - std::size_t ybits_q = static_cast( ybits ); - - ASSERT_MESSAGE( zbits_q <= ( c_quantise_normal / 8 ) * 3, "bleh" ); - ASSERT_MESSAGE( ybits_q <= ( c_quantise_normal / 2 ), "bleh" ); - ASSERT_MESSAGE( zbits_q + ( ( c_quantise_normal / 2 ) - ybits_q ) <= ( c_quantise_normal / 2 ), "bleh" ); - - std::size_t y_t = ( zbits_q < ( c_quantise_normal / 4 ) ) ? ybits_q : ( c_quantise_normal / 2 ) - ybits_q; - std::size_t z_t = ( zbits_q < ( c_quantise_normal / 4 ) ) ? zbits_q : ( c_quantise_normal / 2 ) - zbits_q; - std::size_t index = ( c_quantise_normal / 4 ) * y_t + z_t; - ASSERT_MESSAGE( index <= ( c_quantise_normal / 4 ) * ( c_quantise_normal / 2 ), "bleh" ); - - Normal3f tmp( c_quantise_normal - zbits_q - ybits_q, ybits_q, zbits_q ); - tmp = normal3f_normalised( tmp ); - - Normal3f unfolded = normal3f_unfold_octant( normal3f_unfold_sextant( tmp, sextant ), octant ); - - check_normal( normal, unfolded ); - - double dot = normal3f_dot( normal, unfolded ); - float length = VectorLength( normal3f_to_array( unfolded ) ); - float inv_length = 1 / length; - - Normal3f quantised = normal3f_quantised( normal ); - check_normal( normal, quantised ); -} -void test2( const Normal3f& normal, const Normal3f& other ){ - if ( normal3f_quantised( normal ) != normal3f_quantised( other ) ) { - int bleh = 0; + ASSERT_MESSAGE( normal3f_dot( normal, other ) > 0.99, "bleh" ); } -} -static Normal3f normalise( float x, float y, float z ){ - return normal3f_normalised( Normal3f( x, y, z ) ); -} + void test_normal( const Normal3f& normal ){ + Normal3f test = normal3f_from_spherical( spherical_from_normal3f( normal ) ); + check_normal( normal, test ); -float vec_rand(){ - return static_cast( rand() - ( RAND_MAX / 2 ) ); -} + EOctant octant = normal3f_classify_octant( normal ); + Normal3f folded = normal3f_fold_octant( normal, octant ); + ESextant sextant = normal3f_classify_sextant( folded ); + folded = normal3f_fold_sextant( folded, sextant ); -Normal3f normal3f_rand(){ - return normalise( vec_rand(), vec_rand(), vec_rand() ); -} + double scale = static_cast( c_quantise_normal ) / ( folded.x + folded.y + folded.z ); + + double zbits = folded.z * scale; + double ybits = folded.y * scale; + + std::size_t zbits_q = static_cast( zbits ); + std::size_t ybits_q = static_cast( ybits ); + + ASSERT_MESSAGE( zbits_q <= ( c_quantise_normal / 8 ) * 3, "bleh" ); + ASSERT_MESSAGE( ybits_q <= ( c_quantise_normal / 2 ), "bleh" ); + ASSERT_MESSAGE( zbits_q + ( ( c_quantise_normal / 2 ) - ybits_q ) <= ( c_quantise_normal / 2 ), "bleh" ); + + std::size_t y_t = ( zbits_q < ( c_quantise_normal / 4 ) ) ? ybits_q : ( c_quantise_normal / 2 ) - ybits_q; + std::size_t z_t = ( zbits_q < ( c_quantise_normal / 4 ) ) ? zbits_q : ( c_quantise_normal / 2 ) - zbits_q; + std::size_t index = ( c_quantise_normal / 4 ) * y_t + z_t; + ASSERT_MESSAGE( index <= ( c_quantise_normal / 4 ) * ( c_quantise_normal / 2 ), "bleh" ); + + Normal3f tmp( c_quantise_normal - zbits_q - ybits_q, ybits_q, zbits_q ); + tmp = normal3f_normalised( tmp ); + + Normal3f unfolded = normal3f_unfold_octant( normal3f_unfold_sextant( tmp, sextant ), octant ); + + check_normal( normal, unfolded ); + + double dot = normal3f_dot( normal, unfolded ); + float length = VectorLength( normal3f_to_array( unfolded ) ); + float inv_length = 1 / length; + + Normal3f quantised = normal3f_quantised( normal ); + check_normal( normal, quantised ); + } + void test2( const Normal3f& normal, const Normal3f& other ){ + if ( normal3f_quantised( normal ) != normal3f_quantised( other ) ) { + int bleh = 0; + } + } + + static Normal3f normalise( float x, float y, float z ){ + return normal3f_normalised( Normal3f( x, y, z ) ); + } + + float vec_rand(){ + return static_cast( rand() - ( RAND_MAX / 2 ) ); + } + + Normal3f normal3f_rand(){ + return normalise( vec_rand(), vec_rand(), vec_rand() ); + } public: -TestNormalQuantisation(){ - for ( int i = 4096; i > 0; --i ) - test_normal( normal3f_rand() ); + TestNormalQuantisation(){ + for ( int i = 4096; i > 0; --i ) + test_normal( normal3f_rand() ); - test_normal( normalise( 1, 0, 0 ) ); - test_normal( normalise( 0, 1, 0 ) ); - test_normal( normalise( 0, 0, 1 ) ); - test_normal( normalise( 1, 1, 0 ) ); - test_normal( normalise( 1, 0, 1 ) ); - test_normal( normalise( 0, 1, 1 ) ); + test_normal( normalise( 1, 0, 0 ) ); + test_normal( normalise( 0, 1, 0 ) ); + test_normal( normalise( 0, 0, 1 ) ); + test_normal( normalise( 1, 1, 0 ) ); + test_normal( normalise( 1, 0, 1 ) ); + test_normal( normalise( 0, 1, 1 ) ); - test_normal( normalise( 10000, 10000, 10000 ) ); - test_normal( normalise( 10000, 10000, 10001 ) ); - test_normal( normalise( 10000, 10000, 10002 ) ); - test_normal( normalise( 10000, 10000, 10010 ) ); - test_normal( normalise( 10000, 10000, 10020 ) ); - test_normal( normalise( 10000, 10000, 10030 ) ); - test_normal( normalise( 10000, 10000, 10100 ) ); - test_normal( normalise( 10000, 10000, 10101 ) ); - test_normal( normalise( 10000, 10000, 10102 ) ); - test_normal( normalise( 10000, 10000, 10200 ) ); - test_normal( normalise( 10000, 10000, 10201 ) ); - test_normal( normalise( 10000, 10000, 10202 ) ); - test_normal( normalise( 10000, 10000, 10203 ) ); - test_normal( normalise( 10000, 10000, 10300 ) ); + test_normal( normalise( 10000, 10000, 10000 ) ); + test_normal( normalise( 10000, 10000, 10001 ) ); + test_normal( normalise( 10000, 10000, 10002 ) ); + test_normal( normalise( 10000, 10000, 10010 ) ); + test_normal( normalise( 10000, 10000, 10020 ) ); + test_normal( normalise( 10000, 10000, 10030 ) ); + test_normal( normalise( 10000, 10000, 10100 ) ); + test_normal( normalise( 10000, 10000, 10101 ) ); + test_normal( normalise( 10000, 10000, 10102 ) ); + test_normal( normalise( 10000, 10000, 10200 ) ); + test_normal( normalise( 10000, 10000, 10201 ) ); + test_normal( normalise( 10000, 10000, 10202 ) ); + test_normal( normalise( 10000, 10000, 10203 ) ); + test_normal( normalise( 10000, 10000, 10300 ) ); - test2( normalise( 10000, 10000, 10000 ), normalise( 10000, 10000, 10001 ) ); - test2( normalise( 10000, 10000, 10001 ), normalise( 10000, 10001, 10000 ) ); -} + test2( normalise( 10000, 10000, 10000 ), normalise( 10000, 10000, 10001 ) ); + test2( normalise( 10000, 10000, 10001 ), normalise( 10000, 10001, 10000 ) ); + } }; TestNormalQuantisation g_testNormalQuantisation; @@ -1382,9 +1379,9 @@ TestNormalQuantisation g_testNormalQuantisation; class TestSelectableObserver : public observer_template { public: -void notify( const Selectable& arguments ){ - bool bleh = arguments.isSelected(); -} + void notify( const Selectable& arguments ){ + bool bleh = arguments.isSelected(); + } }; inline void test_bleh(){ @@ -1398,9 +1395,9 @@ inline void test_bleh(){ class TestBleh { public: -TestBleh(){ - test_bleh(); -} + TestBleh(){ + test_bleh(); + } }; const TestBleh testbleh; @@ -1411,37 +1408,37 @@ const TestBleh testbleh; class TestRefcountedString { public: -TestRefcountedString(){ - { - // copy construct - SmartString string1( "string1" ); - SmartString string2( string1 ); - SmartString string3( string2 ); + TestRefcountedString(){ + { + // copy construct + SmartString string1( "string1" ); + SmartString string2( string1 ); + SmartString string3( string2 ); + } + { + // refcounted assignment + SmartString string1( "string1" ); + SmartString string2( "string2" ); + string1 = string2; + } + { + // copy assignment + SmartString string1( "string1" ); + SmartString string2( "string2" ); + string1 = string2.c_str(); + } + { + // self-assignment + SmartString string1( "string1" ); + string1 = string1; + } + { + // self-assignment via another reference + SmartString string1( "string1" ); + SmartString string2( string1 ); + string1 = string2; + } } - { - // refcounted assignment - SmartString string1( "string1" ); - SmartString string2( "string2" ); - string1 = string2; - } - { - // copy assignment - SmartString string1( "string1" ); - SmartString string2( "string2" ); - string1 = string2.c_str(); - } - { - // self-assignment - SmartString string1( "string1" ); - string1 = string1; - } - { - // self-assignment via another reference - SmartString string1( "string1" ); - SmartString string2( string1 ); - string1 = string2; - } -} }; const TestRefcountedString g_testRefcountedString; @@ -1460,15 +1457,15 @@ void Select_MakeStructural(){ class BrushMakeSided { -std::size_t m_count; + std::size_t m_count; public: -BrushMakeSided( std::size_t count ) - : m_count( count ){ -} -void set(){ - Scene_BrushConstructPrefab( GlobalSceneGraph(), eBrushPrism, m_count, false, TextureBrowser_GetSelectedShader() ); -} -typedef MemberCaller SetCaller; + BrushMakeSided( std::size_t count ) + : m_count( count ){ + } + void set(){ + Scene_BrushConstructPrefab( GlobalSceneGraph(), eBrushPrism, m_count, false, TextureBrowser_GetSelectedShader() ); + } + typedef MemberCaller SetCaller; }; @@ -1483,15 +1480,15 @@ BrushMakeSided g_brushmakesided9( 9 ); class BrushPrefab { -EBrushPrefab m_type; + EBrushPrefab m_type; public: -BrushPrefab( EBrushPrefab type ) - : m_type( type ){ -} -void set(){ - DoSides( m_type, GlobalXYWnd_getCurrentViewType() ); -} -typedef MemberCaller SetCaller; + BrushPrefab( EBrushPrefab type ) + : m_type( type ){ + } + void set(){ + DoSides( m_type, GlobalXYWnd_getCurrentViewType() ); + } + typedef MemberCaller SetCaller; }; BrushPrefab g_brushprism( eBrushPrism ); diff --git a/radiant/brushmodule.cpp b/radiant/brushmodule.cpp index c71b38ef..479445d0 100644 --- a/radiant/brushmodule.cpp +++ b/radiant/brushmodule.cpp @@ -46,7 +46,9 @@ bool getTextureLockEnabled(){ } const char* getTexdefTypeIdLabel(){ - return g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_QUAKE ? "AP" : g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ? "BP" : "220"; + return g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_QUAKE ? "AP" + : g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ? "BP" + : "220"; } const char* BrushType_getName( EBrushType type ){ @@ -82,27 +84,27 @@ typedef FreeCaller1 FaceExport void Brush_constructPreferences( PreferencesPage& page ){ page.appendCheckBox( - "", "Snap planes to integer grid", - FaceImportSnapPlanesCaller(), - FaceExportSnapPlanesCaller() - ); + "", "Snap planes to integer grid", + FaceImportSnapPlanesCaller(), + FaceExportSnapPlanesCaller() + ); page.appendEntry( - "Default texture scale", - g_texdef_default_scale - ); + "Default texture scale", + g_texdef_default_scale + ); if ( g_multipleBrushTypes ) { const char* names[] = { BrushType_getName( g_brushTypes[0] ), BrushType_getName( g_brushTypes[1] ), BrushType_getName( g_brushTypes[2] ) }; page.appendCombo( - "New map Brush Type", - g_brushType, - STRING_ARRAY_RANGE( names ) - ); + "New map Brush Type", + g_brushType, + STRING_ARRAY_RANGE( names ) + ); } // d1223m page.appendCheckBox( "", - "Always use caulk for new brushes", - g_brush_always_caulk - ); + "Always use caulk for new brushes", + g_brush_always_caulk + ); } void Brush_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Brush", "Brush Settings" ) ); @@ -133,17 +135,17 @@ void Brush_Construct( EBrushType type ){ } } GlobalPreferenceSystem().registerPreference( - "BrushType", - IntImportStringCaller( g_brushType ), - IntExportStringCaller( g_brushType ) - ); + "BrushType", + IntImportStringCaller( g_brushType ), + IntExportStringCaller( g_brushType ) + ); type = g_brushTypes[g_brushType]; } // d1223m GlobalPreferenceSystem().registerPreference( - "BrushAlwaysCaulk", - BoolImportStringCaller( g_brush_always_caulk ), - BoolExportStringCaller( g_brush_always_caulk ) ); + "BrushAlwaysCaulk", + BoolImportStringCaller( g_brush_always_caulk ), + BoolExportStringCaller( g_brush_always_caulk ) ); Brush_registerCommands(); Brush_registerPreferencesPage(); @@ -217,22 +219,22 @@ typedef Callback1 FaceCallback; class Quake3BrushCreator : public BrushCreator { public: -scene::Node& createBrush(){ - return ( new BrushNode )->node(); -} -EBrushType getFormat() const { - return Brush::m_type; -} -void toggleFormat( EBrushType type ) const { - Brush_toggleFormat( type ); -} -void Brush_forEachFace( scene::Node& brush, const BrushFaceDataCallback& callback ){ - ::Brush_forEachFace( *Node_getBrush( brush ), FaceCallback( BrushFaceDataFromFaceCaller( callback ) ) ); -} -bool Brush_addFace( scene::Node& brush, const _QERFaceData& faceData ){ - Node_getBrush( brush )->undoSave(); - return Node_getBrush( brush )->addPlane( faceData.m_p0, faceData.m_p1, faceData.m_p2, faceData.m_shader, TextureProjection( faceData.m_texdef, brushprimit_texdef_t(), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) ) ) != 0; -} + scene::Node& createBrush(){ + return ( new BrushNode )->node(); + } + EBrushType getFormat() const { + return Brush::m_type; + } + void toggleFormat( EBrushType type ) const { + Brush_toggleFormat( type ); + } + void Brush_forEachFace( scene::Node& brush, const BrushFaceDataCallback& callback ){ + ::Brush_forEachFace( *Node_getBrush( brush ), FaceCallback( BrushFaceDataFromFaceCaller( callback ) ) ); + } + bool Brush_addFace( scene::Node& brush, const _QERFaceData& faceData ){ + Node_getBrush( brush )->undoSave(); + return Node_getBrush( brush )->addPlane( faceData.m_p0, faceData.m_p1, faceData.m_p2, faceData.m_shader, TextureProjection( faceData.m_texdef, brushprimit_texdef_t(), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) ) ) != 0; + } }; Quake3BrushCreator g_Quake3BrushCreator; @@ -258,22 +260,22 @@ class BrushDependencies : class BrushDoom3API : public TypeSystemRef { -BrushCreator* m_brushdoom3; + BrushCreator* m_brushdoom3; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "doom3" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "doom3" ); -BrushDoom3API(){ - Brush_Construct( eBrushTypeDoom3 ); + BrushDoom3API(){ + Brush_Construct( eBrushTypeDoom3 ); - m_brushdoom3 = &GetBrushCreator(); -} -~BrushDoom3API(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushdoom3; -} + m_brushdoom3 = &GetBrushCreator(); + } + ~BrushDoom3API(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushdoom3; + } }; typedef SingletonModule BrushDoom3Module; @@ -283,22 +285,22 @@ StaticRegisterModule staticRegisterBrushDoom3( StaticBrushDoom3Module::instance( class BrushQuake4API : public TypeSystemRef { -BrushCreator* m_brushquake4; + BrushCreator* m_brushquake4; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "quake4" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "quake4" ); -BrushQuake4API(){ - Brush_Construct( eBrushTypeQuake4 ); + BrushQuake4API(){ + Brush_Construct( eBrushTypeQuake4 ); - m_brushquake4 = &GetBrushCreator(); -} -~BrushQuake4API(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushquake4; -} + m_brushquake4 = &GetBrushCreator(); + } + ~BrushQuake4API(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushquake4; + } }; typedef SingletonModule BrushQuake4Module; @@ -308,27 +310,27 @@ StaticRegisterModule staticRegisterBrushQuake4( StaticBrushQuake4Module::instanc class BrushQuake3API : public TypeSystemRef { -BrushCreator* m_brushquake3; + BrushCreator* m_brushquake3; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "quake3" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "quake3" ); -BrushQuake3API(){ - g_multipleBrushTypes = true; - g_brushTypes[0] = eBrushTypeQuake3; - g_brushTypes[1] = eBrushTypeQuake3BP; - g_brushTypes[2] = eBrushTypeQuake3Valve220; + BrushQuake3API(){ + g_multipleBrushTypes = true; + g_brushTypes[0] = eBrushTypeQuake3; + g_brushTypes[1] = eBrushTypeQuake3BP; + g_brushTypes[2] = eBrushTypeQuake3Valve220; - Brush_Construct( eBrushTypeQuake3BP ); + Brush_Construct( eBrushTypeQuake3BP ); - m_brushquake3 = &GetBrushCreator(); -} -~BrushQuake3API(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushquake3; -} + m_brushquake3 = &GetBrushCreator(); + } + ~BrushQuake3API(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushquake3; + } }; typedef SingletonModule BrushQuake3Module; @@ -338,27 +340,27 @@ StaticRegisterModule staticRegisterBrushQuake3( StaticBrushQuake3Module::instanc class BrushQuake2API : public TypeSystemRef { -BrushCreator* m_brushquake2; + BrushCreator* m_brushquake2; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "quake2" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "quake2" ); -BrushQuake2API(){ - g_multipleBrushTypes = true; - g_brushTypes[0] = eBrushTypeQuake2; - g_brushTypes[1] = eBrushTypeQuake3BP; - g_brushTypes[2] = eBrushTypeQuake3Valve220; + BrushQuake2API(){ + g_multipleBrushTypes = true; + g_brushTypes[0] = eBrushTypeQuake2; + g_brushTypes[1] = eBrushTypeQuake3BP; + g_brushTypes[2] = eBrushTypeQuake3Valve220; - Brush_Construct( eBrushTypeQuake2 ); + Brush_Construct( eBrushTypeQuake2 ); - m_brushquake2 = &GetBrushCreator(); -} -~BrushQuake2API(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushquake2; -} + m_brushquake2 = &GetBrushCreator(); + } + ~BrushQuake2API(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushquake2; + } }; typedef SingletonModule BrushQuake2Module; @@ -368,27 +370,27 @@ StaticRegisterModule staticRegisterBrushQuake2( StaticBrushQuake2Module::instanc class BrushQuake1API : public TypeSystemRef { -BrushCreator* m_brushquake1; + BrushCreator* m_brushquake1; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "quake" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "quake" ); -BrushQuake1API(){ - g_multipleBrushTypes = true; - g_brushTypes[0] = eBrushTypeQuake; - g_brushTypes[1] = eBrushTypeQuake3BP; - g_brushTypes[2] = eBrushTypeValve220; + BrushQuake1API(){ + g_multipleBrushTypes = true; + g_brushTypes[0] = eBrushTypeQuake; + g_brushTypes[1] = eBrushTypeQuake3BP; + g_brushTypes[2] = eBrushTypeValve220; - Brush_Construct( eBrushTypeQuake ); + Brush_Construct( eBrushTypeQuake ); - m_brushquake1 = &GetBrushCreator(); -} -~BrushQuake1API(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushquake1; -} + m_brushquake1 = &GetBrushCreator(); + } + ~BrushQuake1API(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushquake1; + } }; typedef SingletonModule BrushQuake1Module; @@ -398,22 +400,22 @@ StaticRegisterModule staticRegisterBrushQuake1( StaticBrushQuake1Module::instanc class BrushHalfLifeAPI : public TypeSystemRef { -BrushCreator* m_brushhalflife; + BrushCreator* m_brushhalflife; public: -typedef BrushCreator Type; -STRING_CONSTANT( Name, "halflife" ); + typedef BrushCreator Type; + STRING_CONSTANT( Name, "halflife" ); -BrushHalfLifeAPI(){ - Brush_Construct( eBrushTypeValve220 ); + BrushHalfLifeAPI(){ + Brush_Construct( eBrushTypeValve220 ); - m_brushhalflife = &GetBrushCreator(); -} -~BrushHalfLifeAPI(){ - Brush_Destroy(); -} -BrushCreator* getTable(){ - return m_brushhalflife; -} + m_brushhalflife = &GetBrushCreator(); + } + ~BrushHalfLifeAPI(){ + Brush_Destroy(); + } + BrushCreator* getTable(){ + return m_brushhalflife; + } }; typedef SingletonModule BrushHalfLifeModule; diff --git a/radiant/brushnode.h b/radiant/brushnode.h index ac899d9b..4efcb0d4 100644 --- a/radiant/brushnode.h +++ b/radiant/brushnode.h @@ -32,111 +32,111 @@ class BrushNode : public scene::Instantiable, public scene::Cloneable { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -Brush m_brush; -BrushTokenImporter m_mapImporter; -BrushTokenExporter m_mapExporter; -BrushXMLImporter m_xmlImporter; -BrushXMLExporter m_xmlExporter; + scene::Node m_node; + InstanceSet m_instances; + Brush m_brush; + BrushTokenImporter m_mapImporter; + BrushTokenExporter m_mapExporter; + BrushXMLImporter m_xmlImporter; + BrushXMLExporter m_xmlExporter; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Snappable& get( NullType){ - return m_brush; -} -TransformNode& get( NullType){ - return m_brush; -} -Brush& get( NullType){ - return m_brush; -} -XMLImporter& get( NullType){ - return m_xmlImporter; -} -XMLExporter& get( NullType){ - return m_xmlExporter; -} -MapImporter& get( NullType){ - return m_mapImporter; -} -MapExporter& get( NullType){ - return m_mapExporter; -} -Nameable& get( NullType){ - return m_brush; -} -BrushDoom3& get( NullType){ - return m_brush; -} + Snappable& get( NullType){ + return m_brush; + } + TransformNode& get( NullType){ + return m_brush; + } + Brush& get( NullType){ + return m_brush; + } + XMLImporter& get( NullType){ + return m_xmlImporter; + } + XMLExporter& get( NullType){ + return m_xmlExporter; + } + MapImporter& get( NullType){ + return m_mapImporter; + } + MapExporter& get( NullType){ + return m_mapExporter; + } + Nameable& get( NullType){ + return m_brush; + } + BrushDoom3& get( NullType){ + return m_brush; + } -BrushNode() : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_brush( m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), - m_mapImporter( m_brush ), - m_mapExporter( m_brush ), - m_xmlImporter( m_brush ), - m_xmlExporter( m_brush ){ -} -BrushNode( const BrushNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_brush( other.m_brush, m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), - m_mapImporter( m_brush ), - m_mapExporter( m_brush ), - m_xmlImporter( m_brush ), - m_xmlExporter( m_brush ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + BrushNode() : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_brush( m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), + m_mapImporter( m_brush ), + m_mapExporter( m_brush ), + m_xmlImporter( m_brush ), + m_xmlExporter( m_brush ){ + } + BrushNode( const BrushNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_brush( other.m_brush, m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), + m_mapImporter( m_brush ), + m_mapExporter( m_brush ), + m_xmlImporter( m_brush ), + m_xmlExporter( m_brush ){ + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Node& clone() const { - return ( new BrushNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new BrushNode( *this ) )->node(); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new BrushInstance( path, parent, m_brush ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new BrushInstance( path, parent, m_brush ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; inline Brush* Node_getBrush( scene::Node& node ){ diff --git a/radiant/brushtokens.h b/radiant/brushtokens.h index a3422cb8..9a1572c2 100644 --- a/radiant/brushtokens.h +++ b/radiant/brushtokens.h @@ -161,151 +161,151 @@ inline bool FaceShader_importTokens( FaceShader& faceShader, Tokeniser& tokenise class Doom3FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Doom3FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_Doom3_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_Doom3_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Doom3FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_Doom3_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_Doom3_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; - return true; -} + return true; + } }; class Quake4FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Quake4FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_Doom3_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_Doom3_importTokens( m_face.getShader(), tokeniser ) ); + Quake4FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_Doom3_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_Doom3_importTokens( m_face.getShader(), tokeniser ) ); - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; - return true; -} + return true; + } }; class Quake2FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Quake2FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { - m_face.getShader().m_flags.m_specified = true; - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Quake2FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { + m_face.getShader().m_flags.m_specified = true; + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } + m_face.getTexdef().m_scaleApplied = true; + return true; } - m_face.getTexdef().m_scaleApplied = true; - return true; -} }; class Quake3FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Quake3FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Quake3FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } + m_face.getTexdef().m_scaleApplied = true; + return true; } - m_face.getTexdef().m_scaleApplied = true; - return true; -} }; class Quake3BPFaceTokenImporter { -Face& m_face; + Face& m_face; public: -Quake3BPFaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Quake3BPFaceTokenImporter( Face& face ) : m_face( face ){ } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_BP_importTokens( m_face.getTexdef(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; - return true; -} + return true; + } }; class QuakeFaceTokenImporter { -Face& m_face; + Face& m_face; public: -QuakeFaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///try to load for more flexibility - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + QuakeFaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_importTokens( m_face.getTexdef(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///try to load for more flexibility + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } + m_face.getTexdef().m_scaleApplied = true; + return true; } - m_face.getTexdef().m_scaleApplied = true; - return true; -} }; class Valve220FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Valve220FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_Valve220_importTokens( m_face.getTexdef(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///try to load for more flexibility - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Valve220FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_Valve220_importTokens( m_face.getTexdef(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///try to load for more flexibility + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } + m_face.getTexdef().m_scaleApplied = true; + return true; } - m_face.getTexdef().m_scaleApplied = true; - return true; -} }; class Quake3Valve220FaceTokenImporter { -Face& m_face; + Face& m_face; public: -Quake3Valve220FaceTokenImporter( Face& face ) : m_face( face ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); - RETURN_FALSE_IF_FAIL( FaceTexdef_Valve220_importTokens( m_face.getTexdef(), tokeniser ) ); - if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility - RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + Quake3Valve220FaceTokenImporter( Face& face ) : m_face( face ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( FacePlane_importTokens( m_face.getPlane(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceShader_importTokens( m_face.getShader(), tokeniser ) ); + RETURN_FALSE_IF_FAIL( FaceTexdef_Valve220_importTokens( m_face.getTexdef(), tokeniser ) ); + if ( Tokeniser_nextTokenIsDigit( tokeniser ) ) { ///optional for more flexibility + RETURN_FALSE_IF_FAIL( FaceShader_importContentsFlagsValue( m_face.getShader(), tokeniser ) ); + } + m_face.getTexdef().m_scaleApplied = true; + return true; } - m_face.getTexdef().m_scaleApplied = true; - return true; -} }; @@ -417,317 +417,317 @@ inline void FaceShader_Doom3_exportTokens( const FaceShader& faceShader, TokenWr class Doom3FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Doom3FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_Doom3_exportTokens( m_face.getPlane(), writer ); - FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); - FaceShader_Doom3_exportTokens( m_face.getShader(), writer ); - FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); - writer.nextLine(); -} + Doom3FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_Doom3_exportTokens( m_face.getPlane(), writer ); + FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); + FaceShader_Doom3_exportTokens( m_face.getShader(), writer ); + FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + writer.nextLine(); + } }; class Quake4FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Quake4FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_Doom3_exportTokens( m_face.getPlane(), writer ); - FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); - FaceShader_Doom3_exportTokens( m_face.getShader(), writer ); - writer.nextLine(); -} + Quake4FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_Doom3_exportTokens( m_face.getPlane(), writer ); + FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); + FaceShader_Doom3_exportTokens( m_face.getShader(), writer ); + writer.nextLine(); + } }; class Quake2FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Quake2FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceTexdef_exportTokens( m_face.getTexdef(), writer ); - if ( m_face.getShader().m_flags.m_specified || m_face.isDetail() ) { - FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + Quake2FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceTexdef_exportTokens( m_face.getTexdef(), writer ); + if ( m_face.getShader().m_flags.m_specified || m_face.isDetail() ) { + FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + } + writer.nextLine(); } - writer.nextLine(); -} }; class Quake3FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Quake3FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceTexdef_exportTokens( m_face.getTexdef(), writer ); - FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); - writer.nextLine(); -} + Quake3FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceTexdef_exportTokens( m_face.getTexdef(), writer ); + FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + writer.nextLine(); + } }; class Quake3BPFaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Quake3BPFaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); - writer.nextLine(); -} + Quake3BPFaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceTexdef_BP_exportTokens( m_face.getTexdef(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + writer.nextLine(); + } }; class QuakeFaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -QuakeFaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceTexdef_exportTokens( m_face.getTexdef(), writer ); - writer.nextLine(); -} + QuakeFaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceTexdef_exportTokens( m_face.getTexdef(), writer ); + writer.nextLine(); + } }; class Valve220FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Valve220FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceTexdef_Valve220_exportTokens( m_face.getTexdef(), writer ); - writer.nextLine(); -} + Valve220FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceTexdef_Valve220_exportTokens( m_face.getTexdef(), writer ); + writer.nextLine(); + } }; class Quake3Valve220FaceTokenExporter { -const Face& m_face; + const Face& m_face; public: -Quake3Valve220FaceTokenExporter( const Face& face ) : m_face( face ){ -} -void exportTokens( TokenWriter& writer ) const { - FacePlane_exportTokens( m_face.getPlane(), writer ); - FaceShader_exportTokens( m_face.getShader(), writer ); - FaceTexdef_Valve220_exportTokens( m_face.getTexdef(), writer ); - FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); - writer.nextLine(); -} + Quake3Valve220FaceTokenExporter( const Face& face ) : m_face( face ){ + } + void exportTokens( TokenWriter& writer ) const { + FacePlane_exportTokens( m_face.getPlane(), writer ); + FaceShader_exportTokens( m_face.getShader(), writer ); + FaceTexdef_Valve220_exportTokens( m_face.getTexdef(), writer ); + FaceShader_ContentsFlagsValue_exportTokens( m_face.getShader(), writer ); + writer.nextLine(); + } }; class BrushTokenImporter : public MapImporter { -Brush& m_brush; + Brush& m_brush; public: -BrushTokenImporter( Brush& brush ) : m_brush( brush ){ -} -bool importTokens( Tokeniser& tokeniser ){ - if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "{" ) ); + BrushTokenImporter( Brush& brush ) : m_brush( brush ){ } - while ( 1 ) - { - // check for end of brush - tokeniser.nextLine(); - const char* token = tokeniser.getToken(); - if ( string_equal( token, "}" ) ) { - break; + bool importTokens( Tokeniser& tokeniser ){ + if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "{" ) ); + } + while ( 1 ) + { + // check for end of brush + tokeniser.nextLine(); + const char* token = tokeniser.getToken(); + if ( string_equal( token, "}" ) ) { + break; + } + + tokeniser.ungetToken(); + + m_brush.push_back( FaceSmartPointer( new Face( &m_brush ) ) ); + + //!todo BP support + tokeniser.nextLine(); + + Face& face = *m_brush.back(); + + switch ( Brush::m_type ) + { + case eBrushTypeDoom3: + { + Doom3FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake4: + { + Quake4FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake2: + { + Quake2FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake3: + { + Quake3FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake3BP: + { + Quake3BPFaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake: + { + QuakeFaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeValve220: + { + Valve220FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + case eBrushTypeQuake3Valve220: + { + Quake3Valve220FaceTokenImporter importer( face ); + RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); + } + break; + } + face.planeChanged(); + } + if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "}" ) ); } - tokeniser.ungetToken(); + m_brush.planeChanged(); + m_brush.shaderChanged(); - m_brush.push_back( FaceSmartPointer( new Face( &m_brush ) ) ); - - //!todo BP support - tokeniser.nextLine(); - - Face& face = *m_brush.back(); - - switch ( Brush::m_type ) - { - case eBrushTypeDoom3: - { - Doom3FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake4: - { - Quake4FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake2: - { - Quake2FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake3: - { - Quake3FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake3BP: - { - Quake3BPFaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake: - { - QuakeFaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeValve220: - { - Valve220FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - case eBrushTypeQuake3Valve220: - { - Quake3Valve220FaceTokenImporter importer( face ); - RETURN_FALSE_IF_FAIL( importer.importTokens( tokeniser ) ); - } - break; - } - face.planeChanged(); + return true; } - if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "}" ) ); - } - - m_brush.planeChanged(); - m_brush.shaderChanged(); - - return true; -} }; class BrushTokenExporter : public MapExporter { -const Brush& m_brush; + const Brush& m_brush; public: -BrushTokenExporter( const Brush& brush ) : m_brush( brush ){ -} -void exportTokens( TokenWriter& writer ) const { - m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. - - if ( !m_brush.hasContributingFaces() ) { - return; + BrushTokenExporter( const Brush& brush ) : m_brush( brush ){ } + void exportTokens( TokenWriter& writer ) const { + m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. - writer.writeToken( "{" ); - writer.nextLine(); + if ( !m_brush.hasContributingFaces() ) { + return; + } - if ( Brush::m_type == eBrushTypeQuake3BP ) { - writer.writeToken( "brushDef" ); - writer.nextLine(); writer.writeToken( "{" ); writer.nextLine(); - } - else if ( Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { - writer.writeToken( "brushDef3" ); - writer.nextLine(); - writer.writeToken( "{" ); - writer.nextLine(); - } - for ( Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i ) - { - const Face& face = *( *i ); + if ( Brush::m_type == eBrushTypeQuake3BP ) { + writer.writeToken( "brushDef" ); + writer.nextLine(); + writer.writeToken( "{" ); + writer.nextLine(); + } + else if ( Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { + writer.writeToken( "brushDef3" ); + writer.nextLine(); + writer.writeToken( "{" ); + writer.nextLine(); + } - if ( face.contributes() ) { - switch ( Brush::m_type ) - { - case eBrushTypeDoom3: - { - Doom3FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake4: - { - Quake4FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake2: - { - Quake2FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake3: - { - Quake3FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake3BP: - { - Quake3BPFaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake: - { - QuakeFaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeValve220: - { - Valve220FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; - case eBrushTypeQuake3Valve220: - { - Quake3Valve220FaceTokenExporter exporter( face ); - exporter.exportTokens( writer ); - } - break; + for ( Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i ) + { + const Face& face = *( *i ); + + if ( face.contributes() ) { + switch ( Brush::m_type ) + { + case eBrushTypeDoom3: + { + Doom3FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake4: + { + Quake4FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake2: + { + Quake2FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake3: + { + Quake3FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake3BP: + { + Quake3BPFaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake: + { + QuakeFaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeValve220: + { + Valve220FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + case eBrushTypeQuake3Valve220: + { + Quake3Valve220FaceTokenExporter exporter( face ); + exporter.exportTokens( writer ); + } + break; + } } } - } - if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { + if ( Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4 ) { + writer.writeToken( "}" ); + writer.nextLine(); + } + writer.writeToken( "}" ); writer.nextLine(); } - - writer.writeToken( "}" ); - writer.nextLine(); -} }; diff --git a/radiant/brushxml.h b/radiant/brushxml.h index c1fac55b..742314a5 100644 --- a/radiant/brushxml.h +++ b/radiant/brushxml.h @@ -65,109 +65,109 @@ inline void FacePlane_importXML( FacePlane& facePlane, const char* xmlContent ){ class FaceXMLImporter { -struct xml_state_t -{ - enum EState + struct xml_state_t { - eDefault, - ePlanePts, - eTexdef, - eBPMatrix, - eFlags, - eShader, + enum EState + { + eDefault, + ePlanePts, + eTexdef, + eBPMatrix, + eFlags, + eShader, + }; + + EState m_state; + StringOutputStream m_content; + + xml_state_t( EState state ) + : m_state( state ) + {} + + EState state() const { + return m_state; + } + const char* content() const { + return m_content.c_str(); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_content.write( buffer, length ); + } }; - EState m_state; - StringOutputStream m_content; - - xml_state_t( EState state ) - : m_state( state ) - {} - - EState state() const { - return m_state; - } - const char* content() const { - return m_content.c_str(); - } - std::size_t write( const char* buffer, std::size_t length ){ - return m_content.write( buffer, length ); - } -}; - -std::vector m_xml_state; -Face& m_face; + std::vector m_xml_state; + Face& m_face; public: -FaceXMLImporter( Face& face ) : m_face( face ){ - m_xml_state.push_back( xml_state_t::eDefault ); -} -~FaceXMLImporter(){ - m_face.planeChanged(); -} - -void pushElement( const XMLElement& element ){ - ASSERT_MESSAGE( m_xml_state.back().state() == xml_state_t::eDefault, "parse error" ); - - if ( strcmp( element.name(), "planepts" ) == 0 ) { - m_xml_state.push_back( xml_state_t::ePlanePts ); + FaceXMLImporter( Face& face ) : m_face( face ){ + m_xml_state.push_back( xml_state_t::eDefault ); } - else if ( strcmp( element.name(), "texdef" ) == 0 ) { - m_xml_state.push_back( xml_state_t::eTexdef ); - } - else if ( strcmp( element.name(), "bpmatrix" ) == 0 ) { - m_xml_state.push_back( xml_state_t::eBPMatrix ); - } - else if ( strcmp( element.name(), "flags" ) == 0 ) { - m_xml_state.push_back( xml_state_t::eFlags ); - } - else if ( strcmp( element.name(), "shader" ) == 0 ) { - m_xml_state.push_back( xml_state_t::eShader ); - } -} -void popElement( const char* name ){ - ASSERT_MESSAGE( m_xml_state.back().state() != xml_state_t::eDefault, "parse error" ); - - switch ( m_xml_state.back().state() ) - { - case xml_state_t::ePlanePts: - { - FacePlane_importXML( m_face.getPlane(), m_xml_state.back().content() ); - } - break; - case xml_state_t::eTexdef: - { - FaceTexdef_importXML( m_face.getTexdef(), m_xml_state.back().content() ); - } - break; - case xml_state_t::eBPMatrix: - { - FaceTexdef_BP_importXML( m_face.getTexdef(), m_xml_state.back().content() ); - } - break; - case xml_state_t::eFlags: - { - StringTokeniser content( m_xml_state.back().content() ); - - m_face.getShader().m_flags.m_contentFlags = atoi( content.getToken() ); - m_face.getShader().m_flags.m_surfaceFlags = atoi( content.getToken() ); - m_face.getShader().m_flags.m_value = atoi( content.getToken() ); - } - break; - case xml_state_t::eShader: - { - m_face.getShader().setShader( m_xml_state.back().content() ); - } - break; - default: - break; + ~FaceXMLImporter(){ + m_face.planeChanged(); } - m_xml_state.pop_back(); -} -std::size_t write( const char* data, std::size_t length ){ - ASSERT_MESSAGE( !m_xml_state.empty(), "parse error" ); - return m_xml_state.back().write( data, length ); -} + void pushElement( const XMLElement& element ){ + ASSERT_MESSAGE( m_xml_state.back().state() == xml_state_t::eDefault, "parse error" ); + + if ( strcmp( element.name(), "planepts" ) == 0 ) { + m_xml_state.push_back( xml_state_t::ePlanePts ); + } + else if ( strcmp( element.name(), "texdef" ) == 0 ) { + m_xml_state.push_back( xml_state_t::eTexdef ); + } + else if ( strcmp( element.name(), "bpmatrix" ) == 0 ) { + m_xml_state.push_back( xml_state_t::eBPMatrix ); + } + else if ( strcmp( element.name(), "flags" ) == 0 ) { + m_xml_state.push_back( xml_state_t::eFlags ); + } + else if ( strcmp( element.name(), "shader" ) == 0 ) { + m_xml_state.push_back( xml_state_t::eShader ); + } + } + void popElement( const char* name ){ + ASSERT_MESSAGE( m_xml_state.back().state() != xml_state_t::eDefault, "parse error" ); + + switch ( m_xml_state.back().state() ) + { + case xml_state_t::ePlanePts: + { + FacePlane_importXML( m_face.getPlane(), m_xml_state.back().content() ); + } + break; + case xml_state_t::eTexdef: + { + FaceTexdef_importXML( m_face.getTexdef(), m_xml_state.back().content() ); + } + break; + case xml_state_t::eBPMatrix: + { + FaceTexdef_BP_importXML( m_face.getTexdef(), m_xml_state.back().content() ); + } + break; + case xml_state_t::eFlags: + { + StringTokeniser content( m_xml_state.back().content() ); + + m_face.getShader().m_flags.m_contentFlags = atoi( content.getToken() ); + m_face.getShader().m_flags.m_surfaceFlags = atoi( content.getToken() ); + m_face.getShader().m_flags.m_value = atoi( content.getToken() ); + } + break; + case xml_state_t::eShader: + { + m_face.getShader().setShader( m_xml_state.back().content() ); + } + break; + default: + break; + } + + m_xml_state.pop_back(); + } + std::size_t write( const char* data, std::size_t length ){ + ASSERT_MESSAGE( !m_xml_state.empty(), "parse error" ); + return m_xml_state.back().write( data, length ); + } }; @@ -178,10 +178,10 @@ inline void FaceTexdef_exportXML( const FaceTexdef& texdef, XMLImporter& importe ASSERT_MESSAGE( texdef_sane( texdef.m_projection.m_texdef ), "FaceTexdef_exportXML: bad texdef" ); importer << texdef.m_projection.m_texdef.shift[0] - << ' ' << texdef.m_projection.m_texdef.shift[1] - << ' ' << texdef.m_projection.m_texdef.rotate - << ' ' << texdef.m_projection.m_texdef.scale[0] - << ' ' << texdef.m_projection.m_texdef.scale[1]; + << ' ' << texdef.m_projection.m_texdef.shift[1] + << ' ' << texdef.m_projection.m_texdef.rotate + << ' ' << texdef.m_projection.m_texdef.scale[0] + << ' ' << texdef.m_projection.m_texdef.scale[1]; importer.popElement( element.name() ); } @@ -205,8 +205,8 @@ inline void FaceShader_ContentsFlagsValue_exportXML( const FaceShader& faceShade { importer << faceShader.m_flags.m_contentFlags - << ' ' << faceShader.m_flags.m_surfaceFlags - << ' ' << faceShader.m_flags.m_value; + << ' ' << faceShader.m_flags.m_surfaceFlags + << ' ' << faceShader.m_flags.m_value; } importer.popElement( element.name() ); @@ -274,149 +274,149 @@ inline void FacePolygon_exportXML( const Winding& w, const BasicVector3& class FaceXMLExporter { -const Face& m_face; + const Face& m_face; public: -FaceXMLExporter( const Face& face ) : m_face( face ){ -} -void exportXML( XMLImporter& importer ){ - bool bAlternateTexdef = ( Face::m_type == eBrushTypeQuake3BP || Face::m_type == eBrushTypeDoom3 || Face::m_type == eBrushTypeQuake4 ); - - // write shader - { - StaticElement element( "shader" ); - importer.pushElement( element ); - importer << m_face.getShader().getShader(); - importer.popElement( element.name() ); + FaceXMLExporter( const Face& face ) : m_face( face ){ } + void exportXML( XMLImporter& importer ){ + bool bAlternateTexdef = ( Face::m_type == eBrushTypeQuake3BP || Face::m_type == eBrushTypeDoom3 || Face::m_type == eBrushTypeQuake4 ); - FacePolygon_exportXML( m_face.getWinding(), m_face.getPlane().plane3().normal(), importer ); - FacePlane_exportXML( m_face.getPlane(), importer ); + // write shader + { + StaticElement element( "shader" ); + importer.pushElement( element ); + importer << m_face.getShader().getShader(); + importer.popElement( element.name() ); + } - if ( !bAlternateTexdef ) { - FaceTexdef_exportXML( m_face.getTexdef(), importer ); + FacePolygon_exportXML( m_face.getWinding(), m_face.getPlane().plane3().normal(), importer ); + FacePlane_exportXML( m_face.getPlane(), importer ); + + if ( !bAlternateTexdef ) { + FaceTexdef_exportXML( m_face.getTexdef(), importer ); + } + else + { + FaceTexdef_BP_exportXML( m_face.getTexdef(), importer ); + } + + FaceShader_ContentsFlagsValue_exportXML( m_face.getShader(), importer ); } - else - { - FaceTexdef_BP_exportXML( m_face.getTexdef(), importer ); - } - - FaceShader_ContentsFlagsValue_exportXML( m_face.getShader(), importer ); -} }; class BrushXMLImporter : public XMLImporter { -class xml_state_t -{ -public: -enum EState -{ - eDefault, - eBrush, - eFace, -}; + class xml_state_t + { + public: + enum EState + { + eDefault, + eBrush, + eFace, + }; -private: -EState m_state; + private: + EState m_state; + + public: + xml_state_t( EState state ) + : m_state( state ){ + } + EState state() const { + return m_state; + } + }; + + std::vector m_xml_state; + char m_faceImporter[sizeof( FaceXMLImporter )]; + Brush& m_brush; + + FaceXMLImporter& faceImporter(){ + return *reinterpret_cast( m_faceImporter ); + } public: -xml_state_t( EState state ) - : m_state( state ){ -} -EState state() const { - return m_state; -} -}; - -std::vector m_xml_state; -char m_faceImporter[sizeof( FaceXMLImporter )]; -Brush& m_brush; - -FaceXMLImporter& faceImporter(){ - return *reinterpret_cast( m_faceImporter ); -} - -public: -BrushXMLImporter( Brush& brush ) : m_brush( brush ){ - m_xml_state.push_back( xml_state_t::eDefault ); -} -void pushElement( const XMLElement& element ){ - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eDefault: - ASSERT_MESSAGE( strcmp( element.name(), "brush" ) == 0, "parse error" ); - m_xml_state.push_back( xml_state_t::eBrush ); - break; - case xml_state_t::eBrush: - ASSERT_MESSAGE( strcmp( element.name(), "plane" ) == 0, "parse error" ); - m_xml_state.push_back( xml_state_t::eFace ); - m_brush.push_back( FaceSmartPointer( new Face( &m_brush ) ) ); - constructor( faceImporter(), makeReference( *m_brush.back() ) ); - m_brush.planeChanged(); - m_brush.shaderChanged(); - break; - case xml_state_t::eFace: - m_xml_state.push_back( xml_state_t::eFace ); - faceImporter().pushElement( element ); - break; + BrushXMLImporter( Brush& brush ) : m_brush( brush ){ + m_xml_state.push_back( xml_state_t::eDefault ); } -} -void popElement( const char* name ){ - ASSERT_MESSAGE( !m_xml_state.empty(), "parse error" ); - m_xml_state.pop_back(); + void pushElement( const XMLElement& element ){ + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eDefault: + ASSERT_MESSAGE( strcmp( element.name(), "brush" ) == 0, "parse error" ); + m_xml_state.push_back( xml_state_t::eBrush ); + break; + case xml_state_t::eBrush: + ASSERT_MESSAGE( strcmp( element.name(), "plane" ) == 0, "parse error" ); + m_xml_state.push_back( xml_state_t::eFace ); + m_brush.push_back( FaceSmartPointer( new Face( &m_brush ) ) ); + constructor( faceImporter(), makeReference( *m_brush.back() ) ); + m_brush.planeChanged(); + m_brush.shaderChanged(); + break; + case xml_state_t::eFace: + m_xml_state.push_back( xml_state_t::eFace ); + faceImporter().pushElement( element ); + break; + } + } + void popElement( const char* name ){ + ASSERT_MESSAGE( !m_xml_state.empty(), "parse error" ); + m_xml_state.pop_back(); - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eDefault: - break; - case xml_state_t::eBrush: - destructor( faceImporter() ); - break; - case xml_state_t::eFace: - faceImporter().popElement( name ); - break; + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eDefault: + break; + case xml_state_t::eBrush: + destructor( faceImporter() ); + break; + case xml_state_t::eFace: + faceImporter().popElement( name ); + break; + } } -} -std::size_t write( const char* data, std::size_t length ){ - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eFace: - return faceImporter().write( data, length ); - break; - default: - break; + std::size_t write( const char* data, std::size_t length ){ + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eFace: + return faceImporter().write( data, length ); + break; + default: + break; + } + return length; } - return length; -} }; class BrushXMLExporter : public XMLExporter { -const Brush& m_brush; + const Brush& m_brush; public: -BrushXMLExporter( const Brush& brush ) : m_brush( brush ){ -} -void exportXML( XMLImporter& importer ){ - m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. - ASSERT_MESSAGE( m_brush.hasContributingFaces(), "exporting an empty brush" ); - - const StaticElement brushElement( "brush" ); - importer.pushElement( brushElement ); - - for ( Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i ) - { - if ( ( *i )->contributes() ) { - const StaticElement element( "plane" ); - importer.pushElement( element ); - FaceXMLExporter( *( *i ) ).exportXML( importer ); - importer.popElement( element.name() ); - } + BrushXMLExporter( const Brush& brush ) : m_brush( brush ){ } + void exportXML( XMLImporter& importer ){ + m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. + ASSERT_MESSAGE( m_brush.hasContributingFaces(), "exporting an empty brush" ); - importer.popElement( brushElement.name() ); -} + const StaticElement brushElement( "brush" ); + importer.pushElement( brushElement ); + + for ( Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i ) + { + if ( ( *i )->contributes() ) { + const StaticElement element( "plane" ); + importer.pushElement( element ); + FaceXMLExporter( *( *i ) ).exportXML( importer ); + importer.popElement( element.name() ); + } + } + + importer.popElement( brushElement.name() ); + } }; diff --git a/radiant/build.cpp b/radiant/build.cpp index 869e8d18..83f72e1e 100644 --- a/radiant/build.cpp +++ b/radiant/build.cpp @@ -55,116 +55,116 @@ const char* build_get_variable( const char* name ){ class Evaluatable { public: -virtual ~Evaluatable(){} -virtual void evaluate( StringBuffer& output ) = 0; -virtual void exportXML( XMLImporter& importer ) = 0; + virtual ~Evaluatable(){} + virtual void evaluate( StringBuffer& output ) = 0; + virtual void exportXML( XMLImporter& importer ) = 0; }; class VariableString : public Evaluatable { -CopiedString m_string; + CopiedString m_string; public: -VariableString() : m_string(){ -} -VariableString( const char* string ) : m_string( string ){ -} -const char* c_str() const { - return m_string.c_str(); -} -void setString( const char* string ){ - m_string = string; -} -void evaluate( StringBuffer& output ){ - StringBuffer variable; - bool in_variable = false; - for ( const char* i = m_string.c_str(); *i != '\0'; ++i ) - { - if ( !in_variable ) { - switch ( *i ) - { - case '[': - in_variable = true; - break; - default: - output.push_back( *i ); - break; - } - } - else + VariableString() : m_string(){ + } + VariableString( const char* string ) : m_string( string ){ + } + const char* c_str() const { + return m_string.c_str(); + } + void setString( const char* string ){ + m_string = string; + } + void evaluate( StringBuffer& output ){ + StringBuffer variable; + bool in_variable = false; + for ( const char* i = m_string.c_str(); *i != '\0'; ++i ) { - switch ( *i ) + if ( !in_variable ) { + switch ( *i ) + { + case '[': + in_variable = true; + break; + default: + output.push_back( *i ); + break; + } + } + else { - case ']': - in_variable = false; - output.push_string( build_get_variable( variable.c_str() ) ); - variable.clear(); - break; - default: - variable.push_back( *i ); - break; + switch ( *i ) + { + case ']': + in_variable = false; + output.push_string( build_get_variable( variable.c_str() ) ); + variable.clear(); + break; + default: + variable.push_back( *i ); + break; + } } } } -} -void exportXML( XMLImporter& importer ){ - importer << c_str(); -} + void exportXML( XMLImporter& importer ){ + importer << c_str(); + } }; class Conditional : public Evaluatable { -VariableString* m_test; + VariableString* m_test; public: -Evaluatable* m_result; -Conditional( VariableString* test ) : m_test( test ){ -} -~Conditional(){ - delete m_test; - delete m_result; -} -void evaluate( StringBuffer& output ){ - StringBuffer buffer; - m_test->evaluate( buffer ); - if ( !string_empty( buffer.c_str() ) ) { - m_result->evaluate( output ); + Evaluatable* m_result; + Conditional( VariableString* test ) : m_test( test ){ + } + ~Conditional(){ + delete m_test; + delete m_result; + } + void evaluate( StringBuffer& output ){ + StringBuffer buffer; + m_test->evaluate( buffer ); + if ( !string_empty( buffer.c_str() ) ) { + m_result->evaluate( output ); + } + } + void exportXML( XMLImporter& importer ){ + StaticElement conditionElement( "cond" ); + conditionElement.insertAttribute( "value", m_test->c_str() ); + importer.pushElement( conditionElement ); + m_result->exportXML( importer ); + importer.popElement( conditionElement.name() ); } -} -void exportXML( XMLImporter& importer ){ - StaticElement conditionElement( "cond" ); - conditionElement.insertAttribute( "value", m_test->c_str() ); - importer.pushElement( conditionElement ); - m_result->exportXML( importer ); - importer.popElement( conditionElement.name() ); -} }; typedef std::vector Evaluatables; class Tool : public Evaluatable { -Evaluatables m_evaluatables; + Evaluatables m_evaluatables; public: -~Tool(){ - for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) - { - delete ( *i ); + ~Tool(){ + for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) + { + delete ( *i ); + } } -} -void push_back( Evaluatable* evaluatable ){ - m_evaluatables.push_back( evaluatable ); -} -void evaluate( StringBuffer& output ){ - for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) - { - ( *i )->evaluate( output ); + void push_back( Evaluatable* evaluatable ){ + m_evaluatables.push_back( evaluatable ); } -} -void exportXML( XMLImporter& importer ){ - for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) - { - ( *i )->exportXML( importer ); + void evaluate( StringBuffer& output ){ + for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) + { + ( *i )->evaluate( output ); + } + } + void exportXML( XMLImporter& importer ){ + for ( Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i ) + { + ( *i )->exportXML( importer ); + } } -} }; #include "xml/ixml.h" @@ -172,95 +172,95 @@ void exportXML( XMLImporter& importer ){ class XMLElementParser : public TextOutputStream { public: -virtual XMLElementParser& pushElement( const XMLElement& element ) = 0; -virtual void popElement( const char* name ) = 0; + virtual XMLElementParser& pushElement( const XMLElement& element ) = 0; + virtual void popElement( const char* name ) = 0; }; class VariableStringXMLConstructor final : public XMLElementParser { -StringBuffer m_buffer; -VariableString& m_variableString; + StringBuffer m_buffer; + VariableString& m_variableString; public: -VariableStringXMLConstructor( VariableString& variableString ) : m_variableString( variableString ){ -} -~VariableStringXMLConstructor(){ - m_variableString.setString( m_buffer.c_str() ); -} -std::size_t write( const char* buffer, std::size_t length ){ - m_buffer.push_range( buffer, buffer + length ); - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); - return *this; -} -void popElement( const char* name ){ -} + VariableStringXMLConstructor( VariableString& variableString ) : m_variableString( variableString ){ + } + ~VariableStringXMLConstructor(){ + m_variableString.setString( m_buffer.c_str() ); + } + std::size_t write( const char* buffer, std::size_t length ){ + m_buffer.push_range( buffer, buffer + length ); + return length; + } + XMLElementParser& pushElement( const XMLElement& element ){ + ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); + return *this; + } + void popElement( const char* name ){ + } }; class ConditionalXMLConstructor final : public XMLElementParser { -StringBuffer m_buffer; -Conditional& m_conditional; + StringBuffer m_buffer; + Conditional& m_conditional; public: -ConditionalXMLConstructor( Conditional& conditional ) : m_conditional( conditional ){ -} -~ConditionalXMLConstructor(){ - m_conditional.m_result = new VariableString( m_buffer.c_str() ); -} -std::size_t write( const char* buffer, std::size_t length ){ - m_buffer.push_range( buffer, buffer + length ); - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); - return *this; -} -void popElement( const char* name ){ -} + ConditionalXMLConstructor( Conditional& conditional ) : m_conditional( conditional ){ + } + ~ConditionalXMLConstructor(){ + m_conditional.m_result = new VariableString( m_buffer.c_str() ); + } + std::size_t write( const char* buffer, std::size_t length ){ + m_buffer.push_range( buffer, buffer + length ); + return length; + } + XMLElementParser& pushElement( const XMLElement& element ){ + ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); + return *this; + } + void popElement( const char* name ){ + } }; class ToolXMLConstructor final : public XMLElementParser { -StringBuffer m_buffer; -Tool& m_tool; -ConditionalXMLConstructor* m_conditional; + StringBuffer m_buffer; + Tool& m_tool; + ConditionalXMLConstructor* m_conditional; public: -ToolXMLConstructor( Tool& tool ) : m_tool( tool ){ -} -~ToolXMLConstructor(){ - flush(); -} -std::size_t write( const char* buffer, std::size_t length ){ - m_buffer.push_range( buffer, buffer + length ); - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), "cond" ) ) { + ToolXMLConstructor( Tool& tool ) : m_tool( tool ){ + } + ~ToolXMLConstructor(){ flush(); - Conditional* conditional = new Conditional( new VariableString( element.attribute( "value" ) ) ); - m_tool.push_back( conditional ); - m_conditional = new ConditionalXMLConstructor( *conditional ); - return *m_conditional; } - else - { - ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); - return *this; + std::size_t write( const char* buffer, std::size_t length ){ + m_buffer.push_range( buffer, buffer + length ); + return length; } -} -void popElement( const char* name ){ - if ( string_equal( name, "cond" ) ) { - delete m_conditional; + XMLElementParser& pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), "cond" ) ) { + flush(); + Conditional* conditional = new Conditional( new VariableString( element.attribute( "value" ) ) ); + m_tool.push_back( conditional ); + m_conditional = new ConditionalXMLConstructor( *conditional ); + return *m_conditional; + } + else + { + ERROR_MESSAGE( "parse error: invalid element \"" << element.name() << "\"" ); + return *this; + } + } + void popElement( const char* name ){ + if ( string_equal( name, "cond" ) ) { + delete m_conditional; + } } -} -void flush(){ - if ( !m_buffer.empty() ) { - m_tool.push_back( new VariableString( m_buffer.c_str() ) ); - m_buffer.clear(); + void flush(){ + if ( !m_buffer.empty() ) { + m_tool.push_back( new VariableString( m_buffer.c_str() ) ); + m_buffer.clear(); + } } -} }; typedef VariableString BuildCommand; @@ -268,29 +268,29 @@ typedef std::list Build; class BuildXMLConstructor final : public XMLElementParser { -VariableStringXMLConstructor* m_variableString; -Build& m_build; + VariableStringXMLConstructor* m_variableString; + Build& m_build; public: -BuildXMLConstructor( Build& build ) : m_build( build ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), "command" ) ) { - m_build.push_back( BuildCommand() ); - m_variableString = new VariableStringXMLConstructor( m_build.back() ); - return *m_variableString; + BuildXMLConstructor( Build& build ) : m_build( build ){ } - else - { - ERROR_MESSAGE( "parse error: invalid element" ); - return *this; + std::size_t write( const char* buffer, std::size_t length ){ + return length; + } + XMLElementParser& pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), "command" ) ) { + m_build.push_back( BuildCommand() ); + m_variableString = new VariableStringXMLConstructor( m_build.back() ); + return *m_variableString; + } + else + { + ERROR_MESSAGE( "parse error: invalid element" ); + return *this; + } + } + void popElement( const char* name ){ + delete m_variableString; } -} -void popElement( const char* name ){ - delete m_variableString; -} }; typedef std::pair BuildPair; @@ -311,13 +311,13 @@ static bool is_separator( const BuildPair &p ){ class BuildPairEqual { -const char* m_name; + const char* m_name; public: -BuildPairEqual( const char* name ) : m_name( name ){ -} -bool operator()( const BuildPair& self ) const { - return string_equal( self.first.c_str(), m_name ); -} + BuildPairEqual( const char* name ) : m_name( name ){ + } + bool operator()( const BuildPair& self ) const { + return string_equal( self.first.c_str(), m_name ); + } }; typedef std::list Project; @@ -354,101 +354,101 @@ typedef std::map Tools; class ProjectXMLConstructor : public XMLElementParser { -ToolXMLConstructor* m_tool; -BuildXMLConstructor* m_build; -Project& m_project; -Tools& m_tools; + ToolXMLConstructor* m_tool; + BuildXMLConstructor* m_build; + Project& m_project; + Tools& m_tools; public: -ProjectXMLConstructor( Project& project, Tools& tools ) : m_project( project ), m_tools( tools ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), "var" ) ) { - Tools::iterator i = m_tools.insert( Tools::value_type( element.attribute( "name" ), Tool() ) ).first; - m_tool = new ToolXMLConstructor( ( *i ).second ); - return *m_tool; + ProjectXMLConstructor( Project& project, Tools& tools ) : m_project( project ), m_tools( tools ){ } - else if ( string_equal( element.name(), "build" ) ) { - m_project.push_back( Project::value_type( element.attribute( "name" ), Build() ) ); - m_build = new BuildXMLConstructor( m_project.back().second ); - return *m_build; + std::size_t write( const char* buffer, std::size_t length ){ + return length; } - else if ( string_equal( element.name(), "separator" ) ) { - m_project.push_back( Project::value_type( SEPARATOR_STRING, Build() ) ); - return *this; + XMLElementParser& pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), "var" ) ) { + Tools::iterator i = m_tools.insert( Tools::value_type( element.attribute( "name" ), Tool() ) ).first; + m_tool = new ToolXMLConstructor( ( *i ).second ); + return *m_tool; + } + else if ( string_equal( element.name(), "build" ) ) { + m_project.push_back( Project::value_type( element.attribute( "name" ), Build() ) ); + m_build = new BuildXMLConstructor( m_project.back().second ); + return *m_build; + } + else if ( string_equal( element.name(), "separator" ) ) { + m_project.push_back( Project::value_type( SEPARATOR_STRING, Build() ) ); + return *this; + } + else + { + ERROR_MESSAGE( "parse error: invalid element" ); + return *this; + } } - else - { - ERROR_MESSAGE( "parse error: invalid element" ); - return *this; + void popElement( const char* name ){ + if ( string_equal( name, "var" ) ) { + delete m_tool; + } + else if ( string_equal( name, "build" ) ) { + delete m_build; + } } -} -void popElement( const char* name ){ - if ( string_equal( name, "var" ) ) { - delete m_tool; - } - else if ( string_equal( name, "build" ) ) { - delete m_build; - } -} }; class SkipAllParser : public XMLElementParser { public: -std::size_t write( const char* buffer, std::size_t length ){ - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - return *this; -} -void popElement( const char* name ){ -} + std::size_t write( const char* buffer, std::size_t length ){ + return length; + } + XMLElementParser& pushElement( const XMLElement& element ){ + return *this; + } + void popElement( const char* name ){ + } }; class RootXMLConstructor : public XMLElementParser { -CopiedString m_elementName; -XMLElementParser& m_parser; -SkipAllParser m_skip; -Version m_version; -bool m_compatible; + CopiedString m_elementName; + XMLElementParser& m_parser; + SkipAllParser m_skip; + Version m_version; + bool m_compatible; public: -RootXMLConstructor( const char* elementName, XMLElementParser& parser, const char* version ) : - m_elementName( elementName ), - m_parser( parser ), - m_version( version_parse( version ) ), - m_compatible( false ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - return length; -} -XMLElementParser& pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), m_elementName.c_str() ) ) { - Version dataVersion( version_parse( element.attribute( "version" ) ) ); - if ( version_compatible( m_version, dataVersion ) ) { - m_compatible = true; - return m_parser; + RootXMLConstructor( const char* elementName, XMLElementParser& parser, const char* version ) : + m_elementName( elementName ), + m_parser( parser ), + m_version( version_parse( version ) ), + m_compatible( false ){ + } + std::size_t write( const char* buffer, std::size_t length ){ + return length; + } + XMLElementParser& pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), m_elementName.c_str() ) ) { + Version dataVersion( version_parse( element.attribute( "version" ) ) ); + if ( version_compatible( m_version, dataVersion ) ) { + m_compatible = true; + return m_parser; + } + else + { + return m_skip; + } } else { - return m_skip; + //ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); + return *this; } } - else - { - //ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); - return *this; + void popElement( const char* name ){ } -} -void popElement( const char* name ){ -} -bool versionCompatible() const { - return m_compatible; -} + bool versionCompatible() const { + return m_compatible; + } }; namespace @@ -510,21 +510,21 @@ typedef std::vector XMLElementStack; class XMLParser : public XMLImporter { -XMLElementStack m_stack; + XMLElementStack m_stack; public: -XMLParser( XMLElementParser& parser ){ - m_stack.push_back( &parser ); -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_stack.back()->write( buffer, length ); -} -void pushElement( const XMLElement& element ){ - m_stack.push_back( &m_stack.back()->pushElement( element ) ); -} -void popElement( const char* name ){ - m_stack.pop_back(); - m_stack.back()->popElement( name ); -} + XMLParser( XMLElementParser& parser ){ + m_stack.push_back( &parser ); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_stack.back()->write( buffer, length ); + } + void pushElement( const XMLElement& element ){ + m_stack.push_back( &m_stack.back()->pushElement( element ) ); + } + void popElement( const char* name ){ + m_stack.pop_back(); + m_stack.back()->popElement( name ); + } }; #include "stream/textfilestream.h" @@ -558,66 +558,66 @@ void build_commands_clear(){ class BuildXMLExporter { -Build& m_build; + Build& m_build; public: -BuildXMLExporter( Build& build ) : m_build( build ){ -} -void exportXML( XMLImporter& importer ){ - importer << "\n"; - for ( Build::iterator i = m_build.begin(); i != m_build.end(); ++i ) - { - StaticElement commandElement( "command" ); - importer.pushElement( commandElement ); - ( *i ).exportXML( importer ); - importer.popElement( commandElement.name() ); - importer << "\n"; + BuildXMLExporter( Build& build ) : m_build( build ){ + } + void exportXML( XMLImporter& importer ){ + importer << "\n"; + for ( Build::iterator i = m_build.begin(); i != m_build.end(); ++i ) + { + StaticElement commandElement( "command" ); + importer.pushElement( commandElement ); + ( *i ).exportXML( importer ); + importer.popElement( commandElement.name() ); + importer << "\n"; + } } -} }; class ProjectXMLExporter { -Project& m_project; -Tools& m_tools; + Project& m_project; + Tools& m_tools; public: -ProjectXMLExporter( Project& project, Tools& tools ) : m_project( project ), m_tools( tools ){ -} -void exportXML( XMLImporter& importer ){ - StaticElement projectElement( "project" ); - projectElement.insertAttribute( "version", BUILDMENU_VERSION ); - importer.pushElement( projectElement ); - importer << "\n"; - - for ( Tools::iterator i = m_tools.begin(); i != m_tools.end(); ++i ) - { - StaticElement toolElement( "var" ); - toolElement.insertAttribute( "name", ( *i ).first.c_str() ); - importer.pushElement( toolElement ); - ( *i ).second.exportXML( importer ); - importer.popElement( toolElement.name() ); + ProjectXMLExporter( Project& project, Tools& tools ) : m_project( project ), m_tools( tools ){ + } + void exportXML( XMLImporter& importer ){ + StaticElement projectElement( "project" ); + projectElement.insertAttribute( "version", BUILDMENU_VERSION ); + importer.pushElement( projectElement ); importer << "\n"; - } - for ( Project::iterator i = m_project.begin(); i != m_project.end(); ++i ) - { - if ( is_separator( *i ) ) { - StaticElement buildElement( "separator" ); - importer.pushElement( buildElement ); - importer.popElement( buildElement.name() ); - importer << "\n"; - } - else + + for ( Tools::iterator i = m_tools.begin(); i != m_tools.end(); ++i ) { - StaticElement buildElement( "build" ); - buildElement.insertAttribute( "name", ( *i ).first.c_str() ); - importer.pushElement( buildElement ); - BuildXMLExporter buildExporter( ( *i ).second ); - buildExporter.exportXML( importer ); - importer.popElement( buildElement.name() ); + StaticElement toolElement( "var" ); + toolElement.insertAttribute( "name", ( *i ).first.c_str() ); + importer.pushElement( toolElement ); + ( *i ).second.exportXML( importer ); + importer.popElement( toolElement.name() ); importer << "\n"; } + for ( Project::iterator i = m_project.begin(); i != m_project.end(); ++i ) + { + if ( is_separator( *i ) ) { + StaticElement buildElement( "separator" ); + importer.pushElement( buildElement ); + importer.popElement( buildElement.name() ); + importer << "\n"; + } + else + { + StaticElement buildElement( "build" ); + buildElement.insertAttribute( "name", ( *i ).first.c_str() ); + importer.pushElement( buildElement ); + BuildXMLExporter buildExporter( ( *i ).second ); + buildExporter.exportXML( importer ); + importer.popElement( buildElement.name() ); + importer << "\n"; + } + } + importer.popElement( projectElement.name() ); } - importer.popElement( projectElement.name() ); -} }; #include "xml/xmlwriter.h" @@ -678,12 +678,12 @@ static void project_cell_editing_started( GtkCellRenderer* cell, GtkCellEditable class ProjectList { public: -Project& m_project; -GtkListStore* m_store; -GtkWidget* m_buildView; -bool m_changed; -ProjectList( Project& project ) : m_project( project ), m_changed( false ){ -} + Project& m_project; + GtkListStore* m_store; + GtkWidget* m_buildView; + bool m_changed; + ProjectList( Project& project ) : m_project( project ), m_changed( false ){ + } }; gboolean project_cell_edited( GtkCellRendererText* cell, gchar* path_string, gchar* new_text, ProjectList* projectList ){ @@ -735,11 +735,11 @@ inline bool event_is_del( const GdkEventKey* event ){ } inline bool event_is_copy( const GdkEventKey* event ){ return ( accelerator_for_event_key( event ) == Accelerator( 'C', GDK_CONTROL_MASK ) ) - || ( accelerator_for_event_key( event ) == Accelerator( GDK_KEY_Insert, GDK_CONTROL_MASK ) ); + || ( accelerator_for_event_key( event ) == Accelerator( GDK_KEY_Insert, GDK_CONTROL_MASK ) ); } inline bool event_is_paste( const GdkEventKey* event ){ return ( accelerator_for_event_key( event ) == Accelerator( 'V', GDK_CONTROL_MASK ) ) - || ( accelerator_for_event_key( event ) == Accelerator( GDK_KEY_Insert, GDK_SHIFT_MASK ) ); + || ( accelerator_for_event_key( event ) == Accelerator( GDK_KEY_Insert, GDK_SHIFT_MASK ) ); } gboolean project_key_press( GtkWidget* widget, GdkEventKey* event, ProjectList* projectList ){ @@ -904,8 +904,8 @@ GtkWindow* BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectLi { GtkVBox* vbox = create_dialog_vbox( 4 ); gtk_table_attach( table1, GTK_WIDGET( vbox ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); { GtkButton* button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &modal ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 ); @@ -923,8 +923,8 @@ GtkWindow* BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectLi { GtkFrame* frame = create_dialog_frame( "Build menu" ); gtk_table_attach( table1, GTK_WIDGET( frame ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); { GtkScrolledWindow* scr = create_scrolled_window( GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4 ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( scr ) ); @@ -962,8 +962,8 @@ GtkWindow* BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectLi { GtkFrame* frame = create_dialog_frame( "Commandline" ); gtk_table_attach( table1, GTK_WIDGET( frame ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); { GtkScrolledWindow* scr = create_scrolled_window( GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4 ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( scr ) ); @@ -1004,8 +1004,8 @@ GtkWindow* BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectLi GtkWidget* expander = gtk_expander_new_with_mnemonic( "build variables" ); gtk_widget_show( expander ); gtk_table_attach( table1, expander, 0, 2, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); bsp_init(); for ( Tools::iterator i = g_build_tools.begin(); i != g_build_tools.end(); ++i ){ @@ -1081,17 +1081,17 @@ CopiedString g_lastExecutedBuild; class BuildMenuItem { -const char* m_name; + const char* m_name; public: -GtkMenuItem* m_item; -BuildMenuItem( const char* name, GtkMenuItem* item ) - : m_name( name ), m_item( item ){ -} -void run(){ - g_lastExecutedBuild = m_name; - RunBSP( m_name ); -} -typedef MemberCaller RunCaller; + GtkMenuItem* m_item; + BuildMenuItem( const char* name, GtkMenuItem* item ) + : m_name( name ), m_item( item ){ + } + void run(){ + g_lastExecutedBuild = m_name; + RunBSP( m_name ); + } + typedef MemberCaller RunCaller; }; typedef std::list BuildMenuItems; diff --git a/radiant/build.h b/radiant/build.h index 39024fad..55d94e71 100644 --- a/radiant/build.h +++ b/radiant/build.h @@ -27,7 +27,7 @@ void build_clear_variables(); class CommandListener { public: -virtual void execute( const char* command ) = 0; + virtual void execute( const char* command ) = 0; }; void build_run( const char* name, CommandListener& listener ); diff --git a/radiant/camwindow.cpp b/radiant/camwindow.cpp index cceef1ee..cd7471bf 100644 --- a/radiant/camwindow.cpp +++ b/radiant/camwindow.cpp @@ -196,8 +196,8 @@ struct camera_t static camera_draw_mode draw_mode; - camera_t( View* view, const Callback& update, const Callback1& update_motion_freemove ) - : width( 0 ), + camera_t( View* view, const Callback& update, const Callback1& update_motion_freemove ) : + width( 0 ), height( 0 ), timing( false ), origin( 0, 0, 0 ), @@ -227,17 +227,19 @@ inline Matrix4 projection_for_camera( float near_z, float far_z, float fieldOfVi std::swap( half_width, half_height ); return matrix4_frustum( - -half_width, - half_width, - -half_height, - half_height, - near_z, - far_z - ); + -half_width, + half_width, + -half_height, + half_height, + near_z, + far_z + ); } float Camera_getFarClipPlane( camera_t& camera ){ - return ( g_camwindow_globals_private.m_bCubicClipping ) ? pow( 2.0, ( g_camwindow_globals.m_nCubicScale + 7 ) / 2.0 ) : ( ( g_MaxWorldCoord - g_MinWorldCoord ) * sqrt( 3 ) ); + return ( g_camwindow_globals_private.m_bCubicClipping ) + ? pow( 2.0, ( g_camwindow_globals.m_nCubicScale + 7 ) / 2.0 ) + : ( ( g_MaxWorldCoord - g_MinWorldCoord ) * sqrt( 3 ) ); } void Camera_updateProjection( camera_t& camera ){ @@ -354,10 +356,10 @@ void Camera_FreeMove( camera_t& camera, int dx, int dy ){ if( camera.m_orbit ){ #if 0 const Vector3 radangles( euler_degrees_to_radians( camera.angles ) ); - const Vector3 viewdir( cos( radangles[1] ) * cos( radangles[0] ), - sin( radangles[1] ) * cos( radangles[0] ), - sin( radangles[0] ) - ); + const Vector3 viewdir( cos( radangles[1] ) * cos( radangles[0] ), + sin( radangles[1] ) * cos( radangles[0] ), + sin( radangles[0] ) + ); const float len = vector3_length( camera.origin - camera.m_orbit_center ); camera.origin = camera.m_orbit_center - viewdir * len; #else @@ -463,9 +465,9 @@ void Cam_KeyControl( camera_t& camera, float dtime ){ } else{ /* accelerate */ camera.m_keymove_speed_current = std::min( camera.m_keymove_speed_current - + g_camwindow_globals_private.m_nMoveSpeed * dtime - / g_camwindow_globals_private.m_time_toMaxSpeed * static_cast( msec_per_sec ), - static_cast( g_camwindow_globals_private.m_nMoveSpeed ) ); + + g_camwindow_globals_private.m_nMoveSpeed * dtime + / g_camwindow_globals_private.m_time_toMaxSpeed * static_cast( msec_per_sec ), + static_cast( g_camwindow_globals_private.m_nMoveSpeed ) ); } const float dpos = dtime * camera.m_keymove_speed_current; // Update position @@ -686,28 +688,28 @@ void Camera_PitchDown_Discrete( camera_t& camera ){ class RadiantCameraView : public CameraView { -camera_t& m_camera; -View* m_view; -Callback m_update; + camera_t& m_camera; + View* m_view; + Callback m_update; public: -RadiantCameraView( camera_t& camera, View* view, const Callback& update ) : m_camera( camera ), m_view( view ), m_update( update ){ -} -void update(){ - m_view->Construct( m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height ); - m_update(); -} -void setModelview( const Matrix4& modelview ){ - m_camera.modelview = modelview; - matrix4_multiply_by_matrix4( m_camera.modelview, g_radiant2opengl ); - matrix4_affine_invert( m_camera.modelview ); - Camera_updateVectors( m_camera ); - update(); -} -void setFieldOfView( float fieldOfView ){ - float farClip = Camera_getFarClipPlane( m_camera ); - m_camera.projection = projection_for_camera( camera_t::near_z, farClip, fieldOfView, m_camera.width, m_camera.height ); - update(); -} + RadiantCameraView( camera_t& camera, View* view, const Callback& update ) : m_camera( camera ), m_view( view ), m_update( update ){ + } + void update(){ + m_view->Construct( m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height ); + m_update(); + } + void setModelview( const Matrix4& modelview ){ + m_camera.modelview = modelview; + matrix4_multiply_by_matrix4( m_camera.modelview, g_radiant2opengl ); + matrix4_affine_invert( m_camera.modelview ); + Camera_updateVectors( m_camera ); + update(); + } + void setFieldOfView( float fieldOfView ){ + float farClip = Camera_getFarClipPlane( m_camera ); + m_camera.projection = projection_for_camera( camera_t::near_z, farClip, fieldOfView, m_camera.width, m_camera.height ); + update(); + } }; @@ -766,9 +768,9 @@ public: renderer.SetState( shader, Renderer::eFullMaterials ); Vector4 points[3] = { Vector4( bounds.origin - g_vector3_axes[1] * bounds.extents - g_vector3_axes[2] * bounds.extents, 1 ), - Vector4( bounds.origin - g_vector3_axes[0] * bounds.extents - g_vector3_axes[2] * bounds.extents, 1 ), - Vector4( bounds.origin - g_vector3_axes[0] * bounds.extents - g_vector3_axes[1] * bounds.extents, 1 ), - }; + Vector4( bounds.origin - g_vector3_axes[0] * bounds.extents - g_vector3_axes[2] * bounds.extents, 1 ), + Vector4( bounds.origin - g_vector3_axes[0] * bounds.extents - g_vector3_axes[1] * bounds.extents, 1 ), + }; for( std::size_t i = 0; i < 3; ++i ){ matrix4_transform_vector4( view.GetViewMatrix(), points[i] ); points[i].x() /= points[i].w(); @@ -818,107 +820,107 @@ class RenderableCamWorkzone : public OpenGLRenderable mutable Array m_colorarr0[3]; mutable Array m_colorarr1[3]; public: -void render( RenderStateFlags state ) const { - glEnableClientState( GL_EDGE_FLAG_ARRAY ); + void render( RenderStateFlags state ) const { + glEnableClientState( GL_EDGE_FLAG_ARRAY ); - const AABB bounds = GlobalSelectionSystem().getBoundsSelected(); + const AABB bounds = GlobalSelectionSystem().getBoundsSelected(); - for( std::size_t i = 0; i < 3; ++i ){ - const std::size_t i2 = ( i + 1 ) % 3; - const std::size_t i3 = ( i + 2 ) % 3; -// const Vector3 normal = g_vector3_axes[i]; - const float offset = 1024; - std::vector points; - points.reserve( 4 ); - points.push_back( bounds.origin + g_vector3_axes[i2] * bounds.extents + g_vector3_axes[i3] * bounds.extents ); - if( bounds.extents[i2] != 0 ){ - points.push_back( bounds.origin - g_vector3_axes[i2] * bounds.extents + g_vector3_axes[i3] * bounds.extents ); - } - if( bounds.extents[i3] != 0 ){ - points.push_back( bounds.origin + g_vector3_axes[i2] * bounds.extents - g_vector3_axes[i3] * bounds.extents ); + for( std::size_t i = 0; i < 3; ++i ){ + const std::size_t i2 = ( i + 1 ) % 3; + const std::size_t i3 = ( i + 2 ) % 3; +// const Vector3 normal = g_vector3_axes[i]; + const float offset = 1024; + std::vector points; + points.reserve( 4 ); + points.push_back( bounds.origin + g_vector3_axes[i2] * bounds.extents + g_vector3_axes[i3] * bounds.extents ); if( bounds.extents[i2] != 0 ){ - points.push_back( bounds.origin - g_vector3_axes[i2] * bounds.extents - g_vector3_axes[i3] * bounds.extents ); + points.push_back( bounds.origin - g_vector3_axes[i2] * bounds.extents + g_vector3_axes[i3] * bounds.extents ); + } + if( bounds.extents[i3] != 0 ){ + points.push_back( bounds.origin + g_vector3_axes[i2] * bounds.extents - g_vector3_axes[i3] * bounds.extents ); + if( bounds.extents[i2] != 0 ){ + points.push_back( bounds.origin - g_vector3_axes[i2] * bounds.extents - g_vector3_axes[i3] * bounds.extents ); + } } - } - const float grid = GetGridSize(); - const std::size_t approx_count = ( std::max( 0.f, bounds.extents[i] ) + offset ) * 4 / grid + 8; + const float grid = GetGridSize(); + const std::size_t approx_count = ( std::max( 0.f, bounds.extents[i] ) + offset ) * 4 / grid + 8; - Array& verticesarr( m_verticesarr[i] ); - Array& edgearr( m_edgearr[i] ); - Array& colorarr0( m_colorarr0[i] ); - Array& colorarr1( m_colorarr1[i] ); - if( verticesarr.size() < approx_count ){ - verticesarr.resize( approx_count ); - edgearr.resize( approx_count ); - colorarr0.resize( approx_count ); - colorarr1.resize( approx_count ); - } + Array& verticesarr( m_verticesarr[i] ); + Array& edgearr( m_edgearr[i] ); + Array& colorarr0( m_colorarr0[i] ); + Array& colorarr1( m_colorarr1[i] ); + if( verticesarr.size() < approx_count ){ + verticesarr.resize( approx_count ); + edgearr.resize( approx_count ); + colorarr0.resize( approx_count ); + colorarr1.resize( approx_count ); + } - float coord = float_snapped( bounds.origin[i] - std::max( 0.f, bounds.extents[i] ) - offset, grid ); + float coord = float_snapped( bounds.origin[i] - std::max( 0.f, bounds.extents[i] ) - offset, grid ); // const float coord_end = float_snapped( bounds.origin[i] + std::max( 0.f, bounds.extents[i] ) + offset, grid ) + 0.1f; - const bool start0 = float_snapped( coord, grid * 2 ) == coord; - std::size_t count = 0; + const bool start0 = float_snapped( coord, grid * 2 ) == coord; + std::size_t count = 0; - for( ; count < approx_count - 4; count += 4 ){ - verticesarr[count][i] = - verticesarr[count + 1][i] = coord; - const float alpha = std::max( 0.f, std::min( 1.f, ( offset + bounds.extents[i] - std::fabs( coord - bounds.origin[i] ) ) / offset ) ); - colorarr0[count] = colorarr0[count + 1] = Colour4b( 255, 0, 0, alpha * 255 ); - colorarr1[count] = colorarr1[count + 1] = Colour4b( 255, 255, 255, alpha * 255 ); - coord += grid; - verticesarr[count + 2][i] = - verticesarr[count + 3][i] = coord; - const float alpha2 = std::max( 0.f, std::min( 1.f, ( offset + bounds.extents[i] - std::fabs( coord - bounds.origin[i] ) ) / offset ) ); - colorarr0[count + 2] = colorarr0[count + 3] = Colour4b( 255, 0, 0, alpha2 * 255 ); - colorarr1[count + 2] = colorarr1[count + 3] = Colour4b( 255, 255, 255, alpha2 * 255 ); - coord += grid; - edgearr[count] = - edgearr[count + 2] = GL_FALSE; - edgearr[count + 1] = - edgearr[count + 3] = GL_TRUE; - } + for( ; count < approx_count - 4; count += 4 ){ + verticesarr[count][i] = + verticesarr[count + 1][i] = coord; + const float alpha = std::max( 0.f, std::min( 1.f, ( offset + bounds.extents[i] - std::fabs( coord - bounds.origin[i] ) ) / offset ) ); + colorarr0[count] = colorarr0[count + 1] = Colour4b( 255, 0, 0, alpha * 255 ); + colorarr1[count] = colorarr1[count + 1] = Colour4b( 255, 255, 255, alpha * 255 ); + coord += grid; + verticesarr[count + 2][i] = + verticesarr[count + 3][i] = coord; + const float alpha2 = std::max( 0.f, std::min( 1.f, ( offset + bounds.extents[i] - std::fabs( coord - bounds.origin[i] ) ) / offset ) ); + colorarr0[count + 2] = colorarr0[count + 3] = Colour4b( 255, 0, 0, alpha2 * 255 ); + colorarr1[count + 2] = colorarr1[count + 3] = Colour4b( 255, 255, 255, alpha2 * 255 ); + coord += grid; + edgearr[count] = + edgearr[count + 2] = GL_FALSE; + edgearr[count + 1] = + edgearr[count + 3] = GL_TRUE; + } - if( points.size() == 1 ){ - points.push_back( points[0] + g_vector3_axes[i2] * 8 ); - for( std::size_t k = 0; k < count; k += 4 ){ - edgearr[k + 1] = GL_FALSE; + if( points.size() == 1 ){ + points.push_back( points[0] + g_vector3_axes[i2] * 8 ); + for( std::size_t k = 0; k < count; k += 4 ){ + edgearr[k + 1] = GL_FALSE; + } + } + + glVertexPointer( 3, GL_FLOAT, sizeof( Vector3 ), verticesarr.data()->data() ); + glEdgeFlagPointer( sizeof( GLboolean ), edgearr.data() ); + for( std::vector::const_iterator j = points.begin(); j != points.end(); ++++j ){ + const std::vector::const_iterator jj = j + 1; + for( std::size_t k = 0; k < count; k += 4 ){ + verticesarr[k][i2] = ( *j )[i2]; + verticesarr[k][i3] = ( *j )[i3]; + verticesarr[k + 1][i2] = ( *jj )[i2]; + verticesarr[k + 1][i3] = ( *jj )[i3]; + verticesarr[k + 2][i2] = ( *jj )[i2]; + verticesarr[k + 2][i3] = ( *jj )[i3]; + verticesarr[k + 3][i2] = ( *j )[i2]; + verticesarr[k + 3][i3] = ( *j )[i3]; + } + + glPolygonOffset( -2, 2 ); + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Colour4b ), colorarr0.data() ); + glDrawArrays( GL_QUADS, start0? 0 : 2, GLsizei( count - ( start0? 4 : 2 ) ) ); + + glPolygonOffset( 1, -1 ); + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Colour4b ), colorarr1.data() ); + glDrawArrays( GL_QUADS, start0? 2 : 0, GLsizei( count - ( start0? 2 : 4 ) ) ); + glPolygonOffset( -1, 1 ); // restore default } } - glVertexPointer( 3, GL_FLOAT, sizeof( Vector3 ), verticesarr.data()->data() ); - glEdgeFlagPointer( sizeof( GLboolean ), edgearr.data() ); - for( std::vector::const_iterator j = points.begin(); j != points.end(); ++++j ){ - const std::vector::const_iterator jj = j + 1; - for( std::size_t k = 0; k < count; k += 4 ){ - verticesarr[k][i2] = ( *j )[i2]; - verticesarr[k][i3] = ( *j )[i3]; - verticesarr[k + 1][i2] = ( *jj )[i2]; - verticesarr[k + 1][i3] = ( *jj )[i3]; - verticesarr[k + 2][i2] = ( *jj )[i2]; - verticesarr[k + 2][i3] = ( *jj )[i3]; - verticesarr[k + 3][i2] = ( *j )[i2]; - verticesarr[k + 3][i3] = ( *j )[i3]; - } - - glPolygonOffset( -2, 2 ); - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Colour4b ), colorarr0.data() ); - glDrawArrays( GL_QUADS, start0? 0 : 2, GLsizei( count - ( start0? 4 : 2 ) ) ); - - glPolygonOffset( 1, -1 ); - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Colour4b ), colorarr1.data() ); - glDrawArrays( GL_QUADS, start0? 2 : 0, GLsizei( count - ( start0? 2 : 4 ) ) ); - glPolygonOffset( -1, 1 ); // restore default - } + glDisableClientState( GL_EDGE_FLAG_ARRAY ); } - glDisableClientState( GL_EDGE_FLAG_ARRAY ); -} - -void render( Renderer& renderer, Shader* shader ) const { - renderer.SetState( shader, Renderer::eFullMaterials ); - renderer.addRenderable( *this, g_matrix4_identity ); -} + void render( Renderer& renderer, Shader* shader ) const { + renderer.SetState( shader, Renderer::eFullMaterials ); + renderer.addRenderable( *this, g_matrix4_identity ); + } }; @@ -927,108 +929,108 @@ void render( Renderer& renderer, Shader* shader ) const { class CamWnd { -View m_view; -camera_t m_Camera; -RadiantCameraView m_cameraview; + View m_view; + camera_t m_Camera; + RadiantCameraView m_cameraview; #if 0 -int m_PositionDragCursorX; -int m_PositionDragCursorY; + int m_PositionDragCursorX; + int m_PositionDragCursorY; #endif -guint m_freemove_handle_focusout; + guint m_freemove_handle_focusout; -static Shader* m_state_select0; -static Shader* m_state_select1; -static Shader* m_state_wire; -static Shader* m_state_facewire; -static Shader* m_state_workzone; -static Shader* m_state_text; + static Shader* m_state_select0; + static Shader* m_state_select1; + static Shader* m_state_wire; + static Shader* m_state_facewire; + static Shader* m_state_workzone; + static Shader* m_state_text; -FreezePointer m_freezePointer; + FreezePointer m_freezePointer; -CamDrawSize m_draw_size; -RenderableCamWorkzone m_draw_workzone; + CamDrawSize m_draw_size; + RenderableCamWorkzone m_draw_workzone; public: -FBO* m_fbo; -FBO* fbo_get(){ - return m_fbo = m_fbo? m_fbo : GlobalOpenGL().support_ARB_framebuffer_object? new FBO : new FBO_fallback; -} -GtkWidget* m_gl_widget; -GtkWindow* m_parent; - -SelectionSystemWindowObserver* m_window_observer; -XORRectangle m_XORRectangle; - -DeferredDraw m_deferredDraw; -DeferredMotion m_deferred_motion; - -guint m_selection_button_press_handler; -guint m_selection_button_release_handler; -guint m_selection_motion_handler; - -guint m_freelook_button_press_handler; -guint m_freelook_button_release_handler; - -guint m_sizeHandler; -guint m_exposeHandler; - -Timer m_render_time; - -CamWnd(); -~CamWnd(); - -bool m_drawing; -void queue_draw(){ - //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress"); - if ( m_drawing ) { - return; + FBO* m_fbo; + FBO* fbo_get(){ + return m_fbo = m_fbo? m_fbo : GlobalOpenGL().support_ARB_framebuffer_object? new FBO : new FBO_fallback; } - //globalOutputStream() << "queue... "; - m_deferredDraw.draw(); -} -void draw(); + GtkWidget* m_gl_widget; + GtkWindow* m_parent; -static void captureStates(){ - m_state_text = GlobalShaderCache().capture( "$TEXT" ); - m_state_workzone = GlobalShaderCache().capture( "$CAM_WORKZONE" ); - m_state_facewire = GlobalShaderCache().capture( "$CAM_FACEWIRE" ); - m_state_wire = GlobalShaderCache().capture( "$CAM_WIRE" ); - m_state_select0 = GlobalShaderCache().capture( "$CAM_OVERLAY" ); - m_state_select1 = GlobalShaderCache().capture( "$CAM_HIGHLIGHT" ); -} -static void releaseStates(){ - GlobalShaderCache().release( "$CAM_HIGHLIGHT" ); - GlobalShaderCache().release( "$CAM_OVERLAY" ); - GlobalShaderCache().release( "$CAM_WIRE" ); - GlobalShaderCache().release( "$CAM_FACEWIRE" ); - GlobalShaderCache().release( "$CAM_WORKZONE" ); - GlobalShaderCache().release( "$TEXT" ); -} + SelectionSystemWindowObserver* m_window_observer; + XORRectangle m_XORRectangle; -camera_t& getCamera(){ - return m_Camera; -} + DeferredDraw m_deferredDraw; + DeferredMotion m_deferred_motion; -void BenchMark(); -void Cam_ChangeFloor( bool up ); + guint m_selection_button_press_handler; + guint m_selection_button_release_handler; + guint m_selection_motion_handler; -void DisableFreeMove(); -void EnableFreeMove(); -bool m_bFreeMove; -bool m_bFreeMove_entering; + guint m_freelook_button_press_handler; + guint m_freelook_button_release_handler; -CameraView& getCameraView(){ - return m_cameraview; -} + guint m_sizeHandler; + guint m_exposeHandler; -Timer m_rightClickTimer; -float m_rightClickMove; + Timer m_render_time; -void selection_motion_freemove( const MotionDeltaValues& delta ); + CamWnd(); + ~CamWnd(); + + bool m_drawing; + void queue_draw(){ + //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress"); + if ( m_drawing ) { + return; + } + //globalOutputStream() << "queue... "; + m_deferredDraw.draw(); + } + void draw(); + + static void captureStates(){ + m_state_text = GlobalShaderCache().capture( "$TEXT" ); + m_state_workzone = GlobalShaderCache().capture( "$CAM_WORKZONE" ); + m_state_facewire = GlobalShaderCache().capture( "$CAM_FACEWIRE" ); + m_state_wire = GlobalShaderCache().capture( "$CAM_WIRE" ); + m_state_select0 = GlobalShaderCache().capture( "$CAM_OVERLAY" ); + m_state_select1 = GlobalShaderCache().capture( "$CAM_HIGHLIGHT" ); + } + static void releaseStates(){ + GlobalShaderCache().release( "$CAM_HIGHLIGHT" ); + GlobalShaderCache().release( "$CAM_OVERLAY" ); + GlobalShaderCache().release( "$CAM_WIRE" ); + GlobalShaderCache().release( "$CAM_FACEWIRE" ); + GlobalShaderCache().release( "$CAM_WORKZONE" ); + GlobalShaderCache().release( "$TEXT" ); + } + + camera_t& getCamera(){ + return m_Camera; + } + + void BenchMark(); + void Cam_ChangeFloor( bool up ); + + void DisableFreeMove(); + void EnableFreeMove(); + bool m_bFreeMove; + bool m_bFreeMove_entering; + + CameraView& getCameraView(){ + return m_cameraview; + } + + Timer m_rightClickTimer; + float m_rightClickMove; + + void selection_motion_freemove( const MotionDeltaValues& delta ); private: -void Cam_Draw(); + void Cam_Draw(); }; typedef MemberCaller CamWndQueueDraw; @@ -1428,93 +1430,93 @@ void KeyEvent_disconnect( const char* name ){ void CamWnd_registerCommands( CamWnd& camwnd ){ GlobalKeyEvents_insert( "CameraForward", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraBack", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraLeft", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraRight", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraStrafeRight", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraStrafeLeft", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraUp", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraDown", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraAngleUp", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraAngleDown", accelerator_null(), - ReferenceCaller( camwnd.getCamera() ), - ReferenceCaller( camwnd.getCamera() ) - ); + ReferenceCaller( camwnd.getCamera() ), + ReferenceCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveForward", accelerator_null(), - FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveBack", accelerator_null(), - FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveLeft", accelerator_null(), - FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveRight", accelerator_null(), - FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveForward2", accelerator_null(), - FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveBack2", accelerator_null(), - FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveLeft2", accelerator_null(), - FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveRight2", accelerator_null(), - FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveUp", accelerator_null(), - FreeMoveCameraMoveUpKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveUpKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveUpKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveUpKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeMoveDown", accelerator_null(), - FreeMoveCameraMoveDownKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraMoveDownKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraMoveDownKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraMoveDownKeyUpCaller( camwnd.getCamera() ) + ); GlobalKeyEvents_insert( "CameraFreeFocus", accelerator_null(), - FreeMoveCameraFocusKeyDownCaller( camwnd.getCamera() ), - FreeMoveCameraFocusKeyUpCaller( camwnd.getCamera() ) - ); + FreeMoveCameraFocusKeyDownCaller( camwnd.getCamera() ), + FreeMoveCameraFocusKeyUpCaller( camwnd.getCamera() ) + ); GlobalCommands_insert( "CameraForward", ReferenceCaller( camwnd.getCamera() ) ); GlobalCommands_insert( "CameraBack", ReferenceCaller( camwnd.getCamera() ) ); @@ -1755,35 +1757,35 @@ CamWnd::~CamWnd(){ class FloorHeightWalker : public scene::Graph::Walker { -Vector3 m_current; + Vector3 m_current; public: -mutable float m_bestUp; -mutable float m_bestDown; -mutable float m_bottom; -FloorHeightWalker( const Vector3& current ) : - m_current( current ), m_bestUp( g_MaxWorldCoord ), m_bestDown( g_MinWorldCoord ), m_bottom( g_MaxWorldCoord ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( !path.top().get().visible() ) - return false; - if ( !path.top().get().isRoot() && !node_is_group( path.top() ) ) { - const AABB& aabb = instance.worldAABB(); - if( instance.isSelected() || ( m_current.x() > aabb.origin.x() - aabb.extents.x() - && m_current.x() < aabb.origin.x() + aabb.extents.x() - && m_current.y() > aabb.origin.y() - aabb.extents.y() - && m_current.y() < aabb.origin.y() + aabb.extents.y() ) ){ - const float floorHeight = aabb.origin.z() + aabb.extents.z() + 32.f; - if ( floorHeight > m_current.z() + 0.1f && floorHeight < m_bestUp ) /* 0.1f epsilon to prevent jam at (close?) coords */ - m_bestUp = floorHeight; - if ( floorHeight < m_current.z() - 0.1f && floorHeight > m_bestDown ) - m_bestDown = floorHeight; - const float bottom = aabb.origin.z() - aabb.extents.z() - 16.f; - if( m_bottom > bottom ) - m_bottom = bottom; - } + mutable float m_bestUp; + mutable float m_bestDown; + mutable float m_bottom; + FloorHeightWalker( const Vector3& current ) : + m_current( current ), m_bestUp( g_MaxWorldCoord ), m_bestDown( g_MinWorldCoord ), m_bottom( g_MaxWorldCoord ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( !path.top().get().visible() ) + return false; + if ( !path.top().get().isRoot() && !node_is_group( path.top() ) ) { + const AABB& aabb = instance.worldAABB(); + if( instance.isSelected() || ( m_current.x() > aabb.origin.x() - aabb.extents.x() + && m_current.x() < aabb.origin.x() + aabb.extents.x() + && m_current.y() > aabb.origin.y() - aabb.extents.y() + && m_current.y() < aabb.origin.y() + aabb.extents.y() ) ){ + const float floorHeight = aabb.origin.z() + aabb.extents.z() + 32.f; + if ( floorHeight > m_current.z() + 0.1f && floorHeight < m_bestUp ) /* 0.1f epsilon to prevent jam at (close?) coords */ + m_bestUp = floorHeight; + if ( floorHeight < m_current.z() - 0.1f && floorHeight > m_bestDown ) + m_bestDown = floorHeight; + const float bottom = aabb.origin.z() - aabb.extents.z() - 16.f; + if( m_bottom > bottom ) + m_bottom = bottom; + } + } + return true; } - return true; -} }; void CamWnd::Cam_ChangeFloor( bool up ){ @@ -1820,7 +1822,7 @@ Sys_GetCursorPos( &m_PositionDragCursorX, &m_PositionDragCursorY ); // motion if ( ( m_bFreeMove && ( buttons == ( RAD_CONTROL | RAD_SHIFT ) ) ) - || ( !m_bFreeMove && ( buttons == ( RAD_RBUTTON | RAD_CONTROL ) ) ) ) { + || ( !m_bFreeMove && ( buttons == ( RAD_RBUTTON | RAD_CONTROL ) ) ) ) { Cam_PositionDrag(); CamWnd_Update( camwnd ); CameraMovedNotify(); @@ -1891,80 +1893,80 @@ void CamWnd::DisableFreeMove(){ class CamRenderer : public Renderer { -struct state_type -{ - state_type() : m_highlight( 0 ), m_state( 0 ), m_lights( 0 ){ - } - unsigned int m_highlight; - Shader* m_state; - const LightList* m_lights; -}; + struct state_type + { + state_type() : m_highlight( 0 ), m_state( 0 ), m_lights( 0 ){ + } + unsigned int m_highlight; + Shader* m_state; + const LightList* m_lights; + }; -std::vector m_state_stack; -RenderStateFlags m_globalstate; -Shader* m_state_facewire; -Shader* m_state_wire; -Shader* m_state_select0; -Shader* m_state_select1; -const Vector3& m_viewer; + std::vector m_state_stack; + RenderStateFlags m_globalstate; + Shader* m_state_facewire; + Shader* m_state_wire; + Shader* m_state_select0; + Shader* m_state_select1; + const Vector3& m_viewer; public: -CamRenderer( RenderStateFlags globalstate, Shader* facewire, Shader* wire, Shader* select0, Shader* select1, const Vector3& viewer ) : - m_globalstate( globalstate ), - m_state_facewire( facewire ), - m_state_wire( wire ), - m_state_select0( select0 ), - m_state_select1( select1 ), - m_viewer( viewer ){ - ASSERT_NOTNULL( select0 ); -// ASSERT_NOTNULL( select1 ); - m_state_stack.push_back( state_type() ); -} - -void SetState( Shader* state, EStyle style ){ - ASSERT_NOTNULL( state ); - if ( style == eFullMaterials ) { - m_state_stack.back().m_state = state; - } -} -EStyle getStyle() const { - return eFullMaterials; -} -void PushState(){ - m_state_stack.push_back( m_state_stack.back() ); -} -void PopState(){ - ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); - m_state_stack.pop_back(); -} -void Highlight( EHighlightMode mode, bool bEnable = true ){ - ( bEnable ) - ? m_state_stack.back().m_highlight |= mode - : m_state_stack.back().m_highlight &= ~mode; -} -void setLights( const LightList& lights ){ - m_state_stack.back().m_lights = &lights; -} -void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ){ - if ( m_state_stack.back().m_highlight & ePrimitive ) { - m_state_select0->addRenderable( renderable, world, m_state_stack.back().m_lights ); - } - else if ( m_state_wire && m_state_stack.back().m_highlight & ePrimitiveWire ) { - m_state_wire->addRenderable( renderable, world, m_state_stack.back().m_lights ); - } - if ( m_state_select1 && m_state_stack.back().m_highlight & eFace ) { - m_state_select1->addRenderable( renderable, world, m_state_stack.back().m_lights ); - } - if ( m_state_facewire && m_state_stack.back().m_highlight & eFaceWire ) { - m_state_facewire->addRenderable( renderable, world, m_state_stack.back().m_lights ); + CamRenderer( RenderStateFlags globalstate, Shader* facewire, Shader* wire, Shader* select0, Shader* select1, const Vector3& viewer ) : + m_globalstate( globalstate ), + m_state_facewire( facewire ), + m_state_wire( wire ), + m_state_select0( select0 ), + m_state_select1( select1 ), + m_viewer( viewer ){ + ASSERT_NOTNULL( select0 ); + // ASSERT_NOTNULL( select1 ); + m_state_stack.push_back( state_type() ); } - m_state_stack.back().m_state->addRenderable( renderable, world, m_state_stack.back().m_lights ); -} + void SetState( Shader* state, EStyle style ){ + ASSERT_NOTNULL( state ); + if ( style == eFullMaterials ) { + m_state_stack.back().m_state = state; + } + } + EStyle getStyle() const { + return eFullMaterials; + } + void PushState(){ + m_state_stack.push_back( m_state_stack.back() ); + } + void PopState(){ + ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); + m_state_stack.pop_back(); + } + void Highlight( EHighlightMode mode, bool bEnable = true ){ + ( bEnable ) + ? m_state_stack.back().m_highlight |= mode + : m_state_stack.back().m_highlight &= ~mode; + } + void setLights( const LightList& lights ){ + m_state_stack.back().m_lights = &lights; + } + void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ){ + if ( m_state_stack.back().m_highlight & ePrimitive ) { + m_state_select0->addRenderable( renderable, world, m_state_stack.back().m_lights ); + } + else if ( m_state_wire && m_state_stack.back().m_highlight & ePrimitiveWire ) { + m_state_wire->addRenderable( renderable, world, m_state_stack.back().m_lights ); + } + if ( m_state_select1 && m_state_stack.back().m_highlight & eFace ) { + m_state_select1->addRenderable( renderable, world, m_state_stack.back().m_lights ); + } + if ( m_state_facewire && m_state_stack.back().m_highlight & eFaceWire ) { + m_state_facewire->addRenderable( renderable, world, m_state_stack.back().m_lights ); + } -void render( const Matrix4& modelview, const Matrix4& projection ){ - GlobalShaderCache().render( m_globalstate, modelview, projection, m_viewer ); -} + m_state_stack.back().m_state->addRenderable( renderable, world, m_state_stack.back().m_lights ); + } + + void render( const Matrix4& modelview, const Matrix4& projection ){ + GlobalShaderCache().render( m_globalstate, modelview, projection, m_viewer ); + } }; /* @@ -2081,27 +2083,27 @@ void CamWnd::Cam_Draw(){ break; case cd_solid: globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_SMOOTH - | RENDER_SCALED; + | RENDER_LIGHTING + | RENDER_SMOOTH + | RENDER_SCALED; break; case cd_texture: case cd_texture_plus_wire: globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_TEXTURE - | RENDER_SMOOTH - | RENDER_SCALED; + | RENDER_LIGHTING + | RENDER_TEXTURE + | RENDER_SMOOTH + | RENDER_SCALED; break; case cd_lighting: globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_TEXTURE - | RENDER_SMOOTH - | RENDER_SCALED - | RENDER_BUMP - | RENDER_PROGRAM - | RENDER_SCREEN; + | RENDER_LIGHTING + | RENDER_TEXTURE + | RENDER_SMOOTH + | RENDER_SCALED + | RENDER_BUMP + | RENDER_PROGRAM + | RENDER_SCREEN; break; default: globalstate = 0; @@ -2114,11 +2116,11 @@ void CamWnd::Cam_Draw(){ { CamRenderer renderer( globalstate, - g_camwindow_globals_private.m_bFaceWire ? m_state_facewire : 0, - m_Camera.draw_mode == cd_texture_plus_wire ? m_state_wire : 0, - m_state_select0, - g_camwindow_globals_private.m_bFaceFill ? m_state_select1 : 0, - m_view.getViewer() ); + g_camwindow_globals_private.m_bFaceWire ? m_state_facewire : 0, + m_Camera.draw_mode == cd_texture_plus_wire ? m_state_wire : 0, + m_state_select0, + g_camwindow_globals_private.m_bFaceFill ? m_state_select1 : 0, + m_view.getViewer() ); Scene_Render( renderer, m_view ); @@ -2496,57 +2498,57 @@ void Camera_constructPreferences( PreferencesPage& page ){ page.appendCheckBox( "", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse ); page.appendCheckBox( "", "Zoom to Mouse pointer", g_camwindow_globals_private.m_bZoomToPointer ); page.appendCheckBox( - "", "Discrete movement", - FreeCaller1(), - BoolExportCaller( g_camwindow_globals_private.m_bCamDiscrete ) - ); + "", "Discrete movement", + FreeCaller1(), + BoolExportCaller( g_camwindow_globals_private.m_bCamDiscrete ) + ); page.appendCheckBox( - "", "Enable far-clip plane", - FreeCaller1(), - BoolExportCaller( g_camwindow_globals_private.m_bCubicClipping ) - ); + "", "Enable far-clip plane", + FreeCaller1(), + BoolExportCaller( g_camwindow_globals_private.m_bCubicClipping ) + ); page.appendCheckBox( - "", "Colorize selection", - BoolImportCaller( g_camwindow_globals_private.m_bFaceFill ), - BoolExportCaller( g_camwindow_globals_private.m_bFaceFill ) - ); + "", "Colorize selection", + BoolImportCaller( g_camwindow_globals_private.m_bFaceFill ), + BoolExportCaller( g_camwindow_globals_private.m_bFaceFill ) + ); page.appendCheckBox( - "", "Selected faces wire", - BoolImportCaller( g_camwindow_globals_private.m_bFaceWire ), - BoolExportCaller( g_camwindow_globals_private.m_bFaceWire ) - ); + "", "Selected faces wire", + BoolImportCaller( g_camwindow_globals_private.m_bFaceWire ), + BoolExportCaller( g_camwindow_globals_private.m_bFaceWire ) + ); const char* render_modes[]{ "Wireframe", "Flatshade", "Textured", "Textured+Wire", "Lighting" }; page.appendCombo( - "Render Mode", - StringArrayRange( render_modes, render_modes + ARRAY_SIZE( render_modes ) - ( g_pGameDescription->mGameType == "doom3"? 0 : 1 ) ), - IntImportCallback( RenderModeImportCaller() ), - IntExportCallback( RenderModeExportCaller() ) - ); + "Render Mode", + StringArrayRange( render_modes, render_modes + ARRAY_SIZE( render_modes ) - ( g_pGameDescription->mGameType == "doom3"? 0 : 1 ) ), + IntImportCallback( RenderModeImportCaller() ), + IntExportCallback( RenderModeExportCaller() ) + ); if( GlobalOpenGL().support_ARB_framebuffer_object ){ const char* samples[] = { "0", "2", "4", "8", "16", "32" }; page.appendCombo( - "MSAA", - STRING_ARRAY_RANGE( samples ), - IntImportCallback( MSAAImportCaller() ), - IntExportCallback( MSAAExportCaller() ) - ); + "MSAA", + STRING_ARRAY_RANGE( samples ), + IntImportCallback( MSAAImportCaller() ), + IntExportCallback( MSAAExportCaller() ) + ); } const char* strafe_mode[] = { "None", "Up", "Forward", "Both", "Both Inverted" }; page.appendCombo( - "Strafe Mode", - g_camwindow_globals_private.m_strafeMode, - STRING_ARRAY_RANGE( strafe_mode ) - ); + "Strafe Mode", + g_camwindow_globals_private.m_strafeMode, + STRING_ARRAY_RANGE( strafe_mode ) + ); page.appendSpinner( "Field Of View", 110.0, 1.0, 175.0, - FloatImportCallback( fieldOfViewImportCaller() ), - FloatExportCallback( FloatExportCaller( camera_t::fieldOfView ) ) - ); + FloatImportCallback( fieldOfViewImportCaller() ), + FloatExportCallback( FloatExportCaller( camera_t::fieldOfView ) ) + ); } void Camera_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Camera", "Camera View Preferences" ) ); diff --git a/radiant/clippertool.cpp b/radiant/clippertool.cpp index d1553444..4b562c12 100644 --- a/radiant/clippertool.cpp +++ b/radiant/clippertool.cpp @@ -180,11 +180,11 @@ void Clipper_constructPreferences( PreferencesPage& page ){ { const char* dowhat[] = { "Clip ", "Split", }; page.appendRadio( - "On DoubleClick do: ", - STRING_ARRAY_RANGE( dowhat ), - IntImportCaller( g_clipper_doubleclicked_split ), - IntExportCaller( g_clipper_doubleclicked_split ) - ); + "On DoubleClick do: ", + STRING_ARRAY_RANGE( dowhat ), + IntImportCaller( g_clipper_doubleclicked_split ), + IntExportCaller( g_clipper_doubleclicked_split ) + ); } } void Clipper_constructPage( PreferenceGroup& group ){ diff --git a/radiant/commands.cpp b/radiant/commands.cpp index 673635e0..fe3b5446 100644 --- a/radiant/commands.cpp +++ b/radiant/commands.cpp @@ -243,18 +243,18 @@ class VerifyAcceleratorNotTaken public: bool allow; VerifyAcceleratorNotTaken( const char *name, const Accelerator &accelerator, GtkWidget *w, GtkTreeModel *m ) : - commandName( name ), newAccel( accelerator ), widget( w ), model( m ), allow( true ){ + commandName( name ), newAccel( accelerator ), widget( w ), model( m ), allow( true ){ } void operator()( const char* name, Accelerator& accelerator ){ if ( !allow - || accelerator.key == 0 - || !strcmp( name, commandName ) ) { + || accelerator.key == 0 + || !strcmp( name, commandName ) ) { return; } if ( accelerator == newAccel ) { StringOutputStream msg; msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n" - << "Do you want to unassign " << name << " first?"; + << "Do you want to unassign " << name << " first?"; EMessageBoxReturn r = gtk_MessageBox( widget, msg.c_str(), "Key already used", eMB_YESNOCANCEL ); if ( r == eIDYES ) { // clear the ACTUAL accelerator too! @@ -549,36 +549,36 @@ void SaveCommandMap( const char* path ){ class ReadCommandMap { -const char* m_filename; -std::size_t m_count; + const char* m_filename; + std::size_t m_count; public: -ReadCommandMap( const char* filename ) : m_filename( filename ), m_count( 0 ){ -} -void operator()( const char* name, Accelerator& accelerator ){ - char value[1024]; - if ( read_var( m_filename, "Commands", name, value ) ) { - if ( string_empty( value ) ) { - accelerator = accelerator_null(); - return; - } + ReadCommandMap( const char* filename ) : m_filename( filename ), m_count( 0 ){ + } + void operator()( const char* name, Accelerator& accelerator ){ + char value[1024]; + if ( read_var( m_filename, "Commands", name, value ) ) { + if ( string_empty( value ) ) { + accelerator = accelerator_null(); + return; + } - guint key; - GdkModifierType modifiers; - gtk_accelerator_parse( value, &key, &modifiers ); - accelerator = Accelerator( key, modifiers ); + guint key; + GdkModifierType modifiers; + gtk_accelerator_parse( value, &key, &modifiers ); + accelerator = Accelerator( key, modifiers ); - if ( accelerator.key != 0 ) { - ++m_count; - } - else - { - globalWarningStream() << "WARNING: failed to parse user command " << makeQuoted( name ) << ": unknown key " << makeQuoted( value ) << "\n"; + if ( accelerator.key != 0 ) { + ++m_count; + } + else + { + globalWarningStream() << "WARNING: failed to parse user command " << makeQuoted( name ) << ": unknown key " << makeQuoted( value ) << "\n"; + } } } -} -std::size_t count() const { - return m_count; -} + std::size_t count() const { + return m_count; + } }; void LoadCommandMap( const char* path ){ diff --git a/radiant/console.cpp b/radiant/console.cpp index 5101b5b6..00a13a60 100644 --- a/radiant/console.cpp +++ b/radiant/console.cpp @@ -63,11 +63,11 @@ void Sys_LogFile( bool enable ){ time_t localtime; time( &localtime ); globalOutputStream() << "Today is: " << ctime( &localtime ) - << "This is NetRadiant '" RADIANT_VERSION "' compiled " __DATE__ "\n" RADIANT_ABOUTMSG "\n"; + << "This is NetRadiant '" RADIANT_VERSION "' compiled " __DATE__ "\n" RADIANT_ABOUTMSG "\n"; } else{ gtk_MessageBox( 0, "Failed to create log file, check write permissions in Radiant directory.\n", - "Console logging", eMB_OK, eMB_ICONERROR ); + "Console logging", eMB_OK, eMB_ICONERROR ); } } else if ( !enable && g_hLogFile != 0 ) { @@ -143,20 +143,20 @@ GtkWidget* Console_constructWindow( GtkWindow* toplevel ){ class GtkTextBufferOutputStream : public TextOutputStream { -GtkTextBuffer* textBuffer; -GtkTextIter* iter; -GtkTextTag* tag; + GtkTextBuffer* textBuffer; + GtkTextIter* iter; + GtkTextTag* tag; public: -GtkTextBufferOutputStream( GtkTextBuffer* textBuffer, GtkTextIter* iter, GtkTextTag* tag ) : textBuffer( textBuffer ), iter( iter ), tag( tag ){ -} -std::size_t + GtkTextBufferOutputStream( GtkTextBuffer* textBuffer, GtkTextIter* iter, GtkTextTag* tag ) : textBuffer( textBuffer ), iter( iter ), tag( tag ){ + } + std::size_t #ifdef __GNUC__ //__attribute__((optimize("O0"))) #endif -write( const char* buffer, std::size_t length ){ - gtk_text_buffer_insert_with_tags( textBuffer, iter, buffer, gint( length ), tag, NULL ); - return length; -} + write( const char* buffer, std::size_t length ){ + gtk_text_buffer_insert_with_tags( textBuffer, iter, buffer, gint( length ), tag, NULL ); + return length; + } }; //#pragma GCC pop_options @@ -237,25 +237,25 @@ std::size_t Sys_Print( int level, const char* buf, std::size_t length ){ class SysPrintOutputStream : public TextOutputStream { public: -std::size_t write( const char* buffer, std::size_t length ){ - return Sys_Print( SYS_STD, buffer, length ); -} + std::size_t write( const char* buffer, std::size_t length ){ + return Sys_Print( SYS_STD, buffer, length ); + } }; class SysPrintErrorStream : public TextOutputStream { public: -std::size_t write( const char* buffer, std::size_t length ){ - return Sys_Print( SYS_ERR, buffer, length ); -} + std::size_t write( const char* buffer, std::size_t length ){ + return Sys_Print( SYS_ERR, buffer, length ); + } }; class SysPrintWarningStream : public TextOutputStream { public: -std::size_t write( const char* buffer, std::size_t length ){ - return Sys_Print( SYS_WRN, buffer, length ); -} + std::size_t write( const char* buffer, std::size_t length ){ + return Sys_Print( SYS_WRN, buffer, length ); + } }; SysPrintOutputStream g_outputStream; diff --git a/radiant/csg.cpp b/radiant/csg.cpp index cd7be79c..40a22b13 100644 --- a/radiant/csg.cpp +++ b/radiant/csg.cpp @@ -206,10 +206,10 @@ public: for( std::size_t index = 0; index < winding.numpoints; ++index ){ const std::size_t next = Winding_next( winding, index ); m_out.back()->addPlane( winding[index].vertex, - winding[next].vertex, - winding[next].vertex + face.getPlane().plane3().normal() * m_settings.m_offset, - TextureBrowser_GetSelectedShader(), - projection ); + winding[next].vertex, + winding[next].vertex + face.getPlane().plane3().normal() * m_settings.m_offset, + TextureBrowser_GetSelectedShader(), + projection ); } } } @@ -247,24 +247,24 @@ void brush_extrudeDiag( const Brush& brush0, const Brush& brush2, brush_vector_t double bestdot = -1; for( std::size_t index2 = 0; index2 < winding2.numpoints; ++index2 ){ const double dot = vector3_dot( - vector3_normalised( - vector3_cross( - winding0[index0].vertex - winding0[next].vertex, - winding0[index0].vertex - winding2[index2].vertex - ) - ), - normal - ); + vector3_normalised( + vector3_cross( + winding0[index0].vertex - winding0[next].vertex, + winding0[index0].vertex - winding2[index2].vertex + ) + ), + normal + ); if( dot > bestdot ) { bestdot = dot; BestPoint = winding2[index2].vertex; } } m_out.back()->addPlane( winding0[swap? next : index0].vertex, - winding0[swap? index0 : next].vertex, - BestPoint, - shader, - projection ); + winding0[swap? index0 : next].vertex, + BestPoint, + shader, + projection ); } }; //insert side planes from each winding perspective, as their form may change after brush expansion @@ -288,10 +288,10 @@ void brush_extrudeDiag( const Brush& brush0, const Brush& brush2, brush_vector_t } } m_out.back()->addPlane( winding0[index0].vertex, - winding0[next].vertex, - BestPoint, - shader, - projection ); + winding0[next].vertex, + BestPoint, + shader, + projection ); } } } @@ -325,7 +325,7 @@ public: if( path.top().get().visible() ) { Brush* brush = Node_getBrush( path.top() ); if( brush != 0 - && ( Instance_isSelected( instance ) || Instance_isSelectedComponents( instance ) ) ) { + && ( Instance_isSelected( instance ) || Instance_isSelectedComponents( instance ) ) ) { m_settings.excludeFaces( *Instance_getBrush( instance ) ); brush_vector_t out; @@ -374,21 +374,21 @@ typedef std::list brushlist_t; class BrushGatherSelected : public scene::Graph::Walker { -brush_vector_t& m_brushlist; + brush_vector_t& m_brushlist; public: -BrushGatherSelected( brush_vector_t& brushlist ) - : m_brushlist( brushlist ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 - && Instance_isSelected( instance ) ) { - m_brushlist.push_back( brush ); - } + BrushGatherSelected( brush_vector_t& brushlist ) + : m_brushlist( brushlist ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 + && Instance_isSelected( instance ) ) { + m_brushlist.push_back( brush ); + } + } + return true; } - return true; -} }; /* class BrushDeleteSelected : public scene::Graph::Walker @@ -413,44 +413,44 @@ void post( const scene::Path& path, scene::Instance& instance ) const { class BrushDeleteSelected : public scene::Graph::Walker { -scene::Node* m_keepNode; -mutable bool m_eraseParent; + scene::Node* m_keepNode; + mutable bool m_eraseParent; public: -BrushDeleteSelected( scene::Node* keepNode ): m_keepNode( keepNode ), m_eraseParent( false ){ -} -BrushDeleteSelected(): m_keepNode( NULL ), m_eraseParent( false ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - //globalOutputStream() << path.size() << "\n"; - if ( path.top().get().visible() ) { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 - && Instance_isSelected( instance ) - && path.size() > 1 - && path.top().get_pointer() != m_keepNode ) { - scene::Node& parent = path.parent(); - Path_deleteTop( path ); - if( Node_getTraversable( parent )->empty() ){ - m_eraseParent = true; - //globalOutputStream() << "Empty node?!.\n"; + BrushDeleteSelected( scene::Node* keepNode ): m_keepNode( keepNode ), m_eraseParent( false ){ + } + BrushDeleteSelected(): m_keepNode( NULL ), m_eraseParent( false ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + //globalOutputStream() << path.size() << "\n"; + if ( path.top().get().visible() ) { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 + && Instance_isSelected( instance ) + && path.size() > 1 + && path.top().get_pointer() != m_keepNode ) { + scene::Node& parent = path.parent(); + Path_deleteTop( path ); + if( Node_getTraversable( parent )->empty() ){ + m_eraseParent = true; + //globalOutputStream() << "Empty node?!.\n"; + } + return; + } + } + if( m_eraseParent && !Node_isPrimitive( path.top() ) && path.size() > 1 ){ + //globalOutputStream() << "about to Delete empty node!.\n"; + m_eraseParent = false; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && path.top().get_pointer() != Map_FindWorldspawn( g_map ) + && Node_getTraversable( path.top() )->empty() && path.top().get_pointer() != m_keepNode ) { + //globalOutputStream() << "now Deleting empty node!.\n"; + Path_deleteTop( path ); } - return; } } - if( m_eraseParent && !Node_isPrimitive( path.top() ) && path.size() > 1 ){ - //globalOutputStream() << "about to Delete empty node!.\n"; - m_eraseParent = false; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && path.top().get_pointer() != Map_FindWorldspawn( g_map ) - && Node_getTraversable( path.top() )->empty() && path.top().get_pointer() != m_keepNode ) { - //globalOutputStream() << "now Deleting empty node!.\n"; - Path_deleteTop( path ); - } - } -} }; @@ -458,28 +458,28 @@ template class RemoveReference { public: -typedef Type type; + typedef Type type; }; template class RemoveReference { public: -typedef Type type; + typedef Type type; }; template class Dereference { -const Functor& functor; + const Functor& functor; public: -typedef typename RemoveReference::type* first_argument_type; -typedef typename Functor::result_type result_type; -Dereference( const Functor& functor ) : functor( functor ){ -} -result_type operator()( first_argument_type firstArgument ) const { - return functor( *firstArgument ); -} + typedef typename RemoveReference::type* first_argument_type; + typedef typename Functor::result_type result_type; + Dereference( const Functor& functor ) : functor( functor ){ + } + result_type operator()( first_argument_type firstArgument ) const { + return functor( *firstArgument ); + } }; template @@ -499,35 +499,35 @@ Face* Brush_findIf( const Brush& brush, const Predicate& predicate ){ template class BindArguments1 { -typedef typename Caller::second_argument_type FirstBound; -FirstBound firstBound; + typedef typename Caller::second_argument_type FirstBound; + FirstBound firstBound; public: -typedef typename Caller::result_type result_type; -typedef typename Caller::first_argument_type first_argument_type; -BindArguments1( FirstBound firstBound ) - : firstBound( firstBound ){ -} -result_type operator()( first_argument_type firstArgument ) const { - return Caller::call( firstArgument, firstBound ); -} + typedef typename Caller::result_type result_type; + typedef typename Caller::first_argument_type first_argument_type; + BindArguments1( FirstBound firstBound ) + : firstBound( firstBound ){ + } + result_type operator()( first_argument_type firstArgument ) const { + return Caller::call( firstArgument, firstBound ); + } }; template class BindArguments2 { -typedef typename Caller::second_argument_type FirstBound; -typedef typename Caller::third_argument_type SecondBound; -FirstBound firstBound; -SecondBound secondBound; + typedef typename Caller::second_argument_type FirstBound; + typedef typename Caller::third_argument_type SecondBound; + FirstBound firstBound; + SecondBound secondBound; public: -typedef typename Caller::result_type result_type; -typedef typename Caller::first_argument_type first_argument_type; -BindArguments2( FirstBound firstBound, SecondBound secondBound ) - : firstBound( firstBound ), secondBound( secondBound ){ -} -result_type operator()( first_argument_type firstArgument ) const { - return Caller::call( firstArgument, firstBound, secondBound ); -} + typedef typename Caller::result_type result_type; + typedef typename Caller::first_argument_type first_argument_type; + BindArguments2( FirstBound firstBound, SecondBound secondBound ) + : firstBound( firstBound ), secondBound( secondBound ){ + } + result_type operator()( first_argument_type firstArgument ) const { + return Caller::call( firstArgument, firstBound, secondBound ); + } }; template @@ -583,7 +583,7 @@ bool Brush_subtract( const Brush& brush, const Brush& other, brush_vector_t& ret if ( ( *i )->contributes() ) { brushsplit_t split = Brush_classifyPlane( back, ( *i )->plane3() ); if ( split.counts[ePlaneFront] != 0 - && split.counts[ePlaneBack] != 0 ) { + && split.counts[ePlaneBack] != 0 ) { fragments.push_back( new Brush( back ) ); Face* newFace = fragments.back()->addFace( *( *i ) ); if ( newFace != 0 ) { @@ -608,87 +608,87 @@ bool Brush_subtract( const Brush& brush, const Brush& other, brush_vector_t& ret class SubtractBrushesFromUnselected : public scene::Graph::Walker { -const brush_vector_t& m_brushlist; -std::size_t& m_before; -std::size_t& m_after; -mutable bool m_eraseParent; + const brush_vector_t& m_brushlist; + std::size_t& m_before; + std::size_t& m_after; + mutable bool m_eraseParent; public: -SubtractBrushesFromUnselected( const brush_vector_t& brushlist, std::size_t& before, std::size_t& after ) - : m_brushlist( brushlist ), m_before( before ), m_after( after ), m_eraseParent( false ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - return true; + SubtractBrushesFromUnselected( const brush_vector_t& brushlist, std::size_t& before, std::size_t& after ) + : m_brushlist( brushlist ), m_before( before ), m_after( after ), m_eraseParent( false ){ } - return false; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 - && !Instance_isSelected( instance ) ) { - brush_vector_t buffer[2]; - bool swap = false; - Brush* original = new Brush( *brush ); - buffer[static_cast( swap )].push_back( original ); + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + return true; + } + return false; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 + && !Instance_isSelected( instance ) ) { + brush_vector_t buffer[2]; + bool swap = false; + Brush* original = new Brush( *brush ); + buffer[static_cast( swap )].push_back( original ); - { - for ( brush_vector_t::const_iterator i( m_brushlist.begin() ); i != m_brushlist.end(); ++i ) { - for ( brush_vector_t::iterator j( buffer[static_cast( swap )].begin() ); j != buffer[static_cast( swap )].end(); ++j ) + for ( brush_vector_t::const_iterator i( m_brushlist.begin() ); i != m_brushlist.end(); ++i ) { - if ( Brush_subtract( *( *j ), *( *i ), buffer[static_cast( !swap )] ) ) { - delete ( *j ); - } - else + for ( brush_vector_t::iterator j( buffer[static_cast( swap )].begin() ); j != buffer[static_cast( swap )].end(); ++j ) { - buffer[static_cast( !swap )].push_back( ( *j ) ); + if ( Brush_subtract( *( *j ), *( *i ), buffer[static_cast( !swap )] ) ) { + delete ( *j ); + } + else + { + buffer[static_cast( !swap )].push_back( ( *j ) ); + } + } + buffer[static_cast( swap )].clear(); + swap = !swap; + } + } + + brush_vector_t& out = buffer[static_cast( swap )]; + + if ( out.size() == 1 && out.back() == original ) { + delete original; + } + else + { + ++m_before; + for ( brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i ) + { + ++m_after; + ( *i )->removeEmptyFaces(); + if ( !( *i )->empty() ) { + NodeSmartReference node( ( new BrushNode() )->node() ); + Node_getBrush( node )->copy( *( *i ) ); + delete ( *i ); + Node_getTraversable( path.parent() )->insert( node ); + } + else{ + delete ( *i ); } } - buffer[static_cast( swap )].clear(); - swap = !swap; - } - } - - brush_vector_t& out = buffer[static_cast( swap )]; - - if ( out.size() == 1 && out.back() == original ) { - delete original; - } - else - { - ++m_before; - for ( brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i ) - { - ++m_after; - ( *i )->removeEmptyFaces(); - if ( !( *i )->empty() ) { - NodeSmartReference node( ( new BrushNode() )->node() ); - Node_getBrush( node )->copy( *( *i ) ); - delete ( *i ); - Node_getTraversable( path.parent() )->insert( node ); - } - else{ - delete ( *i ); + scene::Node& parent = path.parent(); + Path_deleteTop( path ); + if( Node_getTraversable( parent )->empty() ){ + m_eraseParent = true; } } - scene::Node& parent = path.parent(); + } + } + if( m_eraseParent && !Node_isPrimitive( path.top() ) && path.size() > 1 ){ + m_eraseParent = false; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && path.top().get_pointer() != Map_FindWorldspawn( g_map ) + && Node_getTraversable( path.top() )->empty() ) { Path_deleteTop( path ); - if( Node_getTraversable( parent )->empty() ){ - m_eraseParent = true; - } } } } - if( m_eraseParent && !Node_isPrimitive( path.top() ) && path.size() > 1 ){ - m_eraseParent = false; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && path.top().get_pointer() != Map_FindWorldspawn( g_map ) - && Node_getTraversable( path.top() )->empty() ) { - Path_deleteTop( path ); - } - } -} }; void CSG_Subtract(){ @@ -709,8 +709,8 @@ void CSG_Subtract(){ std::size_t after = 0; GlobalSceneGraph().traverse( SubtractBrushesFromUnselected( selected_brushes, before, after ) ); globalOutputStream() << "CSG Subtract: Result: " - << Unsigned( after ) << " fragment" << ( after == 1 ? "" : "s" ) - << " from " << Unsigned( before ) << " brush" << ( before == 1 ? "" : "es" ) << ".\n"; + << Unsigned( after ) << " fragment" << ( after == 1 ? "" : "s" ) + << " from " << Unsigned( before ) << " brush" << ( before == 1 ? "" : "es" ) << ".\n"; SceneChangeNotify(); } @@ -719,59 +719,59 @@ void CSG_Subtract(){ #include "clippertool.h" class BrushSplitByPlaneSelected : public scene::Graph::Walker { -const ClipperPoints m_points; -const Plane3 m_plane; /* plane to insert */ -const char* m_shader; -const TextureProjection& m_projection; -const bool m_split; /* split or clip */ + const ClipperPoints m_points; + const Plane3 m_plane; /* plane to insert */ + const char* m_shader; + const TextureProjection& m_projection; + const bool m_split; /* split or clip */ public: -mutable bool m_gj; -BrushSplitByPlaneSelected( const ClipperPoints& points, bool flip, const char* shader, const TextureProjection& projection, bool split ) - : m_points( flip? ClipperPoints( points[0], points[2], points[1], points._count ) : points ), + mutable bool m_gj; + BrushSplitByPlaneSelected( const ClipperPoints& points, bool flip, const char* shader, const TextureProjection& projection, bool split ) : + m_points( flip? ClipperPoints( points[0], points[2], points[1], points._count ) : points ), m_plane( plane3_for_points( m_points[0], m_points[1], m_points[2] ) ), m_shader( shader ), m_projection( projection ), m_split( split ), m_gj( false ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Brush* brush = Node_getBrush( path.top() ); - if ( brush != 0 - && Instance_isSelected( instance ) ) { - const brushsplit_t split = Brush_classifyPlane( *brush, m_plane ); - if ( split.counts[ePlaneBack] && split.counts[ePlaneFront] ) { - // the plane intersects this brush - m_gj = true; - if ( m_split ) { - NodeSmartReference node( ( new BrushNode() )->node() ); - Brush* fragment = Node_getBrush( node ); - fragment->copy( *brush ); - fragment->addPlane( m_points[0], m_points[2], m_points[1], m_shader, m_projection ); - fragment->removeEmptyFaces(); - ASSERT_MESSAGE( !fragment->empty(), "brush left with no faces after split" ); + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 + && Instance_isSelected( instance ) ) { + const brushsplit_t split = Brush_classifyPlane( *brush, m_plane ); + if ( split.counts[ePlaneBack] && split.counts[ePlaneFront] ) { + // the plane intersects this brush + m_gj = true; + if ( m_split ) { + NodeSmartReference node( ( new BrushNode() )->node() ); + Brush* fragment = Node_getBrush( node ); + fragment->copy( *brush ); + fragment->addPlane( m_points[0], m_points[2], m_points[1], m_shader, m_projection ); + fragment->removeEmptyFaces(); + ASSERT_MESSAGE( !fragment->empty(), "brush left with no faces after split" ); - Node_getTraversable( path.parent() )->insert( node ); - { - scene::Path fragmentPath = path; - fragmentPath.top() = makeReference( node.get() ); - selectPath( fragmentPath, true ); + Node_getTraversable( path.parent() )->insert( node ); + { + scene::Path fragmentPath = path; + fragmentPath.top() = makeReference( node.get() ); + selectPath( fragmentPath, true ); + } } - } - brush->addPlane( m_points[0], m_points[1], m_points[2], m_shader, m_projection ); - brush->removeEmptyFaces(); - ASSERT_MESSAGE( !brush->empty(), "brush left with no faces after split" ); - } - else - // the plane does not intersect this brush and the brush is in front of the plane - if ( !m_split && split.counts[ePlaneFront] != 0 ) { - m_gj = true; - Path_deleteTop( path ); + brush->addPlane( m_points[0], m_points[1], m_points[2], m_shader, m_projection ); + brush->removeEmptyFaces(); + ASSERT_MESSAGE( !brush->empty(), "brush left with no faces after split" ); + } + else + // the plane does not intersect this brush and the brush is in front of the plane + if ( !m_split && split.counts[ePlaneFront] != 0 ) { + m_gj = true; + Path_deleteTop( path ); + } } } } -} }; void CSG_WrapMerge( const ClipperPoints& clipperPoints ); @@ -791,21 +791,25 @@ void Scene_BrushSplitByPlane( scene::Graph& graph, const ClipperPoints& points, class BrushInstanceSetClipPlane : public scene::Graph::Walker { -const Plane3 m_plane; + const Plane3 m_plane; public: -BrushInstanceSetClipPlane( const ClipperPoints& points, bool flip ) - : m_plane( points._count < 2? Plane3( 0, 0, 0, 0 ) : flip? plane3_for_points( points[0], points[2], points[1] ) : plane3_for_points( points[0], points[1], points[2] ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - BrushInstance* brush = Instance_getBrush( instance ); - if ( brush != 0 - && path.top().get().visible() - && brush->isSelected() ) { - BrushInstance& brushInstance = *brush; - brushInstance.setClipPlane( m_plane ); + BrushInstanceSetClipPlane( const ClipperPoints& points, bool flip ) + : m_plane( points._count < 2 + ? Plane3( 0, 0, 0, 0 ) + : flip + ? plane3_for_points( points[0], points[2], points[1] ) + : plane3_for_points( points[0], points[1], points[2] ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + BrushInstance* brush = Instance_getBrush( instance ); + if ( brush != 0 + && path.top().get().visible() + && brush->isSelected() ) { + BrushInstance& brushInstance = *brush; + brushInstance.setClipPlane( m_plane ); + } + return true; } - return true; -} }; void Scene_BrushSetClipPlane( scene::Graph& graph, const ClipperPoints& points, bool flip ){ @@ -1001,22 +1005,22 @@ public: class Scene_gatherSelectedComponents : public scene::Graph::Walker { -MergeVertices& m_mergeVertices; -const Vector3Callback m_callback; + MergeVertices& m_mergeVertices; + const Vector3Callback m_callback; public: -Scene_gatherSelectedComponents( MergeVertices& mergeVertices ) - : m_mergeVertices( mergeVertices ), m_callback( [this]( const Vector3& value ){ m_mergeVertices.insert( value ); } ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - ComponentEditable* componentEditable = Instance_getComponentEditable( instance ); - if ( componentEditable ) { - componentEditable->gatherSelectedComponents( m_callback ); - } - return true; + Scene_gatherSelectedComponents( MergeVertices& mergeVertices ) + : m_mergeVertices( mergeVertices ), m_callback( [this]( const Vector3& value ){ m_mergeVertices.insert( value ); } ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + ComponentEditable* componentEditable = Instance_getComponentEditable( instance ); + if ( componentEditable ) { + componentEditable->gatherSelectedComponents( m_callback ); + } + return true; + } + return false; } - return false; -} }; class MergePlane @@ -1084,8 +1088,8 @@ void CSG_build_hull( const MergeVertices& mergeVertices, MergePlanes& mergePlane pointCloud.reserve( mergeVertices.size() ); for( std::size_t i = 0; i < mergeVertices.size(); ++i ){ pointCloud.push_back( quickhull::Vector3( static_cast( mergeVertices[i].x() ), - static_cast( mergeVertices[i].y() ), - static_cast( mergeVertices[i].z() ) ) ); + static_cast( mergeVertices[i].y() ), + static_cast( mergeVertices[i].z() ) ) ); } auto hull = quickhull.getConvexHull( pointCloud, true, true ); const auto& indexBuffer = hull.getIndexBuffer(); @@ -1482,8 +1486,8 @@ void CSG_Tool(){ //gtk_widget_show( label ); GtkWidget* button = gtk_button_new_with_label( "Grid->" ); gtk_table_attach( table, button, 0, 1, 0, 1, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_grid2spin ), &g_csgtool_dialog ); } @@ -1493,8 +1497,8 @@ void CSG_Tool(){ gtk_widget_show( GTK_WIDGET( spin ) ); gtk_widget_set_tooltip_text( GTK_WIDGET( spin ), "Thickness" ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 ); gtk_spin_button_set_numeric( spin, TRUE ); @@ -1517,17 +1521,17 @@ void CSG_Tool(){ gtk_widget_show( radCam ); gtk_table_attach( table, radFaces, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, radPlusFaces, 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, radProj, 4, 5, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, radCam, 5, 6, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_csgtool_dialog.radFaces = GTK_TOGGLE_BUTTON( radFaces ); g_csgtool_dialog.radPlusFaces = GTK_TOGGLE_BUTTON( radPlusFaces ); @@ -1539,8 +1543,8 @@ void CSG_Tool(){ button_set_icon( GTK_BUTTON( button ), "f-caulk.png" ); gtk_button_set_relief( GTK_BUTTON( button ), GTK_RELIEF_NONE ); gtk_table_attach( table, button, 6, 7, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Caulk some faces" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), TRUE ); gtk_widget_show( button ); @@ -1551,8 +1555,8 @@ void CSG_Tool(){ button_set_icon( GTK_BUTTON( button ), "csgtool_removeinner.png" ); gtk_button_set_relief( GTK_BUTTON( button ), GTK_RELIEF_NONE ); gtk_table_attach( table, button, 7, 8, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Remove inner brush" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), TRUE ); gtk_widget_show( button ); @@ -1562,15 +1566,15 @@ void CSG_Tool(){ GtkWidget* sep = gtk_hseparator_new(); gtk_widget_show( sep ); gtk_table_attach( table, sep, 0, 8, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_shrink.png" ); gtk_table_attach( table, button, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Shrink brush" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_BrushShrink ), &g_csgtool_dialog ); @@ -1579,8 +1583,8 @@ void CSG_Tool(){ GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_expand.png" ); gtk_table_attach( table, button, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Expand brush" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_BrushExpand ), &g_csgtool_dialog ); @@ -1589,8 +1593,8 @@ void CSG_Tool(){ GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_diagonal.png" ); gtk_table_attach( table, button, 3, 4, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Hollow::diagonal joints" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowDiag ), &g_csgtool_dialog ); @@ -1599,8 +1603,8 @@ void CSG_Tool(){ GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_wrap.png" ); gtk_table_attach( table, button, 4, 5, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Hollow::wrap" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowWrap ), &g_csgtool_dialog ); @@ -1609,8 +1613,8 @@ void CSG_Tool(){ GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_extrude.png" ); gtk_table_attach( table, button, 5, 6, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Hollow::extrude faces" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowExtrude ), &g_csgtool_dialog ); @@ -1619,8 +1623,8 @@ void CSG_Tool(){ GtkWidget* button = gtk_button_new(); button_set_icon( GTK_BUTTON( button ), "csgtool_pull.png" ); gtk_table_attach( table, button, 6, 7, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_tooltip_text( button, "Hollow::pull faces" ); gtk_widget_show( button ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowPull ), &g_csgtool_dialog ); diff --git a/radiant/dialog.cpp b/radiant/dialog.cpp index f3797e82..7c8f1b8b 100644 --- a/radiant/dialog.cpp +++ b/radiant/dialog.cpp @@ -57,10 +57,10 @@ GtkEntry* DialogEntry_new(){ class DialogEntryRow { public: -DialogEntryRow( GtkWidget* row, GtkEntry* entry ) : m_row( row ), m_entry( entry ){ -} -GtkWidget* m_row; -GtkEntry* m_entry; + DialogEntryRow( GtkWidget* row, GtkEntry* entry ) : m_row( row ), m_entry( entry ){ + } + GtkWidget* m_row; + GtkEntry* m_entry; }; DialogEntryRow DialogEntryRow_new( const char* name ){ @@ -91,10 +91,10 @@ GtkSpinButton* DialogSpinner_new( double value, double lower, double upper, int class DialogSpinnerRow { public: -DialogSpinnerRow( GtkWidget* row, GtkSpinButton* spin ) : m_row( row ), m_spin( spin ){ -} -GtkWidget* m_row; -GtkSpinButton* m_spin; + DialogSpinnerRow( GtkWidget* row, GtkSpinButton* spin ) : m_row( row ), m_spin( spin ){ + } + GtkWidget* m_row; + GtkSpinButton* m_spin; }; DialogSpinnerRow DialogSpinnerRow_new( const char* name, double value, double lower, double upper, int fraction ){ @@ -110,19 +110,19 @@ DialogSpinnerRow DialogSpinnerRow_new( const char* name, double value, double lo template< - typename Type_, - typename Other_, - void( *Import ) ( Type_&, Other_ ), - void( *Export ) ( Type_&, const Callback1& ) - > + typename Type_, + typename Other_, + void( *Import ) ( Type_&, Other_ ), + void( *Export ) ( Type_&, const Callback1& ) + > class ImportExport { public: -typedef Type_ Type; -typedef Other_ Other; + typedef Type_ Type; + typedef Other_ Other; -typedef ReferenceCaller1 ImportCaller; -typedef ReferenceCaller1&, Export> ExportCaller; + typedef ReferenceCaller1 ImportCaller; + typedef ReferenceCaller1&, Export> ExportCaller; }; typedef ImportExport BoolImportExport; @@ -238,70 +238,70 @@ template class CallbackDialogData final : public DLG_DATA { public: -typedef Callback1 ImportCallback; -typedef Callback1 ExportCallback; + typedef Callback1 ImportCallback; + typedef Callback1 ExportCallback; private: -ImportCallback m_importWidget; -ExportCallback m_exportWidget; -ImportCallback m_importViewer; -ExportCallback m_exportViewer; + ImportCallback m_importWidget; + ExportCallback m_exportWidget; + ImportCallback m_importViewer; + ExportCallback m_exportViewer; public: -CallbackDialogData( const ImportCallback& importWidget, const ExportCallback& exportWidget, const ImportCallback& importViewer, const ExportCallback& exportViewer ) - : m_importWidget( importWidget ), m_exportWidget( exportWidget ), m_importViewer( importViewer ), m_exportViewer( exportViewer ){ -} -void release(){ - delete this; -} -void importData() const { - m_exportViewer( m_importWidget ); -} -void exportData() const { - m_exportWidget( m_importViewer ); -} + CallbackDialogData( const ImportCallback& importWidget, const ExportCallback& exportWidget, const ImportCallback& importViewer, const ExportCallback& exportViewer ) + : m_importWidget( importWidget ), m_exportWidget( exportWidget ), m_importViewer( importViewer ), m_exportViewer( exportViewer ){ + } + void release(){ + delete this; + } + void importData() const { + m_exportViewer( m_importWidget ); + } + void exportData() const { + m_exportWidget( m_importViewer ); + } }; template class AddData { -DialogDataList& m_data; + DialogDataList& m_data; public: -AddData( DialogDataList& data ) : m_data( data ){ -} -void apply( typename Widget::Type& widget, typename Viewer::Type& viewer ) const { - m_data.push_back( - new CallbackDialogData( - typename Widget::ImportCaller( widget ), - typename Widget::ExportCaller( widget ), - typename Viewer::ImportCaller( viewer ), - typename Viewer::ExportCaller( viewer ) - ) + AddData( DialogDataList& data ) : m_data( data ){ + } + void apply( typename Widget::Type& widget, typename Viewer::Type& viewer ) const { + m_data.push_back( + new CallbackDialogData( + typename Widget::ImportCaller( widget ), + typename Widget::ExportCaller( widget ), + typename Viewer::ImportCaller( viewer ), + typename Viewer::ExportCaller( viewer ) + ) ); -} + } }; template class AddCustomData { -DialogDataList& m_data; + DialogDataList& m_data; public: -AddCustomData( DialogDataList& data ) : m_data( data ){ -} -void apply( - typename Widget::Type& widget, - const Callback1& importViewer, - const Callback1&>& exportViewer + AddCustomData( DialogDataList& data ) : m_data( data ){ + } + void apply( + typename Widget::Type& widget, + const Callback1& importViewer, + const Callback1&>& exportViewer ) const { - m_data.push_back( - new CallbackDialogData( - typename Widget::ImportCaller( widget ), - typename Widget::ExportCaller( widget ), - importViewer, - exportViewer - ) + m_data.push_back( + new CallbackDialogData( + typename Widget::ImportCaller( widget ), + typename Widget::ExportCaller( widget ), + importViewer, + exportViewer + ) ); -} + } }; // ============================================================================= @@ -588,14 +588,14 @@ void Dialog::addRadioIcons( GtkWidget* vbox, const char* name, StringArrayRange GtkImage* image = new_local_image( *icon ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( image ), pos, pos + 1, 0, 1, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); radio = gtk_radio_button_new_from_widget( GTK_RADIO_BUTTON( radio ) ); gtk_widget_show( radio ); gtk_table_attach( GTK_TABLE( table ), radio, pos, pos + 1, 1, 2, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } AddIntRadioData( *GTK_RADIO_BUTTON( radio ), importViewer, exportViewer ); diff --git a/radiant/dialog.h b/radiant/dialog.h index 34b4aa59..6284c8f5 100644 --- a/radiant/dialog.h +++ b/radiant/dialog.h @@ -107,94 +107,94 @@ typedef std::list DialogDataList; class Dialog { -GtkWindow* m_window; -DialogDataList m_data; + GtkWindow* m_window; + DialogDataList m_data; public: -ModalDialog m_modal; -GtkWindow* m_parent; + ModalDialog m_modal; + GtkWindow* m_parent; -Dialog(); -virtual ~Dialog(); + Dialog(); + virtual ~Dialog(); -/*! - start modal dialog box - you need to use AddModalButton to select eIDOK eIDCANCEL buttons - */ -EMessageBoxReturn DoModal(); -void EndModal( EMessageBoxReturn code ); -virtual GtkWindow* BuildDialog() = 0; -virtual void exportData(); -virtual void importData(); -virtual void PreModal() { }; -virtual void PostModal( EMessageBoxReturn code ) { }; -virtual void ShowDlg(); -virtual void HideDlg(); -void Create(); -void Destroy(); -GtkWindow* GetWidget(){ - return m_window; -} -const GtkWindow* GetWidget() const { - return m_window; -} + /*! + start modal dialog box + you need to use AddModalButton to select eIDOK eIDCANCEL buttons + */ + EMessageBoxReturn DoModal(); + void EndModal( EMessageBoxReturn code ); + virtual GtkWindow* BuildDialog() = 0; + virtual void exportData(); + virtual void importData(); + virtual void PreModal() { }; + virtual void PostModal( EMessageBoxReturn code ) { }; + virtual void ShowDlg(); + virtual void HideDlg(); + void Create(); + void Destroy(); + GtkWindow* GetWidget(){ + return m_window; + } + const GtkWindow* GetWidget() const { + return m_window; + } -GtkWidget* addCheckBox( GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ); -GtkWidget* addCheckBox( GtkWidget* vbox, const char* name, const char* flag, bool& data ); -void addCombo( GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void addCombo( GtkWidget* vbox, const char* name, int& data, StringArrayRange values ); -void addSlider( GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ); -void addSlider( GtkWidget* vbox, const char* name, float& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ); -void addRadio( GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void addRadio( GtkWidget* vbox, const char* name, int& data, StringArrayRange names ); -void addRadioIcons( GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void addRadioIcons( GtkWidget* vbox, const char* name, int& data, StringArrayRange icons ); -GtkWidget* addIntEntry( GtkWidget* vbox, const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -GtkWidget* addEntry( GtkWidget* vbox, const char* name, int& data ){ - return addIntEntry( vbox, name, IntImportCaller( data ), IntExportCaller( data ) ); -} -GtkWidget* addSizeEntry( GtkWidget* vbox, const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ); -GtkWidget* addEntry( GtkWidget* vbox, const char* name, std::size_t& data ){ - return addSizeEntry( vbox, name, SizeImportCaller( data ), SizeExportCaller( data ) ); -} -GtkWidget* addFloatEntry( GtkWidget* vbox, const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); -GtkWidget* addEntry( GtkWidget* vbox, const char* name, float& data ){ - return addFloatEntry( vbox, name, FloatImportCaller( data ), FloatExportCaller( data ) ); -} -GtkWidget* addTextEntry( GtkWidget* vbox, const char* name, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); -GtkWidget* addEntry( GtkWidget* vbox, const char* name, CopiedString& data ){ - return addTextEntry( vbox, name, StringImportCallback( StringImportCaller( data ) ), StringExportCallback( StringExportCaller( data ) ) ); -} -GtkWidget* addPathEntry( GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); -GtkWidget* addPathEntry( GtkWidget* vbox, const char* name, CopiedString& data, bool directory ); -GtkWidget* addSpinner( GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper ); -GtkWidget* addSpinner( GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -GtkWidget* addSpinner( GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); + GtkWidget* addCheckBox( GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ); + GtkWidget* addCheckBox( GtkWidget* vbox, const char* name, const char* flag, bool& data ); + void addCombo( GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void addCombo( GtkWidget* vbox, const char* name, int& data, StringArrayRange values ); + void addSlider( GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ); + void addSlider( GtkWidget* vbox, const char* name, float& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ); + void addRadio( GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void addRadio( GtkWidget* vbox, const char* name, int& data, StringArrayRange names ); + void addRadioIcons( GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void addRadioIcons( GtkWidget* vbox, const char* name, int& data, StringArrayRange icons ); + GtkWidget* addIntEntry( GtkWidget* vbox, const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + GtkWidget* addEntry( GtkWidget* vbox, const char* name, int& data ){ + return addIntEntry( vbox, name, IntImportCaller( data ), IntExportCaller( data ) ); + } + GtkWidget* addSizeEntry( GtkWidget* vbox, const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ); + GtkWidget* addEntry( GtkWidget* vbox, const char* name, std::size_t& data ){ + return addSizeEntry( vbox, name, SizeImportCaller( data ), SizeExportCaller( data ) ); + } + GtkWidget* addFloatEntry( GtkWidget* vbox, const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); + GtkWidget* addEntry( GtkWidget* vbox, const char* name, float& data ){ + return addFloatEntry( vbox, name, FloatImportCaller( data ), FloatExportCaller( data ) ); + } + GtkWidget* addTextEntry( GtkWidget* vbox, const char* name, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); + GtkWidget* addEntry( GtkWidget* vbox, const char* name, CopiedString& data ){ + return addTextEntry( vbox, name, StringImportCallback( StringImportCaller( data ) ), StringExportCallback( StringExportCaller( data ) ) ); + } + GtkWidget* addPathEntry( GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); + GtkWidget* addPathEntry( GtkWidget* vbox, const char* name, CopiedString& data, bool directory ); + GtkWidget* addSpinner( GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper ); + GtkWidget* addSpinner( GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + GtkWidget* addSpinner( GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); protected: -void AddBoolToggleData( GtkToggleButton& object, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ); -void AddIntRadioData( GtkRadioButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void AddTextEntryData( GtkEntry& object, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); -void AddIntEntryData( GtkEntry& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void AddSizeEntryData( GtkEntry& object, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ); -void AddFloatEntryData( GtkEntry& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); -void AddFloatSpinnerData( GtkSpinButton& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); -void AddIntSpinnerData( GtkSpinButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void AddIntAdjustmentData( GtkAdjustment& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void AddFloatAdjustmentData( GtkAdjustment& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); -void AddIntComboData( GtkComboBox& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void AddBoolToggleData( GtkToggleButton& object, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ); + void AddIntRadioData( GtkRadioButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void AddTextEntryData( GtkEntry& object, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ); + void AddIntEntryData( GtkEntry& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void AddSizeEntryData( GtkEntry& object, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ); + void AddFloatEntryData( GtkEntry& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); + void AddFloatSpinnerData( GtkSpinButton& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); + void AddIntSpinnerData( GtkSpinButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void AddIntAdjustmentData( GtkAdjustment& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); + void AddFloatAdjustmentData( GtkAdjustment& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ); + void AddIntComboData( GtkComboBox& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ); -void AddDialogData( GtkToggleButton& object, bool& data ); -void AddDialogData( GtkRadioButton& object, int& data ); -void AddDialogData( GtkEntry& object, CopiedString& data ); -void AddDialogData( GtkEntry& object, int& data ); -void AddDialogData( GtkEntry& object, std::size_t& data ); -void AddDialogData( GtkEntry& object, float& data ); -void AddDialogData( GtkSpinButton& object, float& data ); -void AddDialogData( GtkSpinButton& object, int& data ); -void AddDialogData( GtkAdjustment& object, int& data ); -void AddDialogData( GtkAdjustment& object, float& data ); -void AddDialogData( GtkComboBox& object, int& data ); + void AddDialogData( GtkToggleButton& object, bool& data ); + void AddDialogData( GtkRadioButton& object, int& data ); + void AddDialogData( GtkEntry& object, CopiedString& data ); + void AddDialogData( GtkEntry& object, int& data ); + void AddDialogData( GtkEntry& object, std::size_t& data ); + void AddDialogData( GtkEntry& object, float& data ); + void AddDialogData( GtkSpinButton& object, float& data ); + void AddDialogData( GtkSpinButton& object, int& data ); + void AddDialogData( GtkAdjustment& object, int& data ); + void AddDialogData( GtkAdjustment& object, float& data ); + void AddDialogData( GtkComboBox& object, int& data ); }; #endif diff --git a/radiant/eclass.cpp b/radiant/eclass.cpp index c74c7b72..11312438 100644 --- a/radiant/eclass.cpp +++ b/radiant/eclass.cpp @@ -92,12 +92,12 @@ void Eclass_forEach( EntityClassVisitor& visitor ){ class RadiantEclassCollector : public EntityClassCollector { public: -void insert( EntityClass* eclass ){ - Eclass_InsertAlphabetized( eclass ); -} -void insert( const char* name, const ListAttributeType& list ){ - g_listTypes.insert( ListAttributeTypes::value_type( name, list ) ); -} + void insert( EntityClass* eclass ){ + Eclass_InsertAlphabetized( eclass ); + } + void insert( const char* name, const ListAttributeType& list ){ + g_listTypes.insert( ListAttributeTypes::value_type( name, list ) ); + } }; RadiantEclassCollector g_collector; @@ -114,56 +114,56 @@ const ListAttributeType* EntityClass_findListType( const char* name ){ class EntityClassFilterMode { public: -bool filter_mp_sp; -const char* mp_ignore_prefix; -const char* sp_ignore_prefix; + bool filter_mp_sp; + const char* mp_ignore_prefix; + const char* sp_ignore_prefix; -EntityClassFilterMode() : - filter_mp_sp( !string_empty( g_pGameDescription->getKeyValue( "eclass_filter_gamemode" ) ) ), - mp_ignore_prefix( g_pGameDescription->getKeyValue( "eclass_sp_prefix" ) ), - sp_ignore_prefix( g_pGameDescription->getKeyValue( "eclass_mp_prefix" ) ){ - if ( string_empty( mp_ignore_prefix ) ) { - mp_ignore_prefix = "sp_"; + EntityClassFilterMode() : + filter_mp_sp( !string_empty( g_pGameDescription->getKeyValue( "eclass_filter_gamemode" ) ) ), + mp_ignore_prefix( g_pGameDescription->getKeyValue( "eclass_sp_prefix" ) ), + sp_ignore_prefix( g_pGameDescription->getKeyValue( "eclass_mp_prefix" ) ){ + if ( string_empty( mp_ignore_prefix ) ) { + mp_ignore_prefix = "sp_"; + } + if ( string_empty( sp_ignore_prefix ) ) { + sp_ignore_prefix = "mp_"; + } } - if ( string_empty( sp_ignore_prefix ) ) { - sp_ignore_prefix = "mp_"; - } -} }; class EntityClassesLoadFile { -const EntityClassScanner& scanner; -const char* m_directory; + const EntityClassScanner& scanner; + const char* m_directory; public: -EntityClassesLoadFile( const EntityClassScanner& scanner, const char* directory ) : scanner( scanner ), m_directory( directory ){ -} -void operator()( const char* name ) const { - EntityClassFilterMode filterMode; - - if ( filterMode.filter_mp_sp ) { - if ( string_empty( GlobalRadiant().getGameMode() ) || string_equal( GlobalRadiant().getGameMode(), "sp" ) ) { - if ( string_equal_n( name, filterMode.sp_ignore_prefix, strlen( filterMode.sp_ignore_prefix ) ) ) { - globalOutputStream() << "Ignoring '" << name << "'\n"; - return; - } - } - else - { - if ( string_equal_n( name, filterMode.mp_ignore_prefix, strlen( filterMode.mp_ignore_prefix ) ) ) { - globalOutputStream() << "Ignoring '" << name << "'\n"; - return; - } - } + EntityClassesLoadFile( const EntityClassScanner& scanner, const char* directory ) : scanner( scanner ), m_directory( directory ){ } + void operator()( const char* name ) const { + EntityClassFilterMode filterMode; - // for a given name, we grab the first .def in the vfs - // this allows to override baseq3/scripts/entities.def for instance - StringOutputStream relPath( 256 ); - relPath << m_directory << name; + if ( filterMode.filter_mp_sp ) { + if ( string_empty( GlobalRadiant().getGameMode() ) || string_equal( GlobalRadiant().getGameMode(), "sp" ) ) { + if ( string_equal_n( name, filterMode.sp_ignore_prefix, strlen( filterMode.sp_ignore_prefix ) ) ) { + globalOutputStream() << "Ignoring '" << name << "'\n"; + return; + } + } + else + { + if ( string_equal_n( name, filterMode.mp_ignore_prefix, strlen( filterMode.mp_ignore_prefix ) ) ) { + globalOutputStream() << "Ignoring '" << name << "'\n"; + return; + } + } + } - scanner.scanFile( g_collector, relPath.c_str() ); -} + // for a given name, we grab the first .def in the vfs + // this allows to override baseq3/scripts/entities.def for instance + StringOutputStream relPath( 256 ); + relPath << m_directory << name; + + scanner.scanFile( g_collector, relPath.c_str() ); + } }; struct PathLess @@ -177,14 +177,14 @@ typedef std::map Paths; class PathsInsert { -Paths& m_paths; -const char* m_directory; + Paths& m_paths; + const char* m_directory; public: -PathsInsert( Paths& paths, const char* directory ) : m_paths( paths ), m_directory( directory ){ -} -void operator()( const char* name ) const { - m_paths.insert( Paths::value_type( name, m_directory ) ); -} + PathsInsert( Paths& paths, const char* directory ) : m_paths( paths ), m_directory( directory ){ + } + void operator()( const char* name ) const { + m_paths.insert( Paths::value_type( name, m_directory ) ); + } }; @@ -204,24 +204,24 @@ void EntityClassQuake3_Construct(){ class LoadEntityDefinitionsVisitor : public EClassModules::Visitor { - const char* baseDirectory; - const char* gameDirectory; -public: - LoadEntityDefinitionsVisitor( const char* baseDirectory, const char* gameDirectory ) - : baseDirectory( baseDirectory ), gameDirectory( gameDirectory ){ - } - void visit( const char* name, const EntityClassScanner& table ) const { - Paths paths; - EntityClassQuake3_constructDirectory( baseDirectory, table.getExtension(), paths ); - if ( !string_equal( baseDirectory, gameDirectory ) ) { - EntityClassQuake3_constructDirectory( gameDirectory, table.getExtension(), paths ); + const char* baseDirectory; + const char* gameDirectory; + public: + LoadEntityDefinitionsVisitor( const char* baseDirectory, const char* gameDirectory ) + : baseDirectory( baseDirectory ), gameDirectory( gameDirectory ){ } + void visit( const char* name, const EntityClassScanner& table ) const { + Paths paths; + EntityClassQuake3_constructDirectory( baseDirectory, table.getExtension(), paths ); + if ( !string_equal( baseDirectory, gameDirectory ) ) { + EntityClassQuake3_constructDirectory( gameDirectory, table.getExtension(), paths ); + } - for ( Paths::iterator i = paths.begin(); i != paths.end(); ++i ) - { - EntityClassesLoadFile( table, ( *i ).second ) ( ( *i ).first.c_str() ); + for ( Paths::iterator i = paths.begin(); i != paths.end(); ++i ) + { + EntityClassesLoadFile( table, ( *i ).second ) ( ( *i ).first.c_str() ); + } } - } }; EntityClassManager_getEClassModules().foreachModule( LoadEntityDefinitionsVisitor( baseDirectory.c_str(), gameDirectory.c_str() ) ); @@ -245,31 +245,31 @@ EntityClass *Eclass_ForName( const char *name, bool has_brushes ){ class EntityClassQuake3 : public ModuleObserver { -std::size_t m_unrealised; -ModuleObservers m_observers; + std::size_t m_unrealised; + ModuleObservers m_observers; public: -EntityClassQuake3() : m_unrealised( 4 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - //globalOutputStream() << "Entity Classes: realise\n"; - EntityClassQuake3_Construct(); - m_observers.realise(); + EntityClassQuake3() : m_unrealised( 4 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - m_observers.unrealise(); - //globalOutputStream() << "Entity Classes: unrealise\n"; - Eclass_Clear(); + void realise(){ + if ( --m_unrealised == 0 ) { + //globalOutputStream() << "Entity Classes: realise\n"; + EntityClassQuake3_Construct(); + m_observers.realise(); + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + m_observers.unrealise(); + //globalOutputStream() << "Entity Classes: unrealise\n"; + Eclass_Clear(); + } + } + void attach( ModuleObserver& observer ){ + m_observers.attach( observer ); + } + void detach( ModuleObserver& observer ){ + m_observers.detach( observer ); } -} -void attach( ModuleObserver& observer ){ - m_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - m_observers.detach( observer ); -} }; EntityClassQuake3 g_EntityClassQuake3; @@ -308,48 +308,48 @@ class EntityClassQuake3Dependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef { -EClassModulesRef m_eclass_modules; + EClassModulesRef m_eclass_modules; public: -EntityClassQuake3Dependencies() : - m_eclass_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclasstype" ) ){ -} -EClassModules& getEClassModules(){ - return m_eclass_modules.get(); -} + EntityClassQuake3Dependencies() : + m_eclass_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclasstype" ) ){ + } + EClassModules& getEClassModules(){ + return m_eclass_modules.get(); + } }; class EclassManagerAPI { -EntityClassManager m_eclassmanager; + EntityClassManager m_eclassmanager; public: -typedef EntityClassManager Type; -STRING_CONSTANT( Name, "quake3" ); + typedef EntityClassManager Type; + STRING_CONSTANT( Name, "quake3" ); -EclassManagerAPI(){ - EntityClassQuake3_construct(); + EclassManagerAPI(){ + EntityClassQuake3_construct(); - m_eclassmanager.findOrInsert = &Eclass_ForName; - m_eclassmanager.findListType = &EntityClass_findListType; - m_eclassmanager.forEach = &Eclass_forEach; - m_eclassmanager.attach = &EntityClass_attach; - m_eclassmanager.detach = &EntityClass_detach; - m_eclassmanager.realise = &EntityClass_realise; - m_eclassmanager.unrealise = &EntityClass_unrealise; + m_eclassmanager.findOrInsert = &Eclass_ForName; + m_eclassmanager.findListType = &EntityClass_findListType; + m_eclassmanager.forEach = &Eclass_forEach; + m_eclassmanager.attach = &EntityClass_attach; + m_eclassmanager.detach = &EntityClass_detach; + m_eclassmanager.realise = &EntityClass_realise; + m_eclassmanager.unrealise = &EntityClass_unrealise; - GlobalRadiant().attachGameToolsPathObserver( g_EntityClassQuake3 ); - GlobalRadiant().attachGameModeObserver( g_EntityClassQuake3 ); - GlobalRadiant().attachGameNameObserver( g_EntityClassQuake3 ); -} -~EclassManagerAPI(){ - GlobalRadiant().detachGameNameObserver( g_EntityClassQuake3 ); - GlobalRadiant().detachGameModeObserver( g_EntityClassQuake3 ); - GlobalRadiant().detachGameToolsPathObserver( g_EntityClassQuake3 ); + GlobalRadiant().attachGameToolsPathObserver( g_EntityClassQuake3 ); + GlobalRadiant().attachGameModeObserver( g_EntityClassQuake3 ); + GlobalRadiant().attachGameNameObserver( g_EntityClassQuake3 ); + } + ~EclassManagerAPI(){ + GlobalRadiant().detachGameNameObserver( g_EntityClassQuake3 ); + GlobalRadiant().detachGameModeObserver( g_EntityClassQuake3 ); + GlobalRadiant().detachGameToolsPathObserver( g_EntityClassQuake3 ); - EntityClassQuake3_destroy(); -} -EntityClassManager* getTable(){ - return &m_eclassmanager; -} + EntityClassQuake3_destroy(); + } + EntityClassManager* getTable(){ + return &m_eclassmanager; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/eclass_def.cpp b/radiant/eclass_def.cpp index 4ae3cd05..b74f79cb 100644 --- a/radiant/eclass_def.cpp +++ b/radiant/eclass_def.cpp @@ -45,18 +45,18 @@ class EntityClassDefDependencies : public GlobalShaderCacheModuleRef, public Glo class EclassDefAPI { -EntityClassScanner m_eclassdef; + EntityClassScanner m_eclassdef; public: -typedef EntityClassScanner Type; -STRING_CONSTANT( Name, "def" ); + typedef EntityClassScanner Type; + STRING_CONSTANT( Name, "def" ); -EclassDefAPI(){ - m_eclassdef.scanFile = &Eclass_ScanFile; - m_eclassdef.getExtension = &EClass_GetExtension; -} -EntityClassScanner* getTable(){ - return &m_eclassdef; -} + EclassDefAPI(){ + m_eclassdef.scanFile = &Eclass_ScanFile; + m_eclassdef.getExtension = &EClass_GetExtension; + } + EntityClassScanner* getTable(){ + return &m_eclassdef; + } }; typedef SingletonModule EclassDefModule; @@ -230,7 +230,7 @@ EntityClass *Eclass_InitFromText( const char *text ){ if ( Get_COM_Token()[0] == '(' ) { // parse the size as two vectors e->fixedsize = true; int r = sscanf( text,"%f %f %f) (%f %f %f)", &e->mins[0], &e->mins[1], &e->mins[2], - &e->maxs[0], &e->maxs[1], &e->maxs[2] ); + &e->maxs[0], &e->maxs[1], &e->maxs[2] ); if ( r != 6 ) { return 0; } diff --git a/radiant/eclass_doom3.cpp b/radiant/eclass_doom3.cpp index 7cc25fb7..82f27feb 100644 --- a/radiant/eclass_doom3.cpp +++ b/radiant/eclass_doom3.cpp @@ -41,13 +41,13 @@ class RawString { -const char* m_value; + const char* m_value; public: -RawString( const char* value ) : m_value( value ){ -} -const char* c_str() const { - return m_value; -} + RawString( const char* value ) : m_value( value ){ + } + const char* c_str() const { + return m_value; + } }; inline bool operator<( const RawString& self, const RawString& other ){ @@ -152,14 +152,14 @@ bool EntityClassDoom3_parseUnknown( Tokeniser& tokeniser ){ class Model { public: -bool m_resolved; -CopiedString m_mesh; -CopiedString m_skin; -CopiedString m_parent; -typedef std::map Anims; -Anims m_anims; -Model() : m_resolved( false ){ -} + bool m_resolved; + CopiedString m_mesh; + CopiedString m_skin; + CopiedString m_parent; + typedef std::map Anims; + Anims m_anims; + Model() : m_resolved( false ){ + } }; typedef std::map Models; @@ -403,14 +403,14 @@ static bool EntityClass_parse( EntityClass& entityClass, Tokeniser& tokeniser ){ currentString = &usage; } else if ( string_equal( key, "editor_rotatable" ) - || string_equal( key, "editor_showangle" ) - || string_equal( key, "editor_showangles" ) // typo? in prey movables.def - || string_equal( key, "editor_mover" ) - || string_equal( key, "editor_model" ) - || string_equal( key, "editor_material" ) - || string_equal( key, "editor_combatnode" ) - || ( !string_empty( last ) && string_equal( first.c_str(), "editor_gui" ) ) - || string_equal_n( key, "editor_copy", 11 ) ) { + || string_equal( key, "editor_showangle" ) + || string_equal( key, "editor_showangles" ) // typo? in prey movables.def + || string_equal( key, "editor_mover" ) + || string_equal( key, "editor_model" ) + || string_equal( key, "editor_material" ) + || string_equal( key, "editor_combatnode" ) + || ( !string_empty( last ) && string_equal( first.c_str(), "editor_gui" ) ) + || string_equal_n( key, "editor_copy", 11 ) ) { PARSE_RETURN_FALSE_IF_FAIL( EntityClassDoom3_parseToken( tokeniser ) ); } else if ( !string_empty( last ) && ( string_equal( first.c_str(), "editor_var" ) || string_equal( first.c_str(), "editor_string" ) ) ) { @@ -492,10 +492,10 @@ static bool EntityClass_parse( EntityClass& entityClass, Tokeniser& tokeniser ){ // end quake4-specific keys // begin ignore prey (unknown/unused?) entity keys else if ( string_equal( key, "editor_light" ) - || string_equal( key, "editor_def def_debrisspawner" ) - || string_equal( key, "editor_def def_drop" ) - || string_equal( key, "editor_def def_guihand" ) - || string_equal( key, "editor_def def_mine" ) ) { + || string_equal( key, "editor_def def_debrisspawner" ) + || string_equal( key, "editor_def def_drop" ) + || string_equal( key, "editor_def def_guihand" ) + || string_equal( key, "editor_def def_mine" ) ) { //const char* value = PARSE_RETURN_FALSE_IF_FAIL( EntityClassDoom3_parseToken( tokeniser ) ); } @@ -636,7 +636,7 @@ EntityClass* EntityClassDoom3_findOrInsert( const char *name, bool has_brushes ) EntityClasses::iterator i = g_EntityClassDoom3_classes.find( name ); if ( i != g_EntityClassDoom3_classes.end() //&& string_equal((*i).first, name) - ) { + ) { return ( *i ).second; } @@ -683,73 +683,73 @@ void EntityClass_resolveInheritance( EntityClass* derivedClass ){ class EntityClassDoom3 : public ModuleObserver { -std::size_t m_unrealised; -ModuleObservers m_observers; + std::size_t m_unrealised; + ModuleObservers m_observers; public: -EntityClassDoom3() : m_unrealised( 2 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - globalOutputStream() << "searching vfs directory " << makeQuoted( "def" ) << " for *.def\n"; - GlobalFileSystem().forEachFile( "def/", "def", FreeCaller1() ); + EntityClassDoom3() : m_unrealised( 2 ){ + } + void realise(){ + if ( --m_unrealised == 0 ) { + globalOutputStream() << "searching vfs directory " << makeQuoted( "def" ) << " for *.def\n"; + GlobalFileSystem().forEachFile( "def/", "def", FreeCaller1() ); - { - for ( Models::iterator i = g_models.begin(); i != g_models.end(); ++i ) { - Model_resolveInheritance( ( *i ).first.c_str(), ( *i ).second ); - } - } - { - for ( EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i ) - { - EntityClass_resolveInheritance( ( *i ).second ); - if ( !string_empty( ( *i ).second->m_modelpath.c_str() ) ) { - Models::iterator j = g_models.find( ( *i ).second->m_modelpath ); - if ( j != g_models.end() ) { - ( *i ).second->m_modelpath = ( *j ).second.m_mesh; - ( *i ).second->m_skin = ( *j ).second.m_skin; - } - } - eclass_capture_state( ( *i ).second ); - - StringOutputStream usage( 256 ); - - usage << "-------- NOTES --------\n"; - - if ( !string_empty( ( *i ).second->m_comments.c_str() ) ) { - usage << ( *i ).second->m_comments.c_str() << "\n"; - } - - usage << "\n-------- KEYS --------\n"; - - for ( EntityClassAttributes::iterator j = ( *i ).second->m_attributes.begin(); j != ( *i ).second->m_attributes.end(); ++j ) + for ( Models::iterator i = g_models.begin(); i != g_models.end(); ++i ) { - const char* name = EntityClassAttributePair_getName( *j ); - const char* description = EntityClassAttributePair_getDescription( *j ); - if ( !string_equal( name, description ) ) { - usage << EntityClassAttributePair_getName( *j ) << " : " << EntityClassAttributePair_getDescription( *j ) << "\n"; - } + Model_resolveInheritance( ( *i ).first.c_str(), ( *i ).second ); } - - ( *i ).second->m_comments = usage.c_str(); } - } + { + for ( EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i ) + { + EntityClass_resolveInheritance( ( *i ).second ); + if ( !string_empty( ( *i ).second->m_modelpath.c_str() ) ) { + Models::iterator j = g_models.find( ( *i ).second->m_modelpath ); + if ( j != g_models.end() ) { + ( *i ).second->m_modelpath = ( *j ).second.m_mesh; + ( *i ).second->m_skin = ( *j ).second.m_skin; + } + } + eclass_capture_state( ( *i ).second ); - m_observers.realise(); + StringOutputStream usage( 256 ); + + usage << "-------- NOTES --------\n"; + + if ( !string_empty( ( *i ).second->m_comments.c_str() ) ) { + usage << ( *i ).second->m_comments.c_str() << "\n"; + } + + usage << "\n-------- KEYS --------\n"; + + for ( EntityClassAttributes::iterator j = ( *i ).second->m_attributes.begin(); j != ( *i ).second->m_attributes.end(); ++j ) + { + const char* name = EntityClassAttributePair_getName( *j ); + const char* description = EntityClassAttributePair_getDescription( *j ); + if ( !string_equal( name, description ) ) { + usage << EntityClassAttributePair_getName( *j ) << " : " << EntityClassAttributePair_getDescription( *j ) << "\n"; + } + } + + ( *i ).second->m_comments = usage.c_str(); + } + } + + m_observers.realise(); + } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - m_observers.unrealise(); - EntityClassDoom3_clear(); + void unrealise(){ + if ( ++m_unrealised == 1 ) { + m_observers.unrealise(); + EntityClassDoom3_clear(); + } + } + void attach( ModuleObserver& observer ){ + m_observers.attach( observer ); + } + void detach( ModuleObserver& observer ){ + m_observers.detach( observer ); } -} -void attach( ModuleObserver& observer ){ - m_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - m_observers.detach( observer ); -} }; EntityClassDoom3 g_EntityClassDoom3; @@ -791,28 +791,28 @@ class EntityClassDoom3Dependencies : public GlobalFileSystemModuleRef, public Gl class EntityClassDoom3API { -EntityClassManager m_eclassmanager; + EntityClassManager m_eclassmanager; public: -typedef EntityClassManager Type; -STRING_CONSTANT( Name, "doom3" ); + typedef EntityClassManager Type; + STRING_CONSTANT( Name, "doom3" ); -EntityClassDoom3API(){ - EntityClassDoom3_construct(); + EntityClassDoom3API(){ + EntityClassDoom3_construct(); - m_eclassmanager.findOrInsert = &EntityClassDoom3_findOrInsert; - m_eclassmanager.findListType = &EntityClassDoom3_findListType; - m_eclassmanager.forEach = &EntityClassDoom3_forEach; - m_eclassmanager.attach = &EntityClassDoom3_attach; - m_eclassmanager.detach = &EntityClassDoom3_detach; - m_eclassmanager.realise = &EntityClassDoom3_realise; - m_eclassmanager.unrealise = &EntityClassDoom3_unrealise; -} -~EntityClassDoom3API(){ - EntityClassDoom3_destroy(); -} -EntityClassManager* getTable(){ - return &m_eclassmanager; -} + m_eclassmanager.findOrInsert = &EntityClassDoom3_findOrInsert; + m_eclassmanager.findListType = &EntityClassDoom3_findListType; + m_eclassmanager.forEach = &EntityClassDoom3_forEach; + m_eclassmanager.attach = &EntityClassDoom3_attach; + m_eclassmanager.detach = &EntityClassDoom3_detach; + m_eclassmanager.realise = &EntityClassDoom3_realise; + m_eclassmanager.unrealise = &EntityClassDoom3_unrealise; + } + ~EntityClassDoom3API(){ + EntityClassDoom3_destroy(); + } + EntityClassManager* getTable(){ + return &m_eclassmanager; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/eclass_fgd.cpp b/radiant/eclass_fgd.cpp index 1018af34..bea76e37 100644 --- a/radiant/eclass_fgd.cpp +++ b/radiant/eclass_fgd.cpp @@ -170,24 +170,24 @@ void EntityClassFGD_parseClass( Tokeniser& tokeniser, bool fixedsize, bool isBas ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, ")" ), PARSE_ERROR ); } else if ( string_equal( property, "sprite" ) - || string_equal( property, "decal" ) - // hl2 below - || string_equal( property, "overlay" ) - || string_equal( property, "light" ) - || string_equal( property, "keyframe" ) - || string_equal( property, "animator" ) - || string_equal( property, "quadbounds" ) ) { + || string_equal( property, "decal" ) + // hl2 below + || string_equal( property, "overlay" ) + || string_equal( property, "light" ) + || string_equal( property, "keyframe" ) + || string_equal( property, "animator" ) + || string_equal( property, "quadbounds" ) ) { ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, "(" ), PARSE_ERROR ); ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, ")" ), PARSE_ERROR ); } // hl2 below else if ( string_equal( property, "sphere" ) - || string_equal( property, "sweptplayerhull" ) - || string_equal( property, "studio" ) - || string_equal( property, "studioprop" ) - || string_equal( property, "lightprop" ) - || string_equal( property, "lightcone" ) - || string_equal( property, "sidelist" ) ) { + || string_equal( property, "sweptplayerhull" ) + || string_equal( property, "studio" ) + || string_equal( property, "studioprop" ) + || string_equal( property, "lightprop" ) + || string_equal( property, "lightcone" ) + || string_equal( property, "sidelist" ) ) { ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, "(" ), PARSE_ERROR ); if ( string_equal( tokeniser.getToken(), ")" ) ) { tokeniser.ungetToken(); @@ -195,7 +195,7 @@ void EntityClassFGD_parseClass( Tokeniser& tokeniser, bool fixedsize, bool isBas ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, ")" ), PARSE_ERROR ); } else if ( string_equal( property, "line" ) - || string_equal( property, "cylinder" ) ) { + || string_equal( property, "cylinder" ) ) { ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, "(" ), PARSE_ERROR ); //const char* r = tokeniser.getToken(); @@ -254,7 +254,7 @@ void EntityClassFGD_parseClass( Tokeniser& tokeniser, bool fixedsize, bool isBas } if ( string_equal_nocase( key.c_str(), "input" ) - || string_equal_nocase( key.c_str(), "output" ) ) { + || string_equal_nocase( key.c_str(), "output" ) ) { const char* name = tokeniser.getToken(); if ( !string_equal( name, "(" ) ) { ASSERT_MESSAGE( EntityClassFGD_parseToken( tokeniser, "(" ), PARSE_ERROR ); @@ -393,28 +393,28 @@ void EntityClassFGD_parseClass( Tokeniser& tokeniser, bool fixedsize, bool isBas else if ( string_equal_nocase( type.c_str(), "decal" ) ) { } else if ( string_equal_nocase( type.c_str(), "string" ) - || string_equal_nocase( type.c_str(), "integer" ) - || string_equal_nocase( type.c_str(), "studio" ) - || string_equal_nocase( type.c_str(), "sprite" ) - || string_equal_nocase( type.c_str(), "color255" ) - || string_equal_nocase( type.c_str(), "target_source" ) - || string_equal_nocase( type.c_str(), "target_destination" ) - || string_equal_nocase( type.c_str(), "sound" ) - // hl2 below - || string_equal_nocase( type.c_str(), "angle" ) - || string_equal_nocase( type.c_str(), "origin" ) - || string_equal_nocase( type.c_str(), "float" ) - || string_equal_nocase( type.c_str(), "node_dest" ) - || string_equal_nocase( type.c_str(), "filterclass" ) - || string_equal_nocase( type.c_str(), "vector" ) - || string_equal_nocase( type.c_str(), "sidelist" ) - || string_equal_nocase( type.c_str(), "material" ) - || string_equal_nocase( type.c_str(), "vecline" ) - || string_equal_nocase( type.c_str(), "axis" ) - || string_equal_nocase( type.c_str(), "npcclass" ) - || string_equal_nocase( type.c_str(), "target_name_or_class" ) - || string_equal_nocase( type.c_str(), "pointentityclass" ) - || string_equal_nocase( type.c_str(), "scene" ) ) { + || string_equal_nocase( type.c_str(), "integer" ) + || string_equal_nocase( type.c_str(), "studio" ) + || string_equal_nocase( type.c_str(), "sprite" ) + || string_equal_nocase( type.c_str(), "color255" ) + || string_equal_nocase( type.c_str(), "target_source" ) + || string_equal_nocase( type.c_str(), "target_destination" ) + || string_equal_nocase( type.c_str(), "sound" ) + // hl2 below + || string_equal_nocase( type.c_str(), "angle" ) + || string_equal_nocase( type.c_str(), "origin" ) + || string_equal_nocase( type.c_str(), "float" ) + || string_equal_nocase( type.c_str(), "node_dest" ) + || string_equal_nocase( type.c_str(), "filterclass" ) + || string_equal_nocase( type.c_str(), "vector" ) + || string_equal_nocase( type.c_str(), "sidelist" ) + || string_equal_nocase( type.c_str(), "material" ) + || string_equal_nocase( type.c_str(), "vecline" ) + || string_equal_nocase( type.c_str(), "axis" ) + || string_equal_nocase( type.c_str(), "npcclass" ) + || string_equal_nocase( type.c_str(), "target_name_or_class" ) + || string_equal_nocase( type.c_str(), "pointentityclass" ) + || string_equal_nocase( type.c_str(), "scene" ) ) { if ( !string_equal( tokeniser.getToken(), "readonly" ) ) { tokeniser.ungetToken(); } @@ -493,11 +493,11 @@ void EntityClassFGD_parse( TextInputStream& inputStream, const char* path ){ EntityClassFGD_parseClass( tokeniser, false, true ); } else if ( string_equal( blockType, "@PointClass" ) - // hl2 below - || string_equal( blockType, "@KeyFrameClass" ) - || string_equal( blockType, "@MoveClass" ) - || string_equal( blockType, "@FilterClass" ) - || string_equal( blockType, "@NPCClass" ) ) { + // hl2 below + || string_equal( blockType, "@KeyFrameClass" ) + || string_equal( blockType, "@MoveClass" ) + || string_equal( blockType, "@FilterClass" ) + || string_equal( blockType, "@NPCClass" ) ) { EntityClassFGD_parseClass( tokeniser, true, false ); } // hl2 below @@ -542,7 +542,7 @@ EntityClass* EntityClassFGD_findOrInsert( const char *name, bool has_brushes ){ EntityClasses::iterator i = g_EntityClassFGD_classes.find( name ); if ( i != g_EntityClassFGD_classes.end() //&& string_equal((*i).first, name) - ) { + ) { return ( *i ).second; } @@ -594,53 +594,53 @@ void EntityClassFGD_resolveInheritance( EntityClass* derivedClass ){ class EntityClassFGD : public ModuleObserver { -std::size_t m_unrealised; -ModuleObservers m_observers; + std::size_t m_unrealised; + ModuleObservers m_observers; public: -EntityClassFGD() : m_unrealised( 3 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - StringOutputStream filename( 256 ); - filename << GlobalRadiant().getGameToolsPath() << GlobalRadiant().getGameName() << "/halflife.fgd"; - EntityClassFGD_loadFile( filename.c_str() ); + EntityClassFGD() : m_unrealised( 3 ){ + } + void realise(){ + if ( --m_unrealised == 0 ) { + StringOutputStream filename( 256 ); + filename << GlobalRadiant().getGameToolsPath() << GlobalRadiant().getGameName() << "/halflife.fgd"; + EntityClassFGD_loadFile( filename.c_str() ); - { - for ( EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i ) { - EntityClassFGD_resolveInheritance( ( *i ).second ); - if ( ( *i ).second->fixedsize && string_empty( ( *i ).second->m_modelpath.c_str() ) ) { - if ( !( *i ).second->sizeSpecified ) { - globalErrorStream() << "size not specified for entity class: " << makeQuoted( ( *i ).second->name() ) << '\n'; - } - if ( !( *i ).second->colorSpecified ) { - globalErrorStream() << "color not specified for entity class: " << makeQuoted( ( *i ).second->name() ) << '\n'; + for ( EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i ) + { + EntityClassFGD_resolveInheritance( ( *i ).second ); + if ( ( *i ).second->fixedsize && string_empty( ( *i ).second->m_modelpath.c_str() ) ) { + if ( !( *i ).second->sizeSpecified ) { + globalErrorStream() << "size not specified for entity class: " << makeQuoted( ( *i ).second->name() ) << '\n'; + } + if ( !( *i ).second->colorSpecified ) { + globalErrorStream() << "color not specified for entity class: " << makeQuoted( ( *i ).second->name() ) << '\n'; + } } } } - } - { - for ( BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i ) { - eclass_capture_state( ( *i ).second ); + for ( BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i ) + { + eclass_capture_state( ( *i ).second ); + } } - } - m_observers.realise(); + m_observers.realise(); + } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - m_observers.unrealise(); - EntityClassFGD_clear(); + void unrealise(){ + if ( ++m_unrealised == 1 ) { + m_observers.unrealise(); + EntityClassFGD_clear(); + } + } + void attach( ModuleObserver& observer ){ + m_observers.attach( observer ); + } + void detach( ModuleObserver& observer ){ + m_observers.detach( observer ); } -} -void attach( ModuleObserver& observer ){ - m_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - m_observers.detach( observer ); -} }; EntityClassFGD g_EntityClassFGD; @@ -678,34 +678,34 @@ class EntityClassFGDDependencies : public GlobalFileSystemModuleRef, public Glob class EntityClassFGDAPI { -EntityClassManager m_eclassmanager; + EntityClassManager m_eclassmanager; public: -typedef EntityClassManager Type; -STRING_CONSTANT( Name, "halflife" ); + typedef EntityClassManager Type; + STRING_CONSTANT( Name, "halflife" ); -EntityClassFGDAPI(){ - EntityClassFGD_construct(); + EntityClassFGDAPI(){ + EntityClassFGD_construct(); - m_eclassmanager.findOrInsert = &EntityClassFGD_findOrInsert; - m_eclassmanager.findListType = &EntityClassFGD_findListType; - m_eclassmanager.forEach = &EntityClassFGD_forEach; - m_eclassmanager.attach = &EntityClassFGD_attach; - m_eclassmanager.detach = &EntityClassFGD_detach; - m_eclassmanager.realise = &EntityClassFGD_realise; - m_eclassmanager.unrealise = &EntityClassFGD_unrealise; + m_eclassmanager.findOrInsert = &EntityClassFGD_findOrInsert; + m_eclassmanager.findListType = &EntityClassFGD_findListType; + m_eclassmanager.forEach = &EntityClassFGD_forEach; + m_eclassmanager.attach = &EntityClassFGD_attach; + m_eclassmanager.detach = &EntityClassFGD_detach; + m_eclassmanager.realise = &EntityClassFGD_realise; + m_eclassmanager.unrealise = &EntityClassFGD_unrealise; - GlobalRadiant().attachGameToolsPathObserver( g_EntityClassFGD ); - GlobalRadiant().attachGameNameObserver( g_EntityClassFGD ); -} -~EntityClassFGDAPI(){ - GlobalRadiant().detachGameNameObserver( g_EntityClassFGD ); - GlobalRadiant().detachGameToolsPathObserver( g_EntityClassFGD ); + GlobalRadiant().attachGameToolsPathObserver( g_EntityClassFGD ); + GlobalRadiant().attachGameNameObserver( g_EntityClassFGD ); + } + ~EntityClassFGDAPI(){ + GlobalRadiant().detachGameNameObserver( g_EntityClassFGD ); + GlobalRadiant().detachGameToolsPathObserver( g_EntityClassFGD ); - EntityClassFGD_destroy(); -} -EntityClassManager* getTable(){ - return &m_eclassmanager; -} + EntityClassFGD_destroy(); + } + EntityClassManager* getTable(){ + return &m_eclassmanager; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/eclass_xml.cpp b/radiant/eclass_xml.cpp index d1893360..64be1ffa 100644 --- a/radiant/eclass_xml.cpp +++ b/radiant/eclass_xml.cpp @@ -128,10 +128,10 @@ class IgnoreBreaks { public: -const char* m_first; -const char* m_last; -IgnoreBreaks( const char* first, const char* last ) : m_first( first ), m_last( last ){ -} + const char* m_first; + const char* m_last; + IgnoreBreaks( const char* first, const char* last ) : m_first( first ), m_last( last ){ + } }; template @@ -151,122 +151,122 @@ namespace class TreeXMLImporter : public TextOutputStream { public: -virtual TreeXMLImporter& pushElement( const XMLElement& element ) = 0; -virtual void popElement( const char* name ) = 0; + virtual TreeXMLImporter& pushElement( const XMLElement& element ) = 0; + virtual void popElement( const char* name ) = 0; }; template class Storage { -char m_storage[sizeof( Type )]; + char m_storage[sizeof( Type )]; public: -Type& get(){ - return *reinterpret_cast( m_storage ); -} -const Type& get() const { - return *reinterpret_cast( m_storage ); -} + Type& get(){ + return *reinterpret_cast( m_storage ); + } + const Type& get() const { + return *reinterpret_cast( m_storage ); + } }; class BreakImporter : public TreeXMLImporter { public: -BreakImporter( StringOutputStream& comment ){ - comment << '\n'; -} -static const char* name(){ - return "n"; -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); - return *this; -} -void popElement( const char* elementName ){ - ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} + BreakImporter( StringOutputStream& comment ){ + comment << '\n'; + } + static const char* name(){ + return "n"; + } + TreeXMLImporter& pushElement( const XMLElement& element ){ + ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); + return *this; + } + void popElement( const char* elementName ){ + ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + } + std::size_t write( const char* data, std::size_t length ){ + return length; + } }; class AttributeImporter : public TreeXMLImporter { -StringOutputStream& m_comment; + StringOutputStream& m_comment; -EntityClassAttribute* m_attribute; + EntityClassAttribute* m_attribute; public: -AttributeImporter( StringOutputStream& comment, EntityClass* entityClass, const XMLElement& element ) : m_comment( comment ){ - const char* type = element.name(); - const char* key = element.attribute( "key" ); - const char* name = element.attribute( "name" ); - const char* value = element.attribute( "value" ); + AttributeImporter( StringOutputStream& comment, EntityClass* entityClass, const XMLElement& element ) : m_comment( comment ){ + const char* type = element.name(); + const char* key = element.attribute( "key" ); + const char* name = element.attribute( "name" ); + const char* value = element.attribute( "value" ); - ASSERT_MESSAGE( !string_empty( key ), "key attribute not specified" ); - ASSERT_MESSAGE( !string_empty( name ), "name attribute not specified" ); + ASSERT_MESSAGE( !string_empty( key ), "key attribute not specified" ); + ASSERT_MESSAGE( !string_empty( name ), "name attribute not specified" ); - m_attribute = &EntityClass_insertAttribute( *entityClass, key, EntityClassAttribute( type, name, value ) ).second; + m_attribute = &EntityClass_insertAttribute( *entityClass, key, EntityClassAttribute( type, name, value ) ).second; - if ( string_equal( type, "flag" ) ) { - std::size_t bit = atoi( element.attribute( "bit" ) ); - ASSERT_MESSAGE( bit < MAX_FLAGS, "invalid flag bit" ); - ASSERT_MESSAGE( string_empty( entityClass->flagnames[bit] ), "non-unique flag bit" ); - strcpy( entityClass->flagnames[bit], key ); - entityClass->flagAttributes[bit] = m_attribute; - } - else if( entityClass->fixedsize && string_equal( type, "model" ) ){ - entityClass->miscmodel_is = true; - entityClass->m_miscmodel_key = key; - } - else if( string_equal( type, "angle" ) || string_equal( type, "angles" ) || string_equal( type, "direction" ) ){ - entityClass->has_angles = true; - } + if ( string_equal( type, "flag" ) ) { + std::size_t bit = atoi( element.attribute( "bit" ) ); + ASSERT_MESSAGE( bit < MAX_FLAGS, "invalid flag bit" ); + ASSERT_MESSAGE( string_empty( entityClass->flagnames[bit] ), "non-unique flag bit" ); + strcpy( entityClass->flagnames[bit], key ); + entityClass->flagAttributes[bit] = m_attribute; + } + else if( entityClass->fixedsize && string_equal( type, "model" ) ){ + entityClass->miscmodel_is = true; + entityClass->m_miscmodel_key = key; + } + else if( string_equal( type, "angle" ) || string_equal( type, "angles" ) || string_equal( type, "direction" ) ){ + entityClass->has_angles = true; + } - m_comment << key; - m_comment << " : "; -} -~AttributeImporter(){ -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - ERROR_MESSAGE( PARSE_ERROR( element.name(), "attribute" ) ); - return *this; -} -void popElement( const char* elementName ){ - ERROR_MESSAGE( PARSE_ERROR( elementName, "attribute" ) ); -} -std::size_t write( const char* data, std::size_t length ){ - CopiedString& desc = m_attribute->m_description; - if( desc.empty() ){ - desc = StringRange( data, data + length ); + m_comment << key; + m_comment << " : "; } - else{ // in case of special symbols, e.g. ", &apos, <, >, &, xml writes in a few steps - desc = StringOutputStream()( desc.c_str(), StringRange( data, data + length ) ); + ~AttributeImporter(){ } + TreeXMLImporter& pushElement( const XMLElement& element ){ + ERROR_MESSAGE( PARSE_ERROR( element.name(), "attribute" ) ); + return *this; + } + void popElement( const char* elementName ){ + ERROR_MESSAGE( PARSE_ERROR( elementName, "attribute" ) ); + } + std::size_t write( const char* data, std::size_t length ){ + CopiedString& desc = m_attribute->m_description; + if( desc.empty() ){ + desc = StringRange( data, data + length ); + } + else{ // in case of special symbols, e.g. ", &apos, <, >, &, xml writes in a few steps + desc = StringOutputStream()( desc.c_str(), StringRange( data, data + length ) ); + } - return m_comment.write( data, length ); -} + return m_comment.write( data, length ); + } }; bool attributeSupported( const char* name ){ - return string_equal( name, "string" ) - || string_equal( name, "array" ) - || string_equal( name, "integer" ) - || string_equal( name, "boolean" ) - || string_equal( name, "integer2" ) - || string_equal( name, "integer3" ) - || string_equal( name, "real" ) - || string_equal( name, "angle" ) - || string_equal( name, "direction" ) - || string_equal( name, "real3" ) - || string_equal( name, "angles" ) - || string_equal( name, "color" ) - || string_equal( name, "target" ) - || string_equal( name, "targetname" ) - || string_equal( name, "sound" ) - || string_equal( name, "texture" ) - || string_equal( name, "model" ) - || string_equal( name, "skin" ) - || string_equal( name, "flag" ); + return string_equal( name, "string" ) + || string_equal( name, "array" ) + || string_equal( name, "integer" ) + || string_equal( name, "boolean" ) + || string_equal( name, "integer2" ) + || string_equal( name, "integer3" ) + || string_equal( name, "real" ) + || string_equal( name, "angle" ) + || string_equal( name, "direction" ) + || string_equal( name, "real3" ) + || string_equal( name, "angles" ) + || string_equal( name, "color" ) + || string_equal( name, "target" ) + || string_equal( name, "targetname" ) + || string_equal( name, "sound" ) + || string_equal( name, "texture" ) + || string_equal( name, "model" ) + || string_equal( name, "skin" ) + || string_equal( name, "flag" ); } typedef std::map ListAttributeTypes; @@ -278,94 +278,94 @@ bool listAttributeSupported( ListAttributeTypes& listTypes, const char* name ){ class ClassImporter : public TreeXMLImporter { -EntityClassCollector& m_collector; -EntityClass* m_eclass; -StringOutputStream m_comment; -Storage m_attribute; -ListAttributeTypes& m_listTypes; + EntityClassCollector& m_collector; + EntityClass* m_eclass; + StringOutputStream m_comment; + Storage m_attribute; + ListAttributeTypes& m_listTypes; public: -ClassImporter( EntityClassCollector& collector, ListAttributeTypes& listTypes, const XMLElement& element ) : m_collector( collector ), m_listTypes( listTypes ){ - m_eclass = Eclass_Alloc(); - m_eclass->free = &Eclass_Free; + ClassImporter( EntityClassCollector& collector, ListAttributeTypes& listTypes, const XMLElement& element ) : m_collector( collector ), m_listTypes( listTypes ){ + m_eclass = Eclass_Alloc(); + m_eclass->free = &Eclass_Free; - const char* name = element.attribute( "name" ); - ASSERT_MESSAGE( !string_empty( name ), "name attribute not specified for class" ); - m_eclass->name_set( name ); + const char* name = element.attribute( "name" ); + ASSERT_MESSAGE( !string_empty( name ), "name attribute not specified for class" ); + m_eclass->name_set( name ); - const char* color = element.attribute( "color" ); - ASSERT_MESSAGE( !string_empty( name ), "color attribute not specified for class " << name ); - string_parse_vector3( color, m_eclass->color ); - eclass_capture_state( m_eclass ); + const char* color = element.attribute( "color" ); + ASSERT_MESSAGE( !string_empty( name ), "color attribute not specified for class " << name ); + string_parse_vector3( color, m_eclass->color ); + eclass_capture_state( m_eclass ); - const char* model = element.attribute( "model" ); - if ( !string_empty( model ) ) { - m_eclass->m_modelpath = StringOutputStream( 256 )( PathCleaned( model ) ).c_str(); - } + const char* model = element.attribute( "model" ); + if ( !string_empty( model ) ) { + m_eclass->m_modelpath = StringOutputStream( 256 )( PathCleaned( model ) ).c_str(); + } - const char* type = element.name(); - if ( string_equal( type, "point" ) ) { - const char* box = element.attribute( "box" ); - ASSERT_MESSAGE( !string_empty( box ), "box attribute not found for class " << name ); - m_eclass->fixedsize = true; - string_parse_vector( box, &m_eclass->mins.x(), &m_eclass->mins.x() + 6 ); + const char* type = element.name(); + if ( string_equal( type, "point" ) ) { + const char* box = element.attribute( "box" ); + ASSERT_MESSAGE( !string_empty( box ), "box attribute not found for class " << name ); + m_eclass->fixedsize = true; + string_parse_vector( box, &m_eclass->mins.x(), &m_eclass->mins.x() + 6 ); + } } -} -~ClassImporter(){ - m_eclass->m_comments = m_comment.c_str(); - m_collector.insert( m_eclass ); + ~ClassImporter(){ + m_eclass->m_comments = m_comment.c_str(); + m_collector.insert( m_eclass ); - for ( ListAttributeTypes::iterator i = m_listTypes.begin(); i != m_listTypes.end(); ++i ) - { - m_collector.insert( ( *i ).first.c_str(), ( *i ).second ); + for ( ListAttributeTypes::iterator i = m_listTypes.begin(); i != m_listTypes.end(); ++i ) + { + m_collector.insert( ( *i ).first.c_str(), ( *i ).second ); + } } -} -static const char* name(){ - return "class"; -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - if ( attributeSupported( element.name() ) || listAttributeSupported( m_listTypes, element.name() ) ) { - constructor( m_attribute.get(), makeReference( m_comment ), m_eclass, element ); - return m_attribute.get(); + static const char* name(){ + return "class"; } - else - { - ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); - return *this; + TreeXMLImporter& pushElement( const XMLElement& element ){ + if ( attributeSupported( element.name() ) || listAttributeSupported( m_listTypes, element.name() ) ) { + constructor( m_attribute.get(), makeReference( m_comment ), m_eclass, element ); + return m_attribute.get(); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); + return *this; + } } -} -void popElement( const char* elementName ){ - if ( attributeSupported( elementName ) || listAttributeSupported( m_listTypes, elementName ) ) { - destructor( m_attribute.get() ); + void popElement( const char* elementName ){ + if ( attributeSupported( elementName ) || listAttributeSupported( m_listTypes, elementName ) ) { + destructor( m_attribute.get() ); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + } } - else - { - ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + std::size_t write( const char* data, std::size_t length ){ + return m_comment.write( data, length ); } -} -std::size_t write( const char* data, std::size_t length ){ - return m_comment.write( data, length ); -} }; class ItemImporter : public TreeXMLImporter { public: -ItemImporter( ListAttributeType& list, const XMLElement& element ){ - const char* name = element.attribute( "name" ); - const char* value = element.attribute( "value" ); - list.push_back( name, value ); -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - ERROR_MESSAGE( PARSE_ERROR( element.name(), "item" ) ); - return *this; -} -void popElement( const char* elementName ){ - ERROR_MESSAGE( PARSE_ERROR( elementName, "item" ) ); -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} + ItemImporter( ListAttributeType& list, const XMLElement& element ){ + const char* name = element.attribute( "name" ); + const char* value = element.attribute( "value" ); + list.push_back( name, value ); + } + TreeXMLImporter& pushElement( const XMLElement& element ){ + ERROR_MESSAGE( PARSE_ERROR( element.name(), "item" ) ); + return *this; + } + void popElement( const char* elementName ){ + ERROR_MESSAGE( PARSE_ERROR( elementName, "item" ) ); + } + std::size_t write( const char* data, std::size_t length ){ + return length; + } }; bool isItem( const char* name ){ @@ -374,41 +374,41 @@ bool isItem( const char* name ){ class ListAttributeImporter : public TreeXMLImporter { -ListAttributeType* m_listType; -Storage m_item; + ListAttributeType* m_listType; + Storage m_item; public: -ListAttributeImporter( ListAttributeTypes& listTypes, const XMLElement& element ){ - const char* name = element.attribute( "name" ); - m_listType = &listTypes[name]; -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - if ( isItem( element.name() ) ) { - constructor( m_item.get(), makeReference( *m_listType ), element ); - return m_item.get(); + ListAttributeImporter( ListAttributeTypes& listTypes, const XMLElement& element ){ + const char* name = element.attribute( "name" ); + m_listType = &listTypes[name]; } - else - { - ERROR_MESSAGE( PARSE_ERROR( element.name(), "list" ) ); - return *this; + TreeXMLImporter& pushElement( const XMLElement& element ){ + if ( isItem( element.name() ) ) { + constructor( m_item.get(), makeReference( *m_listType ), element ); + return m_item.get(); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( element.name(), "list" ) ); + return *this; + } } -} -void popElement( const char* elementName ){ - if ( isItem( elementName ) ) { - destructor( m_item.get() ); + void popElement( const char* elementName ){ + if ( isItem( elementName ) ) { + destructor( m_item.get() ); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( elementName, "list" ) ); + } } - else - { - ERROR_MESSAGE( PARSE_ERROR( elementName, "list" ) ); + std::size_t write( const char* data, std::size_t length ){ + return length; } -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} }; bool classSupported( const char* name ){ return string_equal( name, "group" ) - || string_equal( name, "point" ); + || string_equal( name, "point" ); } bool listSupported( const char* name ){ @@ -417,102 +417,102 @@ bool listSupported( const char* name ){ class ClassesImporter : public TreeXMLImporter { -EntityClassCollector& m_collector; -Storage m_class; -Storage m_list; -ListAttributeTypes m_listTypes; + EntityClassCollector& m_collector; + Storage m_class; + Storage m_list; + ListAttributeTypes m_listTypes; public: -ClassesImporter( EntityClassCollector& collector ) : m_collector( collector ){ -} -static const char* name(){ - return "classes"; -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - if ( classSupported( element.name() ) ) { - constructor( m_class.get(), makeReference( m_collector ), makeReference( m_listTypes ), element ); - return m_class.get(); + ClassesImporter( EntityClassCollector& collector ) : m_collector( collector ){ } - else if ( listSupported( element.name() ) ) { - constructor( m_list.get(), makeReference( m_listTypes ), element ); - return m_list.get(); + static const char* name(){ + return "classes"; } - else - { - ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); - return *this; + TreeXMLImporter& pushElement( const XMLElement& element ){ + if ( classSupported( element.name() ) ) { + constructor( m_class.get(), makeReference( m_collector ), makeReference( m_listTypes ), element ); + return m_class.get(); + } + else if ( listSupported( element.name() ) ) { + constructor( m_list.get(), makeReference( m_listTypes ), element ); + return m_list.get(); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); + return *this; + } } -} -void popElement( const char* elementName ){ - if ( classSupported( elementName ) ) { - destructor( m_class.get() ); + void popElement( const char* elementName ){ + if ( classSupported( elementName ) ) { + destructor( m_class.get() ); + } + else if ( listSupported( elementName ) ) { + destructor( m_list.get() ); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + } } - else if ( listSupported( elementName ) ) { - destructor( m_list.get() ); + std::size_t write( const char* data, std::size_t length ){ + return length; } - else - { - ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); - } -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} }; class EclassXMLImporter : public TreeXMLImporter { -EntityClassCollector& m_collector; -Storage m_classes; + EntityClassCollector& m_collector; + Storage m_classes; public: -EclassXMLImporter( EntityClassCollector& collector ) : m_collector( collector ){ -} -static const char* name(){ - return "classes"; -} -TreeXMLImporter& pushElement( const XMLElement& element ){ - if ( string_equal( element.name(), ClassesImporter::name() ) ) { - constructor( m_classes.get(), makeReference( m_collector ) ); - return m_classes.get(); + EclassXMLImporter( EntityClassCollector& collector ) : m_collector( collector ){ } - else - { - ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); - return *this; + static const char* name(){ + return "classes"; } -} -void popElement( const char* elementName ){ - if ( string_equal( elementName, ClassesImporter::name() ) ) { - destructor( m_classes.get() ); + TreeXMLImporter& pushElement( const XMLElement& element ){ + if ( string_equal( element.name(), ClassesImporter::name() ) ) { + constructor( m_classes.get(), makeReference( m_collector ) ); + return m_classes.get(); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( element.name(), name() ) ); + return *this; + } } - else - { - ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + void popElement( const char* elementName ){ + if ( string_equal( elementName, ClassesImporter::name() ) ) { + destructor( m_classes.get() ); + } + else + { + ERROR_MESSAGE( PARSE_ERROR( elementName, name() ) ); + } + } + std::size_t write( const char* data, std::size_t length ){ + return length; } -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} }; class TreeXMLImporterStack : public XMLImporter { -std::vector< Reference > m_importers; + std::vector< Reference > m_importers; public: -TreeXMLImporterStack( TreeXMLImporter& importer ){ - m_importers.push_back( makeReference( importer ) ); -} -void pushElement( const XMLElement& element ){ - m_importers.push_back( makeReference( m_importers.back().get().pushElement( element ) ) ); -} -void popElement( const char* name ){ - m_importers.pop_back(); - m_importers.back().get().popElement( name ); -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_importers.back().get().write( buffer, length ); -} + TreeXMLImporterStack( TreeXMLImporter& importer ){ + m_importers.push_back( makeReference( importer ) ); + } + void pushElement( const XMLElement& element ){ + m_importers.push_back( makeReference( m_importers.back().get().pushElement( element ) ) ); + } + void popElement( const char* name ){ + m_importers.pop_back(); + m_importers.back().get().popElement( name ); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_importers.back().get().write( buffer, length ); + } }; @@ -542,18 +542,18 @@ class EntityClassXMLDependencies : public GlobalFileSystemModuleRef, public Glob class EclassXMLAPI { -EntityClassScanner m_eclassxml; + EntityClassScanner m_eclassxml; public: -typedef EntityClassScanner Type; -STRING_CONSTANT( Name, "xml" ); + typedef EntityClassScanner Type; + STRING_CONSTANT( Name, "xml" ); -EclassXMLAPI(){ - m_eclassxml.scanFile = &ScanFile; - m_eclassxml.getExtension = &GetExtension; -} -EntityClassScanner* getTable(){ - return &m_eclassxml; -} + EclassXMLAPI(){ + m_eclassxml.scanFile = &ScanFile; + m_eclassxml.getExtension = &GetExtension; + } + EntityClassScanner* getTable(){ + return &m_eclassxml; + } }; typedef SingletonModule EclassXMLModule; diff --git a/radiant/entity.cpp b/radiant/entity.cpp index 1fd7a178..8dd689bb 100644 --- a/radiant/entity.cpp +++ b/radiant/entity.cpp @@ -63,110 +63,110 @@ entity_globals_t g_entity_globals; class EntitySetKeyValueSelected : public scene::Graph::Walker { -const char* m_key; -const char* m_value; + const char* m_key; + const char* m_value; public: -EntitySetKeyValueSelected( const char* key, const char* value ) - : m_key( key ), m_value( value ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 - && ( instance.childSelected() || Instance_isSelected( instance ) ) ) { - entity->setKeyValue( m_key, m_value ); + EntitySetKeyValueSelected( const char* key, const char* value ) + : m_key( key ), m_value( value ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && ( instance.childSelected() || Instance_isSelected( instance ) ) ) { + entity->setKeyValue( m_key, m_value ); + } } -} }; class EntitySetClassnameSelected : public scene::Graph::Walker { -const char* m_classname; -scene::Node* m_world; -const bool m_2world; + const char* m_classname; + scene::Node* m_world; + const bool m_2world; public: -EntitySetClassnameSelected( const char* classname ) - : m_classname( classname ), m_world( Map_FindWorldspawn( g_map ) ), m_2world( m_world && string_equal( m_classname, "worldspawn" ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 && ( instance.childSelected() || Instance_isSelected( instance ) ) ) { - if( path.top().get_pointer() == m_world ){ /* do not want to convert whole worldspawn entity */ - if( instance.childSelected() && !m_2world ){ /* create an entity from world brushes instead */ - EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( m_classname, true ); - if( entityClass->fixedsize ) - return; + EntitySetClassnameSelected( const char* classname ) + : m_classname( classname ), m_world( Map_FindWorldspawn( g_map ) ), m_2world( m_world && string_equal( m_classname, "worldspawn" ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && ( instance.childSelected() || Instance_isSelected( instance ) ) ) { + if( path.top().get_pointer() == m_world ){ /* do not want to convert whole worldspawn entity */ + if( instance.childSelected() && !m_2world ){ /* create an entity from world brushes instead */ + EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( m_classname, true ); + if( entityClass->fixedsize ) + return; - //is important to have retexturing here; if doing in the end, undo doesn't succeed; //don't do this extra now, as it requires retexturing, working for subgraph -// if ( string_compare_nocase_n( m_classname, "trigger_", 8 ) == 0 ){ -// Scene_PatchSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() ); -// Scene_BrushSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() ); -// } + //is important to have retexturing here; if doing in the end, undo doesn't succeed; //don't do this extra now, as it requires retexturing, working for subgraph +// if ( string_compare_nocase_n( m_classname, "trigger_", 8 ) == 0 ){ +// Scene_PatchSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() ); +// Scene_BrushSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() ); +// } - NodeSmartReference node( GlobalEntityCreator().createEntity( entityClass ) ); - Node_getTraversable( GlobalSceneGraph().root() )->insert( node ); + NodeSmartReference node( GlobalEntityCreator().createEntity( entityClass ) ); + Node_getTraversable( GlobalSceneGraph().root() )->insert( node ); - scene::Path entitypath( makeReference( GlobalSceneGraph().root() ) ); - entitypath.push( makeReference( node.get() ) ); - scene::Instance& entityInstance = findInstance( entitypath ); + scene::Path entitypath( makeReference( GlobalSceneGraph().root() ) ); + entitypath.push( makeReference( node.get() ) ); + scene::Instance& entityInstance = findInstance( entitypath ); - if ( g_pGameDescription->mGameType == "doom3" ) { - Node_getEntity( node )->setKeyValue( "model", Node_getEntity( node )->getKeyValue( "name" ) ); + if ( g_pGameDescription->mGameType == "doom3" ) { + Node_getEntity( node )->setKeyValue( "model", Node_getEntity( node )->getKeyValue( "name" ) ); + } + + //Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node ); + Scene_parentSubgraphSelectedBrushesToEntity( GlobalSceneGraph(), node, path ); + Scene_forEachChildSelectable( SelectableSetSelected( true ), entityInstance.path() ); } - - //Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node ); - Scene_parentSubgraphSelectedBrushesToEntity( GlobalSceneGraph(), node, path ); - Scene_forEachChildSelectable( SelectableSetSelected( true ), entityInstance.path() ); + return; } - return; - } - else if( m_2world ){ /* ungroupSelectedEntities */ //condition is skipped with world = 0, so code next to this may create multiple worldspawns; todo handle this very special case? - if( node_is_group( path.top() ) ){ - parentBrushes( path.top(), *m_world ); - Path_deleteTop( path ); + else if( m_2world ){ /* ungroupSelectedEntities */ //condition is skipped with world = 0, so code next to this may create multiple worldspawns; todo handle this very special case? + if( node_is_group( path.top() ) ){ + parentBrushes( path.top(), *m_world ); + Path_deleteTop( path ); + } + return; } - return; - } - EntityClass* eclass = GlobalEntityClassManager().findOrInsert( m_classname, node_is_group( path.top() ) ); - NodeSmartReference node( GlobalEntityCreator().createEntity( eclass ) ); + EntityClass* eclass = GlobalEntityClassManager().findOrInsert( m_classname, node_is_group( path.top() ) ); + NodeSmartReference node( GlobalEntityCreator().createEntity( eclass ) ); - if( entity->isContainer() && eclass->fixedsize ){ /* group entity to point one */ - char value[64]; - sprintf( value, "%g %g %g", instance.worldAABB().origin[0], instance.worldAABB().origin[1], instance.worldAABB().origin[2] ); - entity->setKeyValue( "origin", value ); - } + if( entity->isContainer() && eclass->fixedsize ){ /* group entity to point one */ + char value[64]; + sprintf( value, "%g %g %g", instance.worldAABB().origin[0], instance.worldAABB().origin[1], instance.worldAABB().origin[2] ); + entity->setKeyValue( "origin", value ); + } - EntityCopyingVisitor visitor( *Node_getEntity( node ) ); + EntityCopyingVisitor visitor( *Node_getEntity( node ) ); // entity->forEachKeyValue( visitor ); - NodeSmartReference child( path.top().get() ); - NodeSmartReference parent( path.parent().get() ); + NodeSmartReference child( path.top().get() ); + NodeSmartReference parent( path.parent().get() ); // Node_getTraversable( parent )->erase( child ); - if ( Node_getTraversable( child ) != 0 && node_is_group( node ) ) { /* group entity to group one */ - parentBrushes( child, node ); - } - Node_getTraversable( parent )->insert( node ); - - entity->forEachKeyValue( visitor ); /* must do this after inserting node, otherwise problem: targeted + having model + not loaded b4 new entities aren't selectable normally + rendered only while 0 0 0 is rendered */ - - if( !entity->isContainer() && !eclass->fixedsize ){ /* point entity to group one */ - AABB bounds( g_vector3_identity, Vector3( 16, 16, 16 ) ); - if ( !string_parse_vector3( entity->getKeyValue( "origin" ), bounds.origin ) ) { - bounds.origin = g_vector3_identity; + if ( Node_getTraversable( child ) != 0 && node_is_group( node ) ) { /* group entity to group one */ + parentBrushes( child, node ); } - Brush_ConstructPlacehoderCuboid( node.get(), bounds ); - Node_getEntity( node )->setKeyValue( "origin", "" ); - } + Node_getTraversable( parent )->insert( node ); - Node_getTraversable( parent )->erase( child ); + entity->forEachKeyValue( visitor ); /* must do this after inserting node, otherwise problem: targeted + having model + not loaded b4 new entities aren't selectable normally + rendered only while 0 0 0 is rendered */ + + if( !entity->isContainer() && !eclass->fixedsize ){ /* point entity to group one */ + AABB bounds( g_vector3_identity, Vector3( 16, 16, 16 ) ); + if ( !string_parse_vector3( entity->getKeyValue( "origin" ), bounds.origin ) ) { + bounds.origin = g_vector3_identity; + } + Brush_ConstructPlacehoderCuboid( node.get(), bounds ); + Node_getEntity( node )->setKeyValue( "origin", "" ); + } + + Node_getTraversable( parent )->erase( child ); + } } -} }; void Scene_EntitySetKeyValue_Selected( const char* key, const char* value ){ @@ -207,7 +207,7 @@ void Entity_ungroupSelected(){ } if ( Node_isEntity( path.top() ) - && node_is_group( path.top() ) ) { + && node_is_group( path.top() ) ) { if ( &world != path.top().get_pointer() ) { parentBrushes( path.top(), world ); Path_deleteTop( path ); @@ -220,62 +220,62 @@ void Entity_ungroupSelected(){ class EntityFindSelected : public scene::Graph::Walker { public: -mutable const scene::Path *groupPath; -mutable scene::Instance *groupInstance; -EntityFindSelected() : groupPath( 0 ), groupInstance( 0 ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 - && Instance_isSelected( instance ) - && node_is_group( path.top() ) - && !groupPath ) { - groupPath = &path; - groupInstance = &instance; + mutable const scene::Path *groupPath; + mutable scene::Instance *groupInstance; + EntityFindSelected() : groupPath( 0 ), groupInstance( 0 ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && Instance_isSelected( instance ) + && node_is_group( path.top() ) + && !groupPath ) { + groupPath = &path; + groupInstance = &instance; + } } -} }; class EntityGroupSelected : public scene::Graph::Walker { -NodeSmartReference group, worldspawn; + NodeSmartReference group, worldspawn; //typedef std::pair DeletionPair; //Stack deleteme; public: -EntityGroupSelected( const scene::Path &p ) : group( p.top().get() ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - Entity* entity = Node_getEntity( path.top() ); - if ( entity == 0 && Node_isPrimitive( path.top() ) ) { - NodeSmartReference child( path.top().get() ); - NodeSmartReference parent( path.parent().get() ); + EntityGroupSelected( const scene::Path &p ) : group( p.top().get() ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity == 0 && Node_isPrimitive( path.top() ) ) { + NodeSmartReference child( path.top().get() ); + NodeSmartReference parent( path.parent().get() ); - if ( path.size() >= 3 && parent != worldspawn ) { - NodeSmartReference parentparent( path[path.size() - 3].get() ); + if ( path.size() >= 3 && parent != worldspawn ) { + NodeSmartReference parentparent( path[path.size() - 3].get() ); - Node_getTraversable( parent )->erase( child ); - Node_getTraversable( group )->insert( child ); + Node_getTraversable( parent )->erase( child ); + Node_getTraversable( group )->insert( child ); - if ( Node_getTraversable( parent )->empty() ) { - //deleteme.push(DeletionPair(parentparent, parent)); - Node_getTraversable( parentparent )->erase( parent ); + if ( Node_getTraversable( parent )->empty() ) { + //deleteme.push(DeletionPair(parentparent, parent)); + Node_getTraversable( parentparent )->erase( parent ); + } + } + else + { + Node_getTraversable( parent )->erase( child ); + Node_getTraversable( group )->insert( child ); } - } - else - { - Node_getTraversable( parent )->erase( child ); - Node_getTraversable( group )->insert( child ); } } } -} }; /// moves selected primitives to entity, whose entityNode is selected or to worldspawn, if none void Entity_moveSelectedPrimitives(){ @@ -329,10 +329,10 @@ void Entity_moveSelectedPrimitivesToFirst(){ void Entity_connectSelected(){ if ( GlobalSelectionSystem().countSelected() == 2 ) { GlobalEntityCreator().connectEntities( - GlobalSelectionSystem().penultimateSelected().path(), - GlobalSelectionSystem().ultimateSelected().path(), - 0 - ); + GlobalSelectionSystem().penultimateSelected().path(), + GlobalSelectionSystem().ultimateSelected().path(), + 0 + ); } else { @@ -343,10 +343,10 @@ void Entity_connectSelected(){ void Entity_killconnectSelected(){ if ( GlobalSelectionSystem().countSelected() == 2 ) { GlobalEntityCreator().connectEntities( - GlobalSelectionSystem().penultimateSelected().path(), - GlobalSelectionSystem().ultimateSelected().path(), - 1 - ); + GlobalSelectionSystem().penultimateSelected().path(), + GlobalSelectionSystem().ultimateSelected().path(), + 1 + ); } else { @@ -405,7 +405,7 @@ void Entity_createFromSelection( const char* name, const Vector3& origin ){ EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( name, true ); const bool isModel = entityClass->miscmodel_is - || ( GlobalSelectionSystem().countSelected() == 0 && classname_equal( name, "func_static" ) && g_pGameDescription->mGameType == "doom3" ); + || ( GlobalSelectionSystem().countSelected() == 0 && classname_equal( name, "func_static" ) && g_pGameDescription->mGameType == "doom3" ); const bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0; @@ -464,8 +464,8 @@ void Entity_createFromSelection( const char* name, const Vector3& origin ){ if ( g_pGameDescription->mGameType == "hl" ) { // FIXME - Hydra: really we need a combined light AND color dialog for halflife. if ( string_equal_nocase( name, "light" ) - || string_equal_nocase( name, "light_environment" ) - || string_equal_nocase( name, "light_spot" ) ) { + || string_equal_nocase( name, "light_environment" ) + || string_equal_nocase( name, "light_spot" ) ) { int intensity = g_iLastLightIntensity; if ( DoLightIntensityDlg( &intensity ) == eIDOK ) { @@ -541,8 +541,8 @@ void Entity_normalizeColor(){ char buffer[128]; sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0], - g_entity_globals.color_entity[1], - g_entity_globals.color_entity[2] ); + g_entity_globals.color_entity[1], + g_entity_globals.color_entity[2] ); StringOutputStream command( 256 ); command << "entityNormalizeColour " << buffer; @@ -574,8 +574,8 @@ void Entity_setColour(){ if ( color_dialog( GTK_WIDGET( MainFrame_getWindow() ), g_entity_globals.color_entity ) ) { char buffer[128]; sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0], - g_entity_globals.color_entity[1], - g_entity_globals.color_entity[2] ); + g_entity_globals.color_entity[1], + g_entity_globals.color_entity[2] ); StringOutputStream command( 256 ); command << "entitySetColour " << buffer; @@ -673,16 +673,16 @@ typedef ReferenceCaller1apply(); - return FALSE; -} + static gboolean toggled( GtkWidget *widget, BooleanAttribute* self ){ + self->apply(); + return FALSE; + } public: -BooleanAttribute( const char* key ) : - m_key( key ), - m_check( 0 ){ - GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new() ); - gtk_widget_show( GTK_WIDGET( check ) ); + BooleanAttribute( const char* key ) : + m_key( key ), + m_check( 0 ){ + GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new() ); + gtk_widget_show( GTK_WIDGET( check ) ); - m_check = check; + m_check = check; - guint handler = g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( toggled ), this ); - g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler ) ); + guint handler = g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( toggled ), this ); + g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler ) ); - update(); -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_check ); -} -void release(){ - delete this; -} -void apply(){ - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( m_check ) ) ? "1" : "" ); -} -typedef MemberCaller ApplyCaller; - -void update(){ - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - if ( !string_empty( value ) ) { - toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_check ), atoi( value ) != 0 ); + update(); } - else - { - toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_check ), false ); + GtkWidget* getWidget() const { + return GTK_WIDGET( m_check ); } -} -typedef MemberCaller UpdateCaller; + void release(){ + delete this; + } + void apply(){ + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( m_check ) ) ? "1" : "" ); + } + typedef MemberCaller ApplyCaller; + + void update(){ + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + if ( !string_empty( value ) ) { + toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_check ), atoi( value ) != 0 ); + } + else + { + toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_check ), false ); + } + } + typedef MemberCaller UpdateCaller; }; class StringAttribute : public EntityAttribute { -CopiedString m_key; -GtkEntry* m_entry; -NonModalEntry m_nonModal; + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; public: -StringAttribute( const char* key ) : - m_key( key ), - m_entry( 0 ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ - GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); - gtk_widget_show( GTK_WIDGET( entry ) ); - gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); + StringAttribute( const char* key ) : + m_key( key ), + m_entry( 0 ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ + GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); + gtk_widget_show( GTK_WIDGET( entry ) ); + gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); - m_entry = entry; - m_nonModal.connect( m_entry ); -} -virtual ~StringAttribute() = default; -GtkWidget* getWidget() const { - return GTK_WIDGET( m_entry ); -} -GtkEntry* getEntry() const { - return m_entry; -} + m_entry = entry; + m_nonModal.connect( m_entry ); + } + virtual ~StringAttribute() = default; + GtkWidget* getWidget() const { + return GTK_WIDGET( m_entry ); + } + GtkEntry* getEntry() const { + return m_entry; + } -void release(){ - delete this; -} -void apply(){ - StringOutputStream value( 64 ); - value << gtk_entry_get_text( m_entry ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); -} -typedef MemberCaller ApplyCaller; + void release(){ + delete this; + } + void apply(){ + StringOutputStream value( 64 ); + value << gtk_entry_get_text( m_entry ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); + } + typedef MemberCaller ApplyCaller; -void update(){ - StringOutputStream value( 64 ); - value << SelectedEntity_getValueForKey( m_key.c_str() ); - gtk_entry_set_text( m_entry, value.c_str() ); -} -typedef MemberCaller UpdateCaller; + void update(){ + StringOutputStream value( 64 ); + value << SelectedEntity_getValueForKey( m_key.c_str() ); + gtk_entry_set_text( m_entry, value.c_str() ); + } + typedef MemberCaller UpdateCaller; }; class ShaderAttribute : public StringAttribute { public: -ShaderAttribute( const char* key ) : StringAttribute( key ){ - GlobalShaderEntryCompletion::instance().connect( StringAttribute::getEntry() ); -} + ShaderAttribute( const char* key ) : StringAttribute( key ){ + GlobalShaderEntryCompletion::instance().connect( StringAttribute::getEntry() ); + } }; class TextureAttribute : public StringAttribute { public: -TextureAttribute( const char* key ) : StringAttribute( key ){ - if( string_empty( GlobalRadiant().getGameDescriptionKeyValue( "show_wads" ) ) ) - GlobalAllShadersEntryCompletion::instance().connect( StringAttribute::getEntry() ); // with textures/ - else - GlobalTextureEntryCompletion::instance().connect( StringAttribute::getEntry() ); // w/o -} + TextureAttribute( const char* key ) : StringAttribute( key ){ + if( string_empty( GlobalRadiant().getGameDescriptionKeyValue( "show_wads" ) ) ) + GlobalAllShadersEntryCompletion::instance().connect( StringAttribute::getEntry() ); // with textures/ + else + GlobalTextureEntryCompletion::instance().connect( StringAttribute::getEntry() ); // w/o + } }; class ColorAttribute final : public EntityAttribute { -CopiedString m_key; -BrowsedPathEntry m_entry; -NonModalEntry m_nonModal; + CopiedString m_key; + BrowsedPathEntry m_entry; + NonModalEntry m_nonModal; public: -ColorAttribute( const char* key ) : - m_key( key ), - m_entry( BrowseCaller( *this ) ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ - m_nonModal.connect( m_entry.m_entry.m_entry ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_entry.m_entry.m_frame ); -} -void apply(){ - StringOutputStream value( 64 ); - value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); -} -typedef MemberCaller ApplyCaller; -void update(){ - StringOutputStream value( 64 ); - value << SelectedEntity_getValueForKey( m_key.c_str() ); - gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); -} -typedef MemberCaller UpdateCaller; -void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ /* hijack BrowsedPathEntry to call colour chooser */ - Vector3 color( 1, 1, 1 ); - string_parse_vector3( gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ), color ); - if( color_dialog( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), color ) ){ - char buffer[64]; - sprintf( buffer, "%g %g %g", color[0], color[1], color[2] ); - gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), buffer ); - apply(); + ColorAttribute( const char* key ) : + m_key( key ), + m_entry( BrowseCaller( *this ) ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ + m_nonModal.connect( m_entry.m_entry.m_entry ); } -} -typedef MemberCaller1 BrowseCaller; + void release(){ + delete this; + } + GtkWidget* getWidget() const { + return GTK_WIDGET( m_entry.m_entry.m_frame ); + } + void apply(){ + StringOutputStream value( 64 ); + value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); + } + typedef MemberCaller ApplyCaller; + void update(){ + StringOutputStream value( 64 ); + value << SelectedEntity_getValueForKey( m_key.c_str() ); + gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); + } + typedef MemberCaller UpdateCaller; + void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ /* hijack BrowsedPathEntry to call colour chooser */ + Vector3 color( 1, 1, 1 ); + string_parse_vector3( gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ), color ); + if( color_dialog( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), color ) ){ + char buffer[64]; + sprintf( buffer, "%g %g %g", color[0], color[1], color[2] ); + gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), buffer ); + apply(); + } + } + typedef MemberCaller1 BrowseCaller; }; class ModelAttribute final : public EntityAttribute { -CopiedString m_key; -BrowsedPathEntry m_entry; -NonModalEntry m_nonModal; + CopiedString m_key; + BrowsedPathEntry m_entry; + NonModalEntry m_nonModal; public: -ModelAttribute( const char* key ) : - m_key( key ), - m_entry( BrowseCaller( *this ) ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ - m_nonModal.connect( m_entry.m_entry.m_entry ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_entry.m_entry.m_frame ); -} -void apply(){ - StringOutputStream value( 64 ); - value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); -} -typedef MemberCaller ApplyCaller; -void update(){ - StringOutputStream value( 64 ); - value << SelectedEntity_getValueForKey( m_key.c_str() ); - gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); -} -typedef MemberCaller UpdateCaller; -void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ - const char *filename = misc_model_dialog( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ) ); - - if ( filename != 0 ) { - setPath( filename ); - apply(); + ModelAttribute( const char* key ) : + m_key( key ), + m_entry( BrowseCaller( *this ) ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ + m_nonModal.connect( m_entry.m_entry.m_entry ); } -} -typedef MemberCaller1 BrowseCaller; + void release(){ + delete this; + } + GtkWidget* getWidget() const { + return GTK_WIDGET( m_entry.m_entry.m_frame ); + } + void apply(){ + StringOutputStream value( 64 ); + value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); + } + typedef MemberCaller ApplyCaller; + void update(){ + StringOutputStream value( 64 ); + value << SelectedEntity_getValueForKey( m_key.c_str() ); + gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); + } + typedef MemberCaller UpdateCaller; + void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ + const char *filename = misc_model_dialog( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ) ); + + if ( filename != 0 ) { + setPath( filename ); + apply(); + } + } + typedef MemberCaller1 BrowseCaller; }; const char* browse_sound( GtkWidget* parent, const char* filepath ){ @@ -336,43 +336,43 @@ const char* browse_sound( GtkWidget* parent, const char* filepath ){ class SoundAttribute final : public EntityAttribute { -CopiedString m_key; -BrowsedPathEntry m_entry; -NonModalEntry m_nonModal; + CopiedString m_key; + BrowsedPathEntry m_entry; + NonModalEntry m_nonModal; public: -SoundAttribute( const char* key ) : - m_key( key ), - m_entry( BrowseCaller( *this ) ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ - m_nonModal.connect( m_entry.m_entry.m_entry ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_entry.m_entry.m_frame ); -} -void apply(){ - StringOutputStream value( 64 ); - value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); -} -typedef MemberCaller ApplyCaller; -void update(){ - StringOutputStream value( 64 ); - value << SelectedEntity_getValueForKey( m_key.c_str() ); - gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); -} -typedef MemberCaller UpdateCaller; -void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ - const char *filename = browse_sound( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ) ); - - if ( filename != 0 ) { - setPath( filename ); - apply(); + SoundAttribute( const char* key ) : + m_key( key ), + m_entry( BrowseCaller( *this ) ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ + m_nonModal.connect( m_entry.m_entry.m_entry ); } -} -typedef MemberCaller1 BrowseCaller; + void release(){ + delete this; + } + GtkWidget* getWidget() const { + return GTK_WIDGET( m_entry.m_entry.m_frame ); + } + void apply(){ + StringOutputStream value( 64 ); + value << gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() ); + } + typedef MemberCaller ApplyCaller; + void update(){ + StringOutputStream value( 64 ); + value << SelectedEntity_getValueForKey( m_key.c_str() ); + gtk_entry_set_text( GTK_ENTRY( m_entry.m_entry.m_entry ), value.c_str() ); + } + typedef MemberCaller UpdateCaller; + void browse( const BrowsedPathEntry::SetPathCallback& setPath ){ + const char *filename = browse_sound( gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ), gtk_entry_get_text( GTK_ENTRY( m_entry.m_entry.m_entry ) ) ); + + if ( filename != 0 ) { + setPath( filename ); + apply(); + } + } + typedef MemberCaller1 BrowseCaller; }; @@ -401,56 +401,56 @@ public: class AngleAttribute final : public EntityAttribute { -CopiedString m_key; -GtkEntry* m_entry; -NonModalEntry m_nonModal; -CamAnglesButton m_butt; -GtkBox* m_hbox; + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; + CamAnglesButton m_butt; + GtkBox* m_hbox; public: -AngleAttribute( const char* key ) : - m_key( key ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), - m_butt( ApplyVecCaller( *this ) ){ - m_entry = numeric_entry_new(); - m_nonModal.connect( m_entry ); + AngleAttribute( const char* key ) : + m_key( key ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), + m_butt( ApplyVecCaller( *this ) ){ + m_entry = numeric_entry_new(); + m_nonModal.connect( m_entry ); - m_hbox = GTK_BOX( gtk_hbox_new( FALSE, 4 ) ); - gtk_widget_show( GTK_WIDGET( m_hbox ) ); - gtk_box_pack_start( m_hbox, GTK_WIDGET( m_entry ), TRUE, TRUE, 0 ); - gtk_box_pack_start( m_hbox, GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_hbox ); -} -void apply(){ - StringOutputStream angle( 32 ); - angle << angle_normalised( entry_get_float( m_entry ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() ); -} -typedef MemberCaller ApplyCaller; - -void update(){ - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - if ( !string_empty( value ) ) { + m_hbox = GTK_BOX( gtk_hbox_new( FALSE, 4 ) ); + gtk_widget_show( GTK_WIDGET( m_hbox ) ); + gtk_box_pack_start( m_hbox, GTK_WIDGET( m_entry ), TRUE, TRUE, 0 ); + gtk_box_pack_start( m_hbox, GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); + } + void release(){ + delete this; + } + GtkWidget* getWidget() const { + return GTK_WIDGET( m_hbox ); + } + void apply(){ StringOutputStream angle( 32 ); - angle << angle_normalised( atof( value ) ); - gtk_entry_set_text( m_entry, angle.c_str() ); + angle << angle_normalised( entry_get_float( m_entry ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() ); } - else - { - gtk_entry_set_text( m_entry, "0" ); - } -} -typedef MemberCaller UpdateCaller; + typedef MemberCaller ApplyCaller; -void apply( const Vector3& angles ){ - entry_set_float( m_entry, angles[1] ); - apply(); -} -typedef MemberCaller1 ApplyVecCaller; + void update(){ + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + if ( !string_empty( value ) ) { + StringOutputStream angle( 32 ); + angle << angle_normalised( atof( value ) ); + gtk_entry_set_text( m_entry, angle.c_str() ); + } + else + { + gtk_entry_set_text( m_entry, "0" ); + } + } + typedef MemberCaller UpdateCaller; + + void apply( const Vector3& angles ){ + entry_set_float( m_entry, angles[1] ); + apply(); + } + typedef MemberCaller1 ApplyVecCaller; }; namespace @@ -461,353 +461,353 @@ const String buttons[] = { "up", "down", "yaw" }; class DirectionAttribute final : public EntityAttribute { -CopiedString m_key; -GtkEntry* m_entry; -NonModalEntry m_nonModal; -RadioHBox m_radio; -NonModalRadio m_nonModalRadio; -CamAnglesButton m_butt; -GtkHBox* m_hbox; + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; + RadioHBox m_radio; + NonModalRadio m_nonModalRadio; + CamAnglesButton m_butt; + GtkHBox* m_hbox; public: -DirectionAttribute( const char* key ) : - m_key( key ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), - m_radio( RadioHBox_new( STRING_ARRAY_RANGE( buttons ) ) ), - m_nonModalRadio( ApplyRadioCaller( *this ) ), - m_butt( ApplyVecCaller( *this ) ){ - m_entry = numeric_entry_new(); - m_nonModal.connect( m_entry ); + DirectionAttribute( const char* key ) : + m_key( key ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), + m_radio( RadioHBox_new( STRING_ARRAY_RANGE( buttons ) ) ), + m_nonModalRadio( ApplyRadioCaller( *this ) ), + m_butt( ApplyVecCaller( *this ) ){ + m_entry = numeric_entry_new(); + m_nonModal.connect( m_entry ); - m_nonModalRadio.connect( m_radio.m_radio ); + m_nonModalRadio.connect( m_radio.m_radio ); - m_hbox = GTK_HBOX( gtk_hbox_new( FALSE, 4 ) ); - gtk_widget_show( GTK_WIDGET( m_hbox ) ); + m_hbox = GTK_HBOX( gtk_hbox_new( FALSE, 4 ) ); + gtk_widget_show( GTK_WIDGET( m_hbox ) ); - gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_radio.m_hbox ), TRUE, TRUE, 0 ); - gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_entry ), TRUE, TRUE, 0 ); - gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_hbox ); -} -void apply(){ - StringOutputStream angle( 32 ); - angle << angle_normalised( entry_get_float( m_entry ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() ); -} -typedef MemberCaller ApplyCaller; + gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_radio.m_hbox ), TRUE, TRUE, 0 ); + gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_entry ), TRUE, TRUE, 0 ); + gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); + } + void release(){ + delete this; + } + GtkWidget* getWidget() const { + return GTK_WIDGET( m_hbox ); + } + void apply(){ + StringOutputStream angle( 32 ); + angle << angle_normalised( entry_get_float( m_entry ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() ); + } + typedef MemberCaller ApplyCaller; -void update(){ - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - if ( !string_empty( value ) ) { - float f = float(atof( value ) ); - if ( f == -1 ) { - gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE ); - radio_button_set_active_no_signal( m_radio.m_radio, 0 ); - gtk_entry_set_text( m_entry, "" ); - } - else if ( f == -2 ) { - gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE ); - radio_button_set_active_no_signal( m_radio.m_radio, 1 ); - gtk_entry_set_text( m_entry, "" ); + void update(){ + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + if ( !string_empty( value ) ) { + float f = float(atof( value ) ); + if ( f == -1 ) { + gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE ); + radio_button_set_active_no_signal( m_radio.m_radio, 0 ); + gtk_entry_set_text( m_entry, "" ); + } + else if ( f == -2 ) { + gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE ); + radio_button_set_active_no_signal( m_radio.m_radio, 1 ); + gtk_entry_set_text( m_entry, "" ); + } + else + { + gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), TRUE ); + radio_button_set_active_no_signal( m_radio.m_radio, 2 ); + StringOutputStream angle( 32 ); + angle << angle_normalised( f ); + gtk_entry_set_text( m_entry, angle.c_str() ); + } } else { - gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), TRUE ); radio_button_set_active_no_signal( m_radio.m_radio, 2 ); - StringOutputStream angle( 32 ); - angle << angle_normalised( f ); - gtk_entry_set_text( m_entry, angle.c_str() ); + gtk_entry_set_text( m_entry, "0" ); } } - else - { - radio_button_set_active_no_signal( m_radio.m_radio, 2 ); - gtk_entry_set_text( m_entry, "0" ); - } -} -typedef MemberCaller UpdateCaller; + typedef MemberCaller UpdateCaller; -void applyRadio(){ - int index = radio_button_get_active( m_radio.m_radio ); - if ( index == 0 ) { - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-1" ); + void applyRadio(){ + int index = radio_button_get_active( m_radio.m_radio ); + if ( index == 0 ) { + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-1" ); + } + else if ( index == 1 ) { + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-2" ); + } + else if ( index == 2 ) { + apply(); + } } - else if ( index == 1 ) { - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-2" ); - } - else if ( index == 2 ) { + typedef MemberCaller ApplyRadioCaller; + + void apply( const Vector3& angles ){ + entry_set_float( m_entry, angles[1] ); apply(); } -} -typedef MemberCaller ApplyRadioCaller; - -void apply( const Vector3& angles ){ - entry_set_float( m_entry, angles[1] ); - apply(); -} -typedef MemberCaller1 ApplyVecCaller; + typedef MemberCaller1 ApplyVecCaller; }; class AnglesEntry { public: -GtkEntry* m_roll; -GtkEntry* m_pitch; -GtkEntry* m_yaw; -AnglesEntry() : m_roll( 0 ), m_pitch( 0 ), m_yaw( 0 ){ -} + GtkEntry* m_roll; + GtkEntry* m_pitch; + GtkEntry* m_yaw; + AnglesEntry() : m_roll( 0 ), m_pitch( 0 ), m_yaw( 0 ){ + } }; class AnglesAttribute final : public EntityAttribute { -CopiedString m_key; -AnglesEntry m_angles; -NonModalEntry m_nonModal; -CamAnglesButton m_butt; -GtkBox* m_hbox; + CopiedString m_key; + AnglesEntry m_angles; + NonModalEntry m_nonModal; + CamAnglesButton m_butt; + GtkBox* m_hbox; public: -AnglesAttribute( const char* key ) : - m_key( key ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), - m_butt( ApplyVecCaller( *this ) ){ - m_hbox = GTK_BOX( gtk_hbox_new( FALSE, 4 ) ); - gtk_widget_show( GTK_WIDGET( m_hbox ) ); - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_angles.m_pitch = entry; - m_nonModal.connect( m_angles.m_pitch ); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_angles.m_yaw = entry; - m_nonModal.connect( m_angles.m_yaw ); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_angles.m_roll = entry; - m_nonModal.connect( m_angles.m_roll ); - } - gtk_box_pack_start( m_hbox, GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_hbox ); -} -void apply(){ - StringOutputStream angles( 64 ); - angles << angle_normalised( entry_get_float( m_angles.m_pitch ) ) - << " " << angle_normalised( entry_get_float( m_angles.m_yaw ) ) - << " " << angle_normalised( entry_get_float( m_angles.m_roll ) ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angles.c_str() ); -} -typedef MemberCaller ApplyCaller; - -void update(){ - StringOutputStream angle( 32 ); - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - if ( !string_empty( value ) ) { - DoubleVector3 pitch_yaw_roll; - if ( !string_parse_vector3( value, pitch_yaw_roll ) ) { - pitch_yaw_roll = DoubleVector3( 0, 0, 0 ); + AnglesAttribute( const char* key ) : + m_key( key ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ), + m_butt( ApplyVecCaller( *this ) ){ + m_hbox = GTK_BOX( gtk_hbox_new( FALSE, 4 ) ); + gtk_widget_show( GTK_WIDGET( m_hbox ) ); + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_angles.m_pitch = entry; + m_nonModal.connect( m_angles.m_pitch ); } - - angle << angle_normalised( pitch_yaw_roll.x() ); - gtk_entry_set_text( m_angles.m_pitch, angle.c_str() ); - angle.clear(); - - angle << angle_normalised( pitch_yaw_roll.y() ); - gtk_entry_set_text( m_angles.m_yaw, angle.c_str() ); - angle.clear(); - - angle << angle_normalised( pitch_yaw_roll.z() ); - gtk_entry_set_text( m_angles.m_roll, angle.c_str() ); - angle.clear(); + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_angles.m_yaw = entry; + m_nonModal.connect( m_angles.m_yaw ); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_angles.m_roll = entry; + m_nonModal.connect( m_angles.m_roll ); + } + gtk_box_pack_start( m_hbox, GTK_WIDGET( m_butt.m_button ), FALSE, FALSE, 0 ); } - else - { - gtk_entry_set_text( m_angles.m_pitch, "0" ); - gtk_entry_set_text( m_angles.m_yaw, "0" ); - gtk_entry_set_text( m_angles.m_roll, "0" ); + void release(){ + delete this; } -} -typedef MemberCaller UpdateCaller; + GtkWidget* getWidget() const { + return GTK_WIDGET( m_hbox ); + } + void apply(){ + StringOutputStream angles( 64 ); + angles << angle_normalised( entry_get_float( m_angles.m_pitch ) ) + << " " << angle_normalised( entry_get_float( m_angles.m_yaw ) ) + << " " << angle_normalised( entry_get_float( m_angles.m_roll ) ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angles.c_str() ); + } + typedef MemberCaller ApplyCaller; -void apply( const Vector3& angles ){ - entry_set_float( m_angles.m_pitch, angles[0] ); - entry_set_float( m_angles.m_yaw, angles[1] ); - entry_set_float( m_angles.m_roll, 0 ); - apply(); -} -typedef MemberCaller1 ApplyVecCaller; + void update(){ + StringOutputStream angle( 32 ); + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + if ( !string_empty( value ) ) { + DoubleVector3 pitch_yaw_roll; + if ( !string_parse_vector3( value, pitch_yaw_roll ) ) { + pitch_yaw_roll = DoubleVector3( 0, 0, 0 ); + } + + angle << angle_normalised( pitch_yaw_roll.x() ); + gtk_entry_set_text( m_angles.m_pitch, angle.c_str() ); + angle.clear(); + + angle << angle_normalised( pitch_yaw_roll.y() ); + gtk_entry_set_text( m_angles.m_yaw, angle.c_str() ); + angle.clear(); + + angle << angle_normalised( pitch_yaw_roll.z() ); + gtk_entry_set_text( m_angles.m_roll, angle.c_str() ); + angle.clear(); + } + else + { + gtk_entry_set_text( m_angles.m_pitch, "0" ); + gtk_entry_set_text( m_angles.m_yaw, "0" ); + gtk_entry_set_text( m_angles.m_roll, "0" ); + } + } + typedef MemberCaller UpdateCaller; + + void apply( const Vector3& angles ){ + entry_set_float( m_angles.m_pitch, angles[0] ); + entry_set_float( m_angles.m_yaw, angles[1] ); + entry_set_float( m_angles.m_roll, 0 ); + apply(); + } + typedef MemberCaller1 ApplyVecCaller; }; class Vector3Entry { public: -GtkEntry* m_x; -GtkEntry* m_y; -GtkEntry* m_z; -Vector3Entry() : m_x( 0 ), m_y( 0 ), m_z( 0 ){ -} + GtkEntry* m_x; + GtkEntry* m_y; + GtkEntry* m_z; + Vector3Entry() : m_x( 0 ), m_y( 0 ), m_z( 0 ){ + } }; class Vector3Attribute final : public EntityAttribute { -CopiedString m_key; -Vector3Entry m_vector3; -NonModalEntry m_nonModal; -GtkBox* m_hbox; + CopiedString m_key; + Vector3Entry m_vector3; + NonModalEntry m_nonModal; + GtkBox* m_hbox; public: -Vector3Attribute( const char* key ) : - m_key( key ), - m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ - m_hbox = GTK_BOX( gtk_hbox_new( TRUE, 4 ) ); - gtk_widget_show( GTK_WIDGET( m_hbox ) ); - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_vector3.m_x = entry; - m_nonModal.connect( m_vector3.m_x ); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_vector3.m_y = entry; - m_nonModal.connect( m_vector3.m_y ); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - m_vector3.m_z = entry; - m_nonModal.connect( m_vector3.m_z ); - } -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_hbox ); -} -void apply(){ - StringOutputStream vector3( 64 ); - vector3 << entry_get_float( m_vector3.m_x ) - << " " << entry_get_float( m_vector3.m_y ) - << " " << entry_get_float( m_vector3.m_z ); - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), vector3.c_str() ); -} -typedef MemberCaller ApplyCaller; - -void update(){ - StringOutputStream buffer( 32 ); - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - if ( !string_empty( value ) ) { - DoubleVector3 x_y_z; - if ( !string_parse_vector3( value, x_y_z ) ) { - x_y_z = DoubleVector3( 0, 0, 0 ); + Vector3Attribute( const char* key ) : + m_key( key ), + m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){ + m_hbox = GTK_BOX( gtk_hbox_new( TRUE, 4 ) ); + gtk_widget_show( GTK_WIDGET( m_hbox ) ); + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_vector3.m_x = entry; + m_nonModal.connect( m_vector3.m_x ); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_vector3.m_y = entry; + m_nonModal.connect( m_vector3.m_y ); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 ); + m_vector3.m_z = entry; + m_nonModal.connect( m_vector3.m_z ); } - - buffer << x_y_z.x(); - gtk_entry_set_text( m_vector3.m_x, buffer.c_str() ); - buffer.clear(); - - buffer << x_y_z.y(); - gtk_entry_set_text( m_vector3.m_y, buffer.c_str() ); - buffer.clear(); - - buffer << x_y_z.z(); - gtk_entry_set_text( m_vector3.m_z, buffer.c_str() ); - buffer.clear(); } - else - { - gtk_entry_set_text( m_vector3.m_x, "0" ); - gtk_entry_set_text( m_vector3.m_y, "0" ); - gtk_entry_set_text( m_vector3.m_z, "0" ); + void release(){ + delete this; } -} -typedef MemberCaller UpdateCaller; + GtkWidget* getWidget() const { + return GTK_WIDGET( m_hbox ); + } + void apply(){ + StringOutputStream vector3( 64 ); + vector3 << entry_get_float( m_vector3.m_x ) + << " " << entry_get_float( m_vector3.m_y ) + << " " << entry_get_float( m_vector3.m_z ); + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), vector3.c_str() ); + } + typedef MemberCaller ApplyCaller; + + void update(){ + StringOutputStream buffer( 32 ); + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + if ( !string_empty( value ) ) { + DoubleVector3 x_y_z; + if ( !string_parse_vector3( value, x_y_z ) ) { + x_y_z = DoubleVector3( 0, 0, 0 ); + } + + buffer << x_y_z.x(); + gtk_entry_set_text( m_vector3.m_x, buffer.c_str() ); + buffer.clear(); + + buffer << x_y_z.y(); + gtk_entry_set_text( m_vector3.m_y, buffer.c_str() ); + buffer.clear(); + + buffer << x_y_z.z(); + gtk_entry_set_text( m_vector3.m_z, buffer.c_str() ); + buffer.clear(); + } + else + { + gtk_entry_set_text( m_vector3.m_x, "0" ); + gtk_entry_set_text( m_vector3.m_y, "0" ); + gtk_entry_set_text( m_vector3.m_z, "0" ); + } + } + typedef MemberCaller UpdateCaller; }; class NonModalComboBox { -Callback m_changed; -guint m_changedHandler; + Callback m_changed; + guint m_changedHandler; -static gboolean changed( GtkComboBox *widget, NonModalComboBox* self ){ - self->m_changed(); - return FALSE; -} + static gboolean changed( GtkComboBox *widget, NonModalComboBox* self ){ + self->m_changed(); + return FALSE; + } public: -NonModalComboBox( const Callback& changed ) : m_changed( changed ), m_changedHandler( 0 ){ -} -void connect( GtkComboBox* combo ){ - m_changedHandler = g_signal_connect( G_OBJECT( combo ), "changed", G_CALLBACK( changed ), this ); -} -void setActive( GtkComboBox* combo, int value ){ - g_signal_handler_disconnect( G_OBJECT( combo ), m_changedHandler ); - gtk_combo_box_set_active( combo, value ); - connect( combo ); -} + NonModalComboBox( const Callback& changed ) : m_changed( changed ), m_changedHandler( 0 ){ + } + void connect( GtkComboBox* combo ){ + m_changedHandler = g_signal_connect( G_OBJECT( combo ), "changed", G_CALLBACK( changed ), this ); + } + void setActive( GtkComboBox* combo, int value ){ + g_signal_handler_disconnect( G_OBJECT( combo ), m_changedHandler ); + gtk_combo_box_set_active( combo, value ); + connect( combo ); + } }; class ListAttribute final : public EntityAttribute { -CopiedString m_key; -GtkComboBox* m_combo; -NonModalComboBox m_nonModal; -const ListAttributeType& m_type; + CopiedString m_key; + GtkComboBox* m_combo; + NonModalComboBox m_nonModal; + const ListAttributeType& m_type; public: -ListAttribute( const char* key, const ListAttributeType& type ) : - m_key( key ), - m_combo( 0 ), - m_nonModal( ApplyCaller( *this ) ), - m_type( type ){ - GtkWidget* combo = gtk_combo_box_text_new(); + ListAttribute( const char* key, const ListAttributeType& type ) : + m_key( key ), + m_combo( 0 ), + m_nonModal( ApplyCaller( *this ) ), + m_type( type ){ + GtkWidget* combo = gtk_combo_box_text_new(); - for ( ListAttributeType::const_iterator i = type.begin(); i != type.end(); ++i ) - { - gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( combo ), ( *i ).first.c_str() ); + for ( ListAttributeType::const_iterator i = type.begin(); i != type.end(); ++i ) + { + gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( combo ), ( *i ).first.c_str() ); + } + + gtk_widget_show( combo ); + m_nonModal.connect( GTK_COMBO_BOX( combo ) ); + + m_combo = GTK_COMBO_BOX( combo ); } - - gtk_widget_show( combo ); - m_nonModal.connect( GTK_COMBO_BOX( combo ) ); - - m_combo = GTK_COMBO_BOX( combo ); -} -void release(){ - delete this; -} -GtkWidget* getWidget() const { - return GTK_WIDGET( m_combo ); -} -void apply(){ - Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), m_type[gtk_combo_box_get_active( m_combo )].second.c_str() ); -} -typedef MemberCaller ApplyCaller; - -void update(){ - const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); - ListAttributeType::const_iterator i = m_type.findValue( value ); - if ( i != m_type.end() ) { - m_nonModal.setActive( m_combo, static_cast( std::distance( m_type.begin(), i ) ) ); + void release(){ + delete this; } - else - { - m_nonModal.setActive( m_combo, 0 ); + GtkWidget* getWidget() const { + return GTK_WIDGET( m_combo ); } -} -typedef MemberCaller UpdateCaller; + void apply(){ + Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), m_type[gtk_combo_box_get_active( m_combo )].second.c_str() ); + } + typedef MemberCaller ApplyCaller; + + void update(){ + const char* value = SelectedEntity_getValueForKey( m_key.c_str() ); + ListAttributeType::const_iterator i = m_type.findValue( value ); + if ( i != m_type.end() ) { + m_nonModal.setActive( m_combo, static_cast( std::distance( m_type.begin(), i ) ) ); + } + else + { + m_nonModal.setActive( m_combo, 0 ); + } + } + typedef MemberCaller UpdateCaller; }; @@ -861,15 +861,15 @@ void GlobalEntityAttributes_clear(){ class GetKeyValueVisitor : public Entity::Visitor { -KeyValues& m_keyvalues; + KeyValues& m_keyvalues; public: -GetKeyValueVisitor( KeyValues& keyvalues ) - : m_keyvalues( keyvalues ){ -} + GetKeyValueVisitor( KeyValues& keyvalues ) + : m_keyvalues( keyvalues ){ + } -void visit( const char* key, const char* value ){ - m_keyvalues.insert( KeyValues::value_type( CopiedString( key ), CopiedString( value ) ) ); -} + void visit( const char* key, const char* value ){ + m_keyvalues.insert( KeyValues::value_type( CopiedString( key ), CopiedString( value ) ) ); + } }; @@ -889,22 +889,22 @@ void Entity_GetKeyValues( const Entity& entity, KeyValues& keyvalues, KeyValues& void Entity_GetKeyValues_Selected( KeyValues& keyvalues, KeyValues& defaultValues ){ class EntityGetKeyValues : public SelectionSystem::Visitor { - KeyValues& m_keyvalues; - KeyValues& m_defaultValues; - mutable std::set m_visited; -public: - EntityGetKeyValues( KeyValues& keyvalues, KeyValues& defaultValues ) - : m_keyvalues( keyvalues ), m_defaultValues( defaultValues ){ - } - void visit( scene::Instance& instance ) const { - Entity* entity = Node_getEntity( instance.path().top() ); - if ( entity == 0 && instance.path().size() != 1 ) { - entity = Node_getEntity( instance.path().parent() ); + KeyValues& m_keyvalues; + KeyValues& m_defaultValues; + mutable std::set m_visited; + public: + EntityGetKeyValues( KeyValues& keyvalues, KeyValues& defaultValues ) + : m_keyvalues( keyvalues ), m_defaultValues( defaultValues ){ } - if ( entity != 0 && m_visited.insert( entity ).second ) { - Entity_GetKeyValues( *entity, m_keyvalues, m_defaultValues ); + void visit( scene::Instance& instance ) const { + Entity* entity = Node_getEntity( instance.path().top() ); + if ( entity == 0 && instance.path().size() != 1 ) { + entity = Node_getEntity( instance.path().parent() ); + } + if ( entity != 0 && m_visited.insert( entity ).second ) { + Entity_GetKeyValues( *entity, m_keyvalues, m_defaultValues ); + } } - } } visitor( keyvalues, defaultValues ); GlobalSelectionSystem().foreachSelected( visitor ); } @@ -919,15 +919,15 @@ const char* keyvalues_valueforkey( KeyValues& keyvalues, const char* key ){ class EntityClassListStoreAppend : public EntityClassVisitor { -GtkListStore* store; + GtkListStore* store; public: -EntityClassListStoreAppend( GtkListStore* store_ ) : store( store_ ){ -} -void visit( EntityClass* e ){ - GtkTreeIter iter; - gtk_list_store_append( store, &iter ); - gtk_list_store_set( store, &iter, 0, e->name(), 1, e, -1 ); -} + EntityClassListStoreAppend( GtkListStore* store_ ) : store( store_ ){ + } + void visit( EntityClass* e ){ + GtkTreeIter iter; + gtk_list_store_append( store, &iter ); + gtk_list_store_set( store, &iter, 0, e->name(), 1, e, -1 ); + } }; void EntityClassList_fill(){ @@ -1042,8 +1042,8 @@ void SurfaceFlags_setEntityClass( EntityClass* eclass ){ str << LowerCase( eclass->flagnames[spawn_table[i]] ); gtk_table_attach( g_spawnflagsTable, widget, i % 4, i % 4 + 1, i / 4, i / 4 + 1, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( GTK_FILL ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( GTK_FILL ), 0, 0 ); g_object_unref( G_OBJECT( widget ) ); gtk_label_set_text( GTK_LABEL( gtk_bin_get_child( GTK_BIN( widget ) ) ), str.c_str() ); @@ -1088,48 +1088,48 @@ template class StatelessAttributeCreator { public: -static EntityAttribute* create( const char* name ){ - return new Attribute( name ); -} + static EntityAttribute* create( const char* name ){ + return new Attribute( name ); + } }; class EntityAttributeFactory { -typedef EntityAttribute* ( *CreateFunc )( const char* name ); -typedef std::map Creators; -Creators m_creators; + typedef EntityAttribute* ( *CreateFunc )( const char* name ); + typedef std::map Creators; + Creators m_creators; public: -EntityAttributeFactory(){ - m_creators.insert( Creators::value_type( "string", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "array", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "integer", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "boolean", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "real", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "angle", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "direction", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "vector3", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "real3", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "angles", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "color", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "target", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "targetname", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "sound", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "shader", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "texture", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "model", &StatelessAttributeCreator::create ) ); - m_creators.insert( Creators::value_type( "skin", &StatelessAttributeCreator::create ) ); -} -EntityAttribute* create( const char* type, const char* name ){ - Creators::iterator i = m_creators.find( type ); - if ( i != m_creators.end() ) { - return ( *i ).second( name ); + EntityAttributeFactory(){ + m_creators.insert( Creators::value_type( "string", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "array", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "integer", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "boolean", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "real", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "angle", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "direction", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "vector3", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "real3", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "angles", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "color", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "target", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "targetname", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "sound", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "shader", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "texture", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "model", &StatelessAttributeCreator::create ) ); + m_creators.insert( Creators::value_type( "skin", &StatelessAttributeCreator::create ) ); } - const ListAttributeType* listType = GlobalEntityClassManager().findListType( type ); - if ( listType != 0 ) { - return new ListAttribute( name, *listType ); + EntityAttribute* create( const char* type, const char* name ){ + Creators::iterator i = m_creators.find( type ); + if ( i != m_creators.end() ) { + return ( *i ).second( name ); + } + const ListAttributeType* listType = GlobalEntityClassManager().findListType( type ); + if ( listType != 0 ) { + return new ListAttribute( name, *listType ); + } + return 0; } - return 0; -} }; typedef Static GlobalEntityAttributeFactory; @@ -1238,13 +1238,13 @@ void EntityInspector_updateKeyValues(){ class EntityInspectorDraw { -IdleDraw m_idleDraw; + IdleDraw m_idleDraw; public: -EntityInspectorDraw() : m_idleDraw( FreeCaller( ) ){ -} -void queueDraw(){ - m_idleDraw.queueDraw(); -} + EntityInspectorDraw() : m_idleDraw( FreeCaller( ) ){ + } + void queueDraw(){ + m_idleDraw.queueDraw(); + } }; EntityInspectorDraw g_EntityInspectorDraw; @@ -1689,8 +1689,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_events( GTK_WIDGET( entry ), GDK_KEY_PRESS_MASK ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( EntityEntry_keypress ), 0 ); g_entityKeyEntry = entry; @@ -1700,8 +1700,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_events( GTK_WIDGET( entry ), GDK_KEY_PRESS_MASK ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( EntityEntry_keypress ), 0 ); g_entityValueEntry = entry; @@ -1711,8 +1711,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Value" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } @@ -1720,16 +1720,16 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Key" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } /* select by key/value buttons */ GtkTable* tab = GTK_TABLE( gtk_table_new( 2, 2, FALSE ) ); gtk_table_attach( table, GTK_WIDGET( tab ), 2, 3, 0, 2, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); table = tab; gtk_widget_show( GTK_WIDGET( table ) ); gtk_table_set_row_spacings( table, 0 ); @@ -1741,8 +1741,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ gtk_widget_set_tooltip_text( button, "Select by key" ); gtk_widget_show( button ); gtk_table_attach( table, button, 0, 1, 0, 1, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( EntityInspector_selectByKey ), 0 ); } { @@ -1752,8 +1752,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ gtk_widget_set_tooltip_text( button, "Select by value" ); gtk_widget_show( button ); gtk_table_attach( table, button, 0, 1, 1, 2, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( EntityInspector_selectByValue ), 0 ); } { @@ -1763,8 +1763,8 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ gtk_widget_set_tooltip_text( button, "Select by key + value" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 0, 2, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( GTK_FILL ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( GTK_FILL ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( EntityInspector_selectByKeyValue ), 0 ); } } @@ -1875,26 +1875,26 @@ GtkWidget* EntityInspector_constructWindow( GtkWindow* toplevel ){ class EntityInspector : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -EntityInspector() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - if ( g_entityInspector_windowConstructed ) { - //globalOutputStream() << "Entity Inspector: realise\n"; - EntityClassList_fill(); + EntityInspector() : m_unrealised( 1 ){ + } + void realise(){ + if ( --m_unrealised == 0 ) { + if ( g_entityInspector_windowConstructed ) { + //globalOutputStream() << "Entity Inspector: realise\n"; + EntityClassList_fill(); + } } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - if ( g_entityInspector_windowConstructed ) { - //globalOutputStream() << "Entity Inspector: unrealise\n"; - EntityClassList_clear(); + void unrealise(){ + if ( ++m_unrealised == 1 ) { + if ( g_entityInspector_windowConstructed ) { + //globalOutputStream() << "Entity Inspector: unrealise\n"; + EntityClassList_clear(); + } } } -} }; EntityInspector g_EntityInspector; diff --git a/radiant/entitylist.cpp b/radiant/entitylist.cpp index edf38a12..10bb61e5 100644 --- a/radiant/entitylist.cpp +++ b/radiant/entitylist.cpp @@ -49,40 +49,40 @@ typedef struct _GtkTreeView GtkTreeView; class EntityList { public: -enum EDirty -{ - eDefault, - eSelection, - eInsertRemove, -}; + enum EDirty + { + eDefault, + eSelection, + eInsertRemove, + }; -EDirty m_dirty; + EDirty m_dirty; -IdleDraw m_idleDraw; -WindowPositionTracker m_positionTracker; + IdleDraw m_idleDraw; + WindowPositionTracker m_positionTracker; -GtkWindow* m_window; -GtkWidget* m_check; -GtkTreeView* m_tree_view; -GraphTreeModel* m_tree_model; -bool m_selection_disabled; + GtkWindow* m_window; + GtkWidget* m_check; + GtkTreeView* m_tree_view; + GraphTreeModel* m_tree_model; + bool m_selection_disabled; -bool m_search_from_start; -scene::Node* m_search_focus_node; + bool m_search_from_start; + scene::Node* m_search_focus_node; -EntityList() : - m_dirty( EntityList::eDefault ), - m_idleDraw( RedrawEntityListCaller() ), - m_window( 0 ), - m_selection_disabled( false ), - m_search_from_start( false ), - m_search_focus_node( 0 ){ + EntityList() : + m_dirty( EntityList::eDefault ), + m_idleDraw( RedrawEntityListCaller() ), + m_window( 0 ), + m_selection_disabled( false ), + m_search_from_start( false ), + m_search_focus_node( 0 ){ m_positionTracker.setPosition( WindowPosition( -1, -1, 350, 500 ) ); -} + } -bool visible() const { - return gtk_widget_get_visible( GTK_WIDGET( m_window ) ); -} + bool visible() const { + return gtk_widget_get_visible( GTK_WIDGET( m_window ) ); + } }; namespace @@ -103,8 +103,8 @@ inline Nameable* Node_getNameable( scene::Node& node ){ const char* node_get_name( scene::Node& node ){ Nameable* nameable = Node_getNameable( node ); return ( nameable != 0 ) - ? nameable->name() - : "node"; + ? nameable->name() + : "node"; } template @@ -293,7 +293,11 @@ static gboolean tree_view_search_equal_func( GtkTreeModel* model, gint column, c scene::Node* node; gtk_tree_model_get( model, iter, column, (gpointer*)&node, -1 ); /* return FALSE means match */ - return ( node && !node->isRoot() )? *(bool*)search_from_start? !string_equal_prefix_nocase( node_get_name( *node ), key ) : !string_in_string_nocase( node_get_name( *node ), key ) : TRUE; + return ( node && !node->isRoot() ) + ? *(bool*)search_from_start + ? !string_equal_prefix_nocase( node_get_name( *node ), key ) + : !string_in_string_nocase( node_get_name( *node ), key ) + : TRUE; } void searchEntrySetModeIcon( GtkEntry* entry, bool search_from_start ){ @@ -480,7 +484,7 @@ void EntityList_constructWindow( GtkWindow* main_window ){ getEntityList().m_check = check; g_signal_connect( G_OBJECT( check ), "clicked", G_CALLBACK( entitylist_focusSelected ), 0 ); } - {//search entry + { //search entry GtkWidget* entry = gtk_entry_new(); gtk_box_pack_start( GTK_BOX( hbox ), entry, TRUE, TRUE, 8 ); searchEntrySetModeIcon( GTK_ENTRY( entry ), getEntityList().m_search_from_start ); @@ -518,30 +522,30 @@ scene::Node* nullNode = 0; class NullSelectedInstance : public scene::Instance, public Selectable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceStaticCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceStaticCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -NullSelectedInstance() : Instance( scene::Path( makeReference( *nullNode ) ), 0, this, StaticTypeCasts::instance().get() ){ -} + NullSelectedInstance() : Instance( scene::Path( makeReference( *nullNode ) ), 0, this, StaticTypeCasts::instance().get() ){ + } -void setSelected( bool select ){ - ERROR_MESSAGE( "error" ); -} -bool isSelected() const { - return true; -} + void setSelected( bool select ){ + ERROR_MESSAGE( "error" ); + } + bool isSelected() const { + return true; + } }; typedef LazyStatic StaticNullSelectedInstance; diff --git a/radiant/environment.cpp b/radiant/environment.cpp index 3a780bc9..c5b0e5dc 100644 --- a/radiant/environment.cpp +++ b/radiant/environment.cpp @@ -140,7 +140,9 @@ void gamedetect(){ #else if ( gamedetect_check_game( "nexuiz.game", "data/common-spog.pk3", "nexuiz-linux-glx.sh", buf, p - buf ) ) #endif - { return; } + { + return; + } // try to detect Q2World installs if ( gamedetect_check_game( "q2w.game", "default/quake2world.version", NULL, buf, p - buf ) ) { @@ -213,11 +215,11 @@ void cmdMap(){ const char* LINK_NAME = #if defined ( __linux__ ) - "/proc/self/exe" + "/proc/self/exe" #else // FreeBSD and OSX - "/proc/curproc/file" + "/proc/curproc/file" #endif -; + ; /// brief Returns the filename of the executable belonging to the current process, or empty string, if not found. const char* getexename( char *buf ){ @@ -243,7 +245,7 @@ void environment_init( int argc, char* argv[] ){ struct passwd *pw; seteuid( getuid() ); if ( geteuid() == 0 && ( loginname = getlogin() ) != 0 && - ( pw = getpwnam( loginname ) ) != 0 ) { + ( pw = getpwnam( loginname ) ) != 0 ) { setuid( pw->pw_uid ); } @@ -287,7 +289,7 @@ void environment_init( int argc, char* argv[] ){ StringOutputStream home( 256 ); if ( !appdata || string_empty( appdata ) ) { ERROR_MESSAGE( "Application Data folder not available.\n" - "Radiant will use C:\\ for user preferences.\n" ); + "Radiant will use C:\\ for user preferences.\n" ); home << "C:"; } else diff --git a/radiant/error.cpp b/radiant/error.cpp index fda7f79f..c5c3adf9 100644 --- a/radiant/error.cpp +++ b/radiant/error.cpp @@ -67,16 +67,16 @@ void Error( const char *error, ... ){ if ( GetLastError() != 0 ) { LPVOID lpMsgBuf; FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - 0, - GetLastError(), - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - (LPTSTR) &lpMsgBuf, - 0, - 0 - ); + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + 0, + GetLastError(), + MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + (LPTSTR) &lpMsgBuf, + 0, + 0 + ); strcat( text, "GetLastError: " ); /* Gtk will only crunch 0<=char<=127 diff --git a/radiant/feedback.h b/radiant/feedback.h index 905abd50..bd849b70 100644 --- a/radiant/feedback.h +++ b/radiant/feedback.h @@ -41,10 +41,10 @@ class IGL2DWindow { public: // Increment the number of references to this object -virtual void IncRef() = 0; + virtual void IncRef() = 0; // Decrement the reference count -virtual void DecRef() = 0; -virtual void Draw2D( VIEWTYPE vt ) = 0; + virtual void DecRef() = 0; + virtual void Draw2D( VIEWTYPE vt ) = 0; }; // 3D window @@ -52,132 +52,153 @@ class IGL3DWindow { public: // Increment the number of references to this object -virtual void IncRef() = 0; + virtual void IncRef() = 0; // Decrement the reference count -virtual void DecRef() = 0; -virtual void Draw3D() = 0; + virtual void DecRef() = 0; + virtual void Draw3D() = 0; }; // a select message with a brush/entity select information class CSelectMsg : public ISAXHandler { -enum { SELECT_MESSAGE, SELECT_BRUSH } ESelectState; -StringOutputStream message; -StringOutputStream brush; + enum { SELECT_MESSAGE, SELECT_BRUSH } ESelectState; + StringOutputStream message; + StringOutputStream brush; public: -CSelectMsg() { ESelectState = SELECT_MESSAGE; } + CSelectMsg() { + ESelectState = SELECT_MESSAGE; + } // SAX interface -void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); -void saxEndElement( message_info_t *ctx, const xmlChar *name ); -void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); + void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); + void saxEndElement( message_info_t *ctx, const xmlChar *name ); + void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); // for use in the dialog window -const char* getName() { return message.c_str(); } -IGL2DWindow* Highlight(); -void DropHighlight() { } + const char* getName() { + return message.c_str(); + } + IGL2DWindow* Highlight(); + void DropHighlight() { } }; class CPointMsg final : public ISAXHandler, public IGL2DWindow { -enum { POINT_MESSAGE, POINT_POINT } EPointState; -StringOutputStream message; -StringOutputStream point; -Vector3 pt; -int refCount; + enum { POINT_MESSAGE, POINT_POINT } EPointState; + StringOutputStream message; + StringOutputStream point; + Vector3 pt; + int refCount; public: -CPointMsg() { EPointState = POINT_MESSAGE; refCount = 0; } + CPointMsg() { + EPointState = POINT_MESSAGE; + refCount = 0; + } // SAX interface -void Release(){ - delete this; -} -void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); -void saxEndElement( message_info_t *ctx, const xmlChar *name ); -void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); + void Release(){ + delete this; + } + void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); + void saxEndElement( message_info_t *ctx, const xmlChar *name ); + void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); // for use in the dialog window -const char* getName() { return message.c_str(); } -IGL2DWindow* Highlight(); -void DropHighlight(); + const char* getName() { + return message.c_str(); + } + IGL2DWindow* Highlight(); + void DropHighlight(); // IGL2DWindow interface -------------------------------- // Increment the number of references to this object -void IncRef() { refCount++; } -// Decrement the reference count -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + void IncRef() { + refCount++; } -} -void Draw2D( VIEWTYPE vt ); +// Decrement the reference count + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } + } + void Draw2D( VIEWTYPE vt ); }; class CWindingMsg final : public ISAXHandler, public IGL2DWindow { -enum { WINDING_MESSAGE, WINDING_WINDING } EPointState; -StringOutputStream message; -StringOutputStream winding; -Vector3 wt[256]; -int numpoints; -int refCount; + enum { WINDING_MESSAGE, WINDING_WINDING } EPointState; + StringOutputStream message; + StringOutputStream winding; + Vector3 wt[256]; + int numpoints; + int refCount; public: -CWindingMsg() { EPointState = WINDING_MESSAGE; refCount = 0; numpoints = 0; } + CWindingMsg() { + EPointState = WINDING_MESSAGE; + refCount = 0; + numpoints = 0; + } // SAX interface -void Release(){ - delete this; -} -void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); -void saxEndElement( message_info_t *ctx, const xmlChar *name ); -void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); + void Release(){ + delete this; + } + void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); + void saxEndElement( message_info_t *ctx, const xmlChar *name ); + void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); // for use in the dialog window -const char* getName() { return message.c_str(); } -IGL2DWindow* Highlight(); -void DropHighlight(); + const char* getName() { + return message.c_str(); + } + IGL2DWindow* Highlight(); + void DropHighlight(); // IGL2DWindow interface -------------------------------- // Increment the number of references to this object -void IncRef() { refCount++; } -// Decrement the reference count -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; + void IncRef() { + refCount++; } -} -void Draw2D( VIEWTYPE vt ); +// Decrement the reference count + void DecRef() { + refCount--; + if ( refCount <= 0 ) { + delete this; + } + } + void Draw2D( VIEWTYPE vt ); }; typedef struct _GtkListStore GtkListStore; class CDbgDlg : public Dialog { -GPtrArray *m_pFeedbackElements; + GPtrArray *m_pFeedbackElements; // the list widget we use in the dialog -GtkListStore* m_clist; -ISAXHandler *m_pHighlight; -IGL2DWindow* m_pDraw2D; + GtkListStore* m_clist; + ISAXHandler *m_pHighlight; + IGL2DWindow* m_pDraw2D; public: -CDbgDlg(){ - m_pFeedbackElements = g_ptr_array_new(); - m_pHighlight = NULL; - m_pDraw2D = NULL; -} + CDbgDlg(){ + m_pFeedbackElements = g_ptr_array_new(); + m_pHighlight = NULL; + m_pDraw2D = NULL; + } // refresh items -void Push( ISAXHandler * ); + void Push( ISAXHandler * ); // clean the debug window, release all ISAXHanlders we have -void Init(); -ISAXHandler *GetElement( std::size_t row ); -void SetHighlight( gint row ); -void DropHighlight(); -void draw2D( VIEWTYPE viewType ){ - if ( m_pDraw2D != 0 ) { - m_pDraw2D->Draw2D( viewType ); + void Init(); + ISAXHandler *GetElement( std::size_t row ); + void SetHighlight( gint row ); + void DropHighlight(); + void draw2D( VIEWTYPE viewType ){ + if ( m_pDraw2D != 0 ) { + m_pDraw2D->Draw2D( viewType ); + } } -} -void destroyWindow(){ - if ( GetWidget() != 0 ) { - Destroy(); + void destroyWindow(){ + if ( GetWidget() != 0 ) { + Destroy(); + } } -} // void HideDlg(); protected: -GtkWindow* BuildDialog(); + GtkWindow* BuildDialog(); }; extern CDbgDlg g_DbgDlg; diff --git a/radiant/filetypes.cpp b/radiant/filetypes.cpp index 9cf4c08b..e95c5340 100644 --- a/radiant/filetypes.cpp +++ b/radiant/filetypes.cpp @@ -32,51 +32,51 @@ class RadiantFileTypeRegistry : public IFileTypeRegistry { -struct filetype_copy_t -{ - filetype_copy_t( const char* moduleName, const filetype_t other ) - : m_moduleName( moduleName ), m_name( other.name ), m_pattern( other.pattern ), m_can_load( other.can_load ), m_can_import( other.can_import ), m_can_save( other.can_save ){ - } - const char* getModuleName() const { - return m_moduleName.c_str(); - } - filetype_t getType() const { - return filetype_t( m_name.c_str(), m_pattern.c_str(), m_can_load, m_can_save, m_can_import ); - } -private: - CopiedString m_moduleName; - CopiedString m_name; - CopiedString m_pattern; -public: - bool m_can_load; - bool m_can_import; - bool m_can_save; -}; -typedef std::vector filetype_list_t; -std::map m_typelists; -public: -RadiantFileTypeRegistry(){ - addType( "*", "*", filetype_t( "All Files", "*.*" ) ); -} -void addType( const char* moduleType, const char* moduleName, filetype_t type ){ - m_typelists[moduleType].push_back( filetype_copy_t( moduleName, type ) ); -} -void getTypeList( const char* moduleType, IFileTypeList* typelist, bool want_load, bool want_import, bool want_save ){ - filetype_list_t& list_ref = m_typelists[moduleType]; - for ( filetype_list_t::iterator i = list_ref.begin(); i != list_ref.end(); ++i ) + struct filetype_copy_t { - if ( want_load && !( *i ).m_can_load ) { - return; + filetype_copy_t( const char* moduleName, const filetype_t other ) + : m_moduleName( moduleName ), m_name( other.name ), m_pattern( other.pattern ), m_can_load( other.can_load ), m_can_import( other.can_import ), m_can_save( other.can_save ){ } - if ( want_import && !( *i ).m_can_import ) { - return; + const char* getModuleName() const { + return m_moduleName.c_str(); } - if ( want_save && !( *i ).m_can_save ) { - return; + filetype_t getType() const { + return filetype_t( m_name.c_str(), m_pattern.c_str(), m_can_load, m_can_save, m_can_import ); + } + private: + CopiedString m_moduleName; + CopiedString m_name; + CopiedString m_pattern; + public: + bool m_can_load; + bool m_can_import; + bool m_can_save; + }; + typedef std::vector filetype_list_t; + std::map m_typelists; +public: + RadiantFileTypeRegistry(){ + addType( "*", "*", filetype_t( "All Files", "*.*" ) ); + } + void addType( const char* moduleType, const char* moduleName, filetype_t type ){ + m_typelists[moduleType].push_back( filetype_copy_t( moduleName, type ) ); + } + void getTypeList( const char* moduleType, IFileTypeList* typelist, bool want_load, bool want_import, bool want_save ){ + filetype_list_t& list_ref = m_typelists[moduleType]; + for ( filetype_list_t::iterator i = list_ref.begin(); i != list_ref.end(); ++i ) + { + if ( want_load && !( *i ).m_can_load ) { + return; + } + if ( want_import && !( *i ).m_can_import ) { + return; + } + if ( want_save && !( *i ).m_can_save ) { + return; + } + typelist->addType( ( *i ).getModuleName(), ( *i ).getType() ); } - typelist->addType( ( *i ).getModuleName(), ( *i ).getType() ); } -} }; static RadiantFileTypeRegistry g_patterns; @@ -88,25 +88,25 @@ IFileTypeRegistry* GetFileTypeRegistry(){ const char* findModuleName( IFileTypeRegistry* registry, const char* moduleType, const char* extension ){ class SearchFileTypeList : public IFileTypeList { - char m_pattern[128]; - const char* m_moduleName; -public: - SearchFileTypeList( const char* ext ) - : m_moduleName( "" ){ - m_pattern[0] = '*'; - m_pattern[1] = '.'; - strncpy( m_pattern + 2, ext, 125 ); - m_pattern[127] = '\0'; - } - void addType( const char* moduleName, filetype_t type ){ - if ( extension_equal( m_pattern, type.pattern ) ) { - m_moduleName = moduleName; + char m_pattern[128]; + const char* m_moduleName; + public: + SearchFileTypeList( const char* ext ) + : m_moduleName( "" ){ + m_pattern[0] = '*'; + m_pattern[1] = '.'; + strncpy( m_pattern + 2, ext, 125 ); + m_pattern[127] = '\0'; + } + void addType( const char* moduleName, filetype_t type ){ + if ( extension_equal( m_pattern, type.pattern ) ) { + m_moduleName = moduleName; + } } - } - const char* getModuleName(){ - return m_moduleName; - } + const char* getModuleName(){ + return m_moduleName; + } } search( extension ); registry->getTypeList( moduleType, &search ); return search.getModuleName(); @@ -118,17 +118,17 @@ public: class FiletypesAPI { -IFileTypeRegistry* m_filetypes; + IFileTypeRegistry* m_filetypes; public: -typedef IFileTypeRegistry Type; -STRING_CONSTANT( Name, "*" ); + typedef IFileTypeRegistry Type; + STRING_CONSTANT( Name, "*" ); -FiletypesAPI(){ - m_filetypes = GetFileTypeRegistry(); -} -IFileTypeRegistry* getTable(){ - return m_filetypes; -} + FiletypesAPI(){ + m_filetypes = GetFileTypeRegistry(); + } + IFileTypeRegistry* getTable(){ + return m_filetypes; + } }; typedef SingletonModule FiletypesModule; diff --git a/radiant/filters.cpp b/radiant/filters.cpp index 34105935..1473d838 100644 --- a/radiant/filters.cpp +++ b/radiant/filters.cpp @@ -55,14 +55,14 @@ inline bool filter_active( int mask ){ class FilterWrapper { public: -FilterWrapper( Filter& filter, int mask ) : m_filter( filter ), m_mask( mask ){ -} -void update(){ - m_filter.setActive( filter_active( m_mask ) ); -} + FilterWrapper( Filter& filter, int mask ) : m_filter( filter ), m_mask( mask ){ + } + void update(){ + m_filter.setActive( filter_active( m_mask ) ); + } private: -Filter& m_filter; -int m_mask; + Filter& m_filter; + int m_mask; }; typedef std::list Filters; @@ -91,19 +91,19 @@ void UpdateFilters(){ class BasicFilterSystem : public FilterSystem { public: -void addFilter( Filter& filter, int mask ){ - g_filters.push_back( FilterWrapper( filter, mask ) ); - g_filters.back().update(); -} -void registerFilterable( Filterable& filterable ){ - filterable.updateFiltered(); - const bool inserted = g_filterables.insert( &filterable ).second; - ASSERT_MESSAGE( inserted, "filterable already registered" ); -} -void unregisterFilterable( Filterable& filterable ){ - const bool erased = g_filterables.erase( &filterable ); - ASSERT_MESSAGE( erased, "filterable not registered" ); -} + void addFilter( Filter& filter, int mask ){ + g_filters.push_back( FilterWrapper( filter, mask ) ); + g_filters.back().update(); + } + void registerFilterable( Filterable& filterable ){ + filterable.updateFiltered(); + const bool inserted = g_filterables.insert( &filterable ).second; + ASSERT_MESSAGE( inserted, "filterable already registered" ); + } + void unregisterFilterable( Filterable& filterable ){ + const bool erased = g_filterables.erase( &filterable ); + ASSERT_MESSAGE( erased, "filterable not registered" ); + } }; BasicFilterSystem g_FilterSystem; @@ -119,29 +119,29 @@ void PerformFiltering(){ class ToggleFilterFlag { -const unsigned int m_mask; + const unsigned int m_mask; public: -ToggleItem m_item; + ToggleItem m_item; -ToggleFilterFlag( unsigned int mask ) : m_mask( mask ), m_item( ActiveCaller( *this ) ){ -} -ToggleFilterFlag( const ToggleFilterFlag& other ) : m_mask( other.m_mask ), m_item( ActiveCaller( *this ) ){ -} -void active( const BoolImportCallback& importCallback ){ - importCallback( ( g_filters_globals.exclude & m_mask ) != 0 ); -} -typedef MemberCaller1 ActiveCaller; -void toggle(){ - g_filters_globals.exclude ^= m_mask; - m_item.update(); - PerformFiltering(); -} -void reset(){ - g_filters_globals.exclude = 0; - m_item.update(); - PerformFiltering(); -} -typedef MemberCaller ToggleCaller; + ToggleFilterFlag( unsigned int mask ) : m_mask( mask ), m_item( ActiveCaller( *this ) ){ + } + ToggleFilterFlag( const ToggleFilterFlag& other ) : m_mask( other.m_mask ), m_item( ActiveCaller( *this ) ){ + } + void active( const BoolImportCallback& importCallback ){ + importCallback( ( g_filters_globals.exclude & m_mask ) != 0 ); + } + typedef MemberCaller1 ActiveCaller; + void toggle(){ + g_filters_globals.exclude ^= m_mask; + m_item.update(); + PerformFiltering(); + } + void reset(){ + g_filters_globals.exclude = 0; + m_item.update(); + PerformFiltering(); + } + typedef MemberCaller ToggleCaller; }; @@ -269,22 +269,22 @@ void DestroyFilters(){ class FilterAPI { -FilterSystem* m_filter; + FilterSystem* m_filter; public: -typedef FilterSystem Type; -STRING_CONSTANT( Name, "*" ); + typedef FilterSystem Type; + STRING_CONSTANT( Name, "*" ); -FilterAPI(){ - ConstructFilters(); + FilterAPI(){ + ConstructFilters(); - m_filter = &GetFilterSystem(); -} -~FilterAPI(){ - DestroyFilters(); -} -FilterSystem* getTable(){ - return m_filter; -} + m_filter = &GetFilterSystem(); + } + ~FilterAPI(){ + DestroyFilters(); + } + FilterSystem* getTable(){ + return m_filter; + } }; typedef SingletonModule FilterModule; diff --git a/radiant/findtexturedialog.cpp b/radiant/findtexturedialog.cpp index 206c5177..2a12d4b9 100644 --- a/radiant/findtexturedialog.cpp +++ b/radiant/findtexturedialog.cpp @@ -47,30 +47,30 @@ class FindTextureDialog : public Dialog { public: -WindowPositionTracker m_position_tracker; -static void setReplaceStr( const char* name ); -static void setFindStr( const char* name ); -static bool isOpen(); -static void show(); -typedef FreeCaller<&FindTextureDialog::show> ShowCaller; -static void updateTextures( const char* name ); + WindowPositionTracker m_position_tracker; + static void setReplaceStr( const char* name ); + static void setFindStr( const char* name ); + static bool isOpen(); + static void show(); + typedef FreeCaller<&FindTextureDialog::show> ShowCaller; + static void updateTextures( const char* name ); -FindTextureDialog(); -virtual ~FindTextureDialog(); -GtkWindow* BuildDialog(); + FindTextureDialog(); + virtual ~FindTextureDialog(); + GtkWindow* BuildDialog(); -void constructWindow( GtkWindow* parent ){ - m_parent = parent; - Create(); -} -void destroyWindow(){ - Destroy(); -} + void constructWindow( GtkWindow* parent ){ + m_parent = parent; + Create(); + } + void destroyWindow(){ + Destroy(); + } -bool m_bSelectedOnly; -CopiedString m_strFind; -CopiedString m_strReplace; + bool m_bSelectedOnly; + CopiedString m_strFind; + CopiedString m_strReplace; }; FindTextureDialog g_FindTextureDialog; @@ -153,25 +153,25 @@ GtkWindow* FindTextureDialog::BuildDialog(){ label = gtk_label_new( "Find:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); label = gtk_label_new( "Replace:*" ); gtk_widget_set_tooltip_text( label, "Empty = search mode" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); entry = gtk_entry_new(); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( entry ), "focus_in_event", - G_CALLBACK( find_focus_in ), 0 ); + G_CALLBACK( find_focus_in ), 0 ); AddDialogData( *GTK_ENTRY( entry ), m_strFind ); GlobalTextureEntryCompletion::instance().connect( GTK_ENTRY( entry ) ); @@ -179,10 +179,10 @@ GtkWindow* FindTextureDialog::BuildDialog(){ gtk_widget_set_tooltip_text( entry, "Empty = search mode" ); gtk_widget_show( entry ); gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( entry ), "focus_in_event", - G_CALLBACK( replace_focus_in ), 0 ); + G_CALLBACK( replace_focus_in ), 0 ); AddDialogData( *GTK_ENTRY( entry ), m_strReplace ); GlobalTextureEntryCompletion::instance().connect( GTK_ENTRY( entry ) ); @@ -199,14 +199,14 @@ GtkWindow* FindTextureDialog::BuildDialog(){ gtk_widget_show( button ); gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnApply ), 0 ); + G_CALLBACK( OnApply ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); button = gtk_button_new_with_label( "Close" ); gtk_widget_show( button ); gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnClose ), 0 ); + G_CALLBACK( OnClose ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); return dlg; diff --git a/radiant/glwidget.cpp b/radiant/glwidget.cpp index 0820d787..9cb3ac66 100644 --- a/radiant/glwidget.cpp +++ b/radiant/glwidget.cpp @@ -27,21 +27,21 @@ class GtkGLAPI { -_QERGtkGLTable m_gtkgl; + _QERGtkGLTable m_gtkgl; public: -typedef _QERGtkGLTable Type; -STRING_CONSTANT( Name, "*" ); + typedef _QERGtkGLTable Type; + STRING_CONSTANT( Name, "*" ); -GtkGLAPI(){ - m_gtkgl.glwidget_new = &glwidget_new; - m_gtkgl.glwidget_swap_buffers = &glwidget_swap_buffers; - m_gtkgl.glwidget_make_current = &glwidget_make_current; - m_gtkgl.glwidget_destroy_context = &glwidget_destroy_context; - m_gtkgl.glwidget_create_context = &glwidget_create_context; -} -_QERGtkGLTable* getTable(){ - return &m_gtkgl; -} + GtkGLAPI(){ + m_gtkgl.glwidget_new = &glwidget_new; + m_gtkgl.glwidget_swap_buffers = &glwidget_swap_buffers; + m_gtkgl.glwidget_make_current = &glwidget_make_current; + m_gtkgl.glwidget_destroy_context = &glwidget_destroy_context; + m_gtkgl.glwidget_create_context = &glwidget_create_context; + } + _QERGtkGLTable* getTable(){ + return &m_gtkgl; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/grid.cpp b/radiant/grid.cpp index 93298fe2..d9add927 100644 --- a/radiant/grid.cpp +++ b/radiant/grid.cpp @@ -119,25 +119,25 @@ void setGridPower( GridPower power ); class GridMenuItem { -GridPower m_id; + GridPower m_id; -GridMenuItem( const GridMenuItem& other ); // NOT COPYABLE -GridMenuItem& operator=( const GridMenuItem& other ); // NOT ASSIGNABLE + GridMenuItem( const GridMenuItem& other ); // NOT COPYABLE + GridMenuItem& operator=( const GridMenuItem& other ); // NOT ASSIGNABLE public: -ToggleItem m_item; + ToggleItem m_item; -GridMenuItem( GridPower id ) : m_id( id ), m_item( ExportCaller( *this ) ){ -} -void set(){ - g_grid_power = m_id; - m_item.update(); - setGridPower( m_id ); -} -typedef MemberCaller SetCaller; -void active( const BoolImportCallback& importCallback ){ - importCallback( g_grid_power == m_id ); -} -typedef MemberCaller1 ExportCaller; + GridMenuItem( GridPower id ) : m_id( id ), m_item( ExportCaller( *this ) ){ + } + void set(){ + g_grid_power = m_id; + m_item.update(); + setGridPower( m_id ); + } + typedef MemberCaller SetCaller; + void active( const BoolImportCallback& importCallback ){ + importCallback( g_grid_power == m_id ); + } + typedef MemberCaller1 ExportCaller; }; GridMenuItem g_gridMenu0125( GRIDPOWER_0125 ); @@ -258,19 +258,19 @@ void Grid_registerShortcuts(){ void Grid_constructPreferences( PreferencesPage& page ){ page.appendCombo( - "Default grid spacing", - g_grid_default, - ARRAY_RANGE( g_gridnames ) - ); + "Default grid spacing", + g_grid_default, + ARRAY_RANGE( g_gridnames ) + ); { const char* coords[] = { "4096", "8192", "16384", "32768", "65536" }; page.appendCombo( - "Max grid coordinate", - STRING_ARRAY_RANGE( coords ), - IntImportCallback( maxGridCoordPowerImportCaller() ), - IntExportCallback( maxGridCoordPowerExportCaller() ) - ); + "Max grid coordinate", + STRING_ARRAY_RANGE( coords ), + IntImportCallback( maxGridCoordPowerImportCaller() ), + IntExportCallback( maxGridCoordPowerExportCaller() ) + ); } } void Grid_constructPage( PreferenceGroup& group ){ diff --git a/radiant/groupdialog.cpp b/radiant/groupdialog.cpp index 64f83768..6f68b619 100644 --- a/radiant/groupdialog.cpp +++ b/radiant/groupdialog.cpp @@ -48,26 +48,26 @@ class GroupDlg { public: -GtkWidget* m_pNotebook; -GtkWindow* m_window; + GtkWidget* m_pNotebook; + GtkWindow* m_window; -GroupDlg(); -void Create( GtkWindow* parent ); + GroupDlg(); + void Create( GtkWindow* parent ); -void Show(){ - /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */ - GtkWidget* glwidget = GTK_WIDGET( g_object_get_data( G_OBJECT( m_window ), "glwidget" ) ); - if ( glwidget ){ - gtk_widget_hide( glwidget ); - gtk_widget_show( glwidget ); + void Show(){ + /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */ + GtkWidget* glwidget = GTK_WIDGET( g_object_get_data( G_OBJECT( m_window ), "glwidget" ) ); + if ( glwidget ){ + gtk_widget_hide( glwidget ); + gtk_widget_show( glwidget ); + } + gtk_widget_show( GTK_WIDGET( m_window ) ); + } + void Hide(){ + gtk_widget_hide( GTK_WIDGET( m_window ) ); } - gtk_widget_show( GTK_WIDGET( m_window ) ); -} -void Hide(){ - gtk_widget_hide( GTK_WIDGET( m_window ) ); -} -WindowPositionTracker m_position_tracker; + WindowPositionTracker m_position_tracker; }; namespace diff --git a/radiant/gtkdlgs.cpp b/radiant/gtkdlgs.cpp index 88759577..c38060ec 100644 --- a/radiant/gtkdlgs.cpp +++ b/radiant/gtkdlgs.cpp @@ -78,19 +78,19 @@ class GameComboConfiguration { public: -const char* basegame_dir; -const char* basegame; -const char* known_dir; -const char* known; -const char* custom; + const char* basegame_dir; + const char* basegame; + const char* known_dir; + const char* known; + const char* custom; -GameComboConfiguration() : - basegame_dir( g_pGameDescription->getRequiredKeyValue( "basegame" ) ), - basegame( g_pGameDescription->getRequiredKeyValue( "basegamename" ) ), - known_dir( g_pGameDescription->getKeyValue( "knowngame" ) ), - known( g_pGameDescription->getKeyValue( "knowngamename" ) ), - custom( g_pGameDescription->getRequiredKeyValue( "unknowngamename" ) ){ -} + GameComboConfiguration() : + basegame_dir( g_pGameDescription->getRequiredKeyValue( "basegame" ) ), + basegame( g_pGameDescription->getRequiredKeyValue( "basegamename" ) ), + known_dir( g_pGameDescription->getKeyValue( "knowngame" ) ), + known( g_pGameDescription->getKeyValue( "knowngamename" ) ), + custom( g_pGameDescription->getRequiredKeyValue( "unknowngamename" ) ){ + } }; typedef LazyStatic LazyStaticGameComboConfiguration; @@ -173,15 +173,15 @@ gboolean OnSelchangeComboWhatgame( GtkWidget *widget, GameCombo* combo ){ class MappingMode { public: -bool do_mapping_mode; -const char* sp_mapping_mode; -const char* mp_mapping_mode; + bool do_mapping_mode; + const char* sp_mapping_mode; + const char* mp_mapping_mode; -MappingMode() : - do_mapping_mode( !string_empty( g_pGameDescription->getKeyValue( "show_gamemode" ) ) ), - sp_mapping_mode( "Single Player mapping mode" ), - mp_mapping_mode( "Multiplayer mapping mode" ){ -} + MappingMode() : + do_mapping_mode( !string_empty( g_pGameDescription->getKeyValue( "show_gamemode" ) ) ), + sp_mapping_mode( "Single Player mapping mode" ), + mp_mapping_mode( "Multiplayer mapping mode" ){ + } }; typedef LazyStatic LazyStaticMappingMode; @@ -193,8 +193,8 @@ inline MappingMode& globalMappingMode(){ class ProjectSettingsDialog { public: -GameCombo game_combo; -GtkComboBox* gamemode_combo; + GameCombo game_combo; + GtkComboBox* gamemode_combo; }; GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, ModalDialog& modal ){ @@ -206,8 +206,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal { GtkVBox* vbox = create_dialog_vbox( 4 ); gtk_table_attach( table1, GTK_WIDGET( vbox ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); { GtkButton* button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &modal ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 ); @@ -220,8 +220,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal { GtkFrame* frame = create_dialog_frame( "Project settings" ); gtk_table_attach( table1, GTK_WIDGET( frame ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); { GtkTable* table2 = create_dialog_table( ( globalMappingMode().do_mapping_mode ) ? 4 : 3, 2, 4, 4, 4 ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( table2 ) ); @@ -230,8 +230,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal GtkLabel* label = GTK_LABEL( gtk_label_new( "Select mod" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table2, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); } { @@ -245,8 +245,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table2, GTK_WIDGET( combo ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( combo ), "changed", G_CALLBACK( OnSelchangeComboWhatgame ), &dialog.game_combo ); } @@ -255,16 +255,16 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal GtkLabel* label = GTK_LABEL( gtk_label_new( "fs_game" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table2, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table2, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); dialog.game_combo.fsgame_entry = entry; } @@ -273,8 +273,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal GtkLabel* label = GTK_LABEL( gtk_label_new( "Mapping mode" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table2, GTK_WIDGET( label ), 0, 1, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); GtkComboBoxText* combo = GTK_COMBO_BOX_TEXT( gtk_combo_box_text_new() ); @@ -283,8 +283,8 @@ GtkWindow* ProjectSettingsDialog_construct( ProjectSettingsDialog& dialog, Modal gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table2, GTK_WIDGET( combo ), 1, 2, 3, 4, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); dialog.gamemode_combo = GTK_COMBO_BOX( combo ); } @@ -318,8 +318,8 @@ void ProjectSettingsDialog_ok( ProjectSettingsDialog& dialog ){ const char* dir = gtk_entry_get_text( dialog.game_combo.fsgame_entry ); const char* new_gamename = path_equal( dir, globalGameComboConfiguration().basegame_dir ) - ? "" - : dir; + ? "" + : dir; if ( !path_equal( new_gamename, gamename_get() ) ) { if ( ConfirmModified( "Edit Project Settings" ) ) { @@ -348,16 +348,16 @@ void ProjectSettingsDialog_ok( ProjectSettingsDialog& dialog ){ void DoProjectSettings(){ //if ( ConfirmModified( "Edit Project Settings" ) ) { - ModalDialog modal; - ProjectSettingsDialog dialog; + ModalDialog modal; + ProjectSettingsDialog dialog; - GtkWindow* window = ProjectSettingsDialog_construct( dialog, modal ); + GtkWindow* window = ProjectSettingsDialog_construct( dialog, modal ); - if ( modal_dialog_show( window, modal ) == eIDOK ) { - ProjectSettingsDialog_ok( dialog ); - } + if ( modal_dialog_show( window, modal ) == eIDOK ) { + ProjectSettingsDialog_ok( dialog ); + } - gtk_widget_destroy( GTK_WIDGET( window ) ); + gtk_widget_destroy( GTK_WIDGET( window ) ); //} } @@ -493,12 +493,12 @@ void DoAbout(){ { GtkLabel* label = GTK_LABEL( gtk_label_new( "NetRadiant " RADIANT_VERSION "\n" - __DATE__ "\n\n" - RADIANT_ABOUTMSG "\n\n" - "By alientrap.org\n\n" - "This program is free software\n" - "licensed under the GNU GPL.\n" - ) ); + __DATE__ "\n\n" + RADIANT_ABOUTMSG "\n\n" + "By alientrap.org\n\n" + "This program is free software\n" + "licensed under the GNU GPL.\n" + ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( label ), FALSE, FALSE, 0 ); @@ -535,48 +535,48 @@ void DoAbout(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Vendor:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Version:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Renderer:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( reinterpret_cast( glGetString( GL_VENDOR ) ) ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( reinterpret_cast( glGetString( GL_VERSION ) ) ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( reinterpret_cast( glGetString( GL_RENDERER ) ) ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } } @@ -632,9 +632,9 @@ EMessageBoxReturn DoTextureLayout( float *fx, float *fy ){ gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox ), TRUE, TRUE, 0 ); { GtkLabel* label = GTK_LABEL( gtk_label_new( "Texture will be fit across the patch based\n" - "on the x and y values given. Values of 1x1\n" - "will \"fit\" the texture. 2x2 will repeat\n" - "it twice, etc." ) ); + "on the x and y values given. Values of 1x1\n" + "will \"fit\" the texture. 2x2 will repeat\n" + "it twice, etc." ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( label ), TRUE, TRUE, 0 ); gtk_label_set_justify( label, GTK_JUSTIFY_LEFT ); @@ -647,24 +647,24 @@ EMessageBoxReturn DoTextureLayout( float *fx, float *fy ){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Texture x:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Texture y:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); x = entry; } @@ -672,8 +672,8 @@ EMessageBoxReturn DoTextureLayout( float *fx, float *fy ){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); y = entry; } @@ -754,7 +754,7 @@ class TextEditor m_textBuffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW( m_textView ) ); g_signal_connect( G_OBJECT( m_textBuffer ), "modified-changed", - G_CALLBACK( modified_changed ), this ); + G_CALLBACK( modified_changed ), this ); hbox = gtk_hbox_new( FALSE, 5 ); gtk_widget_show( hbox ); @@ -764,14 +764,14 @@ class TextEditor gtk_widget_show( m_button ); gtk_box_pack_end( GTK_BOX( hbox ), m_button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( m_button ), "clicked", - G_CALLBACK( editor_close ), this ); + G_CALLBACK( editor_close ), this ); gtk_widget_set_size_request( m_button, 60, -1 ); m_button = gtk_button_new_with_label( "Save" ); gtk_widget_show( m_button ); gtk_box_pack_end( GTK_BOX( hbox ), m_button, FALSE, FALSE, 0 ); g_signal_connect( G_OBJECT( m_button ), "clicked", - G_CALLBACK( editor_save ), this ); + G_CALLBACK( editor_save ), this ); gtk_widget_set_size_request( m_button, 60, -1 ); } static void editor_close( GtkWidget *widget, TextEditor* self ){ @@ -824,9 +824,9 @@ public: gtk_widget_show( m_window ); gtk_window_present( GTK_WINDOW( m_window ) ); - //#ifdef WIN32 + //#ifdef WIN32 process_gui(); - //#endif + //#endif { GtkTextIter text_iter; @@ -835,9 +835,9 @@ public: gtk_text_view_scroll_to_iter( GTK_TEXT_VIEW( m_textView ), &text_iter, 0, TRUE, 0, 0); } - //#ifdef WIN32 + //#ifdef WIN32 gtk_widget_queue_draw( m_textView ); - //#endif + //#endif } }; diff --git a/radiant/gtkmisc.cpp b/radiant/gtkmisc.cpp index f8a25730..661ab493 100644 --- a/radiant/gtkmisc.cpp +++ b/radiant/gtkmisc.cpp @@ -106,8 +106,8 @@ GtkToggleToolButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const ch bool color_dialog( GtkWidget *parent, Vector3& color, const char* title ){ GtkWidget* dlg; GdkColor clr = { 0, guint16( color[0] * 65535 ), - guint16( color[1] * 65535 ), - guint16( color[2] * 65535 ) }; + guint16( color[1] * 65535 ), + guint16( color[2] * 65535 ) }; ModalDialog dialog; dlg = gtk_color_selection_dialog_new( title ); diff --git a/radiant/gtktheme.cpp b/radiant/gtktheme.cpp index 34f42b05..2813b169 100644 --- a/radiant/gtktheme.cpp +++ b/radiant/gtktheme.cpp @@ -346,23 +346,23 @@ GtkWidget* create_rc_window() { g_signal_connect( (gpointer)main_window, "delete_event", - G_CALLBACK( on_main_window_delete_event ), - NULL ); + G_CALLBACK( on_main_window_delete_event ), + NULL ); g_signal_connect( (gpointer)main_use_default_font_radio, "toggled", - G_CALLBACK( on_main_use_default_font_radio_toggled ), - NULL ); + G_CALLBACK( on_main_use_default_font_radio_toggled ), + NULL ); g_signal_connect( (gpointer)main_font_selector_button, "font_set", - G_CALLBACK( on_main_font_selector_button_font_set ), - NULL ); + G_CALLBACK( on_main_font_selector_button_font_set ), + NULL ); g_signal_connect( (gpointer)main_cancel_button, "clicked", - G_CALLBACK( on_main_cancel_button_clicked ), - NULL ); + G_CALLBACK( on_main_cancel_button_clicked ), + NULL ); g_signal_connect( (gpointer)main_reset_button, "clicked", - G_CALLBACK( on_main_reset_button_clicked ), - NULL ); + G_CALLBACK( on_main_reset_button_clicked ), + NULL ); g_signal_connect( (gpointer)main_ok_button, "clicked", - G_CALLBACK( on_main_ok_button_clicked ), - NULL ); + G_CALLBACK( on_main_ok_button_clicked ), + NULL ); /* Store pointers to all widgets, for use by lookup_widget(). */ GLADE_HOOKUP_OBJECT_NO_REF( main_window, main_window, "main_window" ); @@ -526,9 +526,9 @@ static void populate_with_themes( GtkWidget* w ) { gtk_tree_view_set_model( treeview, GTK_TREE_MODEL( store ) ); GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( - "Theme", gtk_cell_renderer_text_new(), - "text", 0, - NULL ); + "Theme", gtk_cell_renderer_text_new(), + "text", 0, + NULL ); gtk_tree_view_column_set_sizing( column, GTK_TREE_VIEW_COLUMN_GROW_ONLY ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeview ), column ); @@ -561,7 +561,7 @@ static void populate_with_themes( GtkWidget* w ) { } g_signal_connect( G_OBJECT( selection ), "changed", - G_CALLBACK( themelist_selection_changed_cb ), NULL ); + G_CALLBACK( themelist_selection_changed_cb ), NULL ); g_object_unref( G_OBJECT( store ) ); diff --git a/radiant/image.cpp b/radiant/image.cpp index c81b3617..491cd8c9 100644 --- a/radiant/image.cpp +++ b/radiant/image.cpp @@ -39,23 +39,23 @@ Image* QERApp_LoadImage( void* environment, const char* name ){ Image* image = 0; class LoadImageVisitor : public ImageModules::Visitor { - const char* m_name; - Image*& m_image; -public: - LoadImageVisitor( const char* name, Image*& image ) - : m_name( name ), m_image( image ){ - } - void visit( const char* name, const _QERPlugImageTable& table ) const { - if ( m_image == 0 ) { - StringOutputStream fullname( 256 ); - fullname << m_name << '.' << name; - ArchiveFile* file = GlobalFileSystem().openFile( fullname.c_str() ); - if ( file != 0 ) { - m_image = table.loadImage( *file ); - file->release(); + const char* m_name; + Image*& m_image; + public: + LoadImageVisitor( const char* name, Image*& image ) + : m_name( name ), m_image( image ){ + } + void visit( const char* name, const _QERPlugImageTable& table ) const { + if ( m_image == 0 ) { + StringOutputStream fullname( 256 ); + fullname << m_name << '.' << name; + ArchiveFile* file = GlobalFileSystem().openFile( fullname.c_str() ); + if ( file != 0 ) { + m_image = table.loadImage( *file ); + file->release(); + } } } - } }; Textures_getImageModules().foreachModule( LoadImageVisitor( name, image ) ); diff --git a/radiant/main.cpp b/radiant/main.cpp index a3551ade..eb087745 100644 --- a/radiant/main.cpp +++ b/radiant/main.cpp @@ -213,7 +213,7 @@ void error_redirect( const gchar *domain, GLogLevelFlags log_level, const gchar #ifndef _DEBUG if ( is_fatal ) #endif - ERROR_MESSAGE( "GTK+ error: " << buf ); + ERROR_MESSAGE( "GTK+ error: " << buf ); } #if defined ( _DEBUG ) && defined ( WIN32 ) && defined ( _MSC_VER ) @@ -228,95 +228,95 @@ void crt_init(){ class Lock { -bool m_locked; + bool m_locked; public: -Lock() : m_locked( false ){ -} -void lock(){ - m_locked = true; -} -void unlock(){ - m_locked = false; -} -bool locked() const { - return m_locked; -} + Lock() : m_locked( false ){ + } + void lock(){ + m_locked = true; + } + void unlock(){ + m_locked = false; + } + bool locked() const { + return m_locked; + } }; class ScopedLock { -Lock& m_lock; + Lock& m_lock; public: -ScopedLock( Lock& lock ) : m_lock( lock ){ - m_lock.lock(); -} -~ScopedLock(){ - m_lock.unlock(); -} + ScopedLock( Lock& lock ) : m_lock( lock ){ + m_lock.lock(); + } + ~ScopedLock(){ + m_lock.unlock(); + } }; class LineLimitedTextOutputStream : public TextOutputStream { -TextOutputStream& outputStream; -std::size_t count; + TextOutputStream& outputStream; + std::size_t count; public: -LineLimitedTextOutputStream( TextOutputStream& outputStream, std::size_t count ) - : outputStream( outputStream ), count( count ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - if ( count != 0 ) { - const char* p = buffer; - const char* end = buffer + length; - for (;; ) - { - p = std::find( p, end, '\n' ); - if ( p == end ) { - break; - } - ++p; - if ( --count == 0 ) { - length = p - buffer; - break; - } - } - outputStream.write( buffer, length ); + LineLimitedTextOutputStream( TextOutputStream& outputStream, std::size_t count ) + : outputStream( outputStream ), count( count ){ + } + std::size_t write( const char* buffer, std::size_t length ){ + if ( count != 0 ) { + const char* p = buffer; + const char* end = buffer + length; + for (;; ) + { + p = std::find( p, end, '\n' ); + if ( p == end ) { + break; + } + ++p; + if ( --count == 0 ) { + length = p - buffer; + break; + } + } + outputStream.write( buffer, length ); + } + return length; } - return length; -} }; class PopupDebugMessageHandler : public DebugMessageHandler { -StringOutputStream m_buffer; -Lock m_lock; + StringOutputStream m_buffer; + Lock m_lock; public: -TextOutputStream& getOutputStream(){ - if ( !m_lock.locked() ) { - return m_buffer; + TextOutputStream& getOutputStream(){ + if ( !m_lock.locked() ) { + return m_buffer; + } + return globalErrorStream(); } - return globalErrorStream(); -} -bool handleMessage(){ - getOutputStream() << "----------------\n"; - LineLimitedTextOutputStream outputStream( getOutputStream(), 24 ); - write_stack_trace( outputStream ); - getOutputStream() << "----------------\n"; - globalErrorStream() << m_buffer.c_str(); - if ( !m_lock.locked() ) { - ScopedLock lock( m_lock ); + bool handleMessage(){ + getOutputStream() << "----------------\n"; + LineLimitedTextOutputStream outputStream( getOutputStream(), 24 ); + write_stack_trace( outputStream ); + getOutputStream() << "----------------\n"; + globalErrorStream() << m_buffer.c_str(); + if ( !m_lock.locked() ) { + ScopedLock lock( m_lock ); #if defined _DEBUG - m_buffer << "Break into the debugger?\n"; - bool handled = gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_YESNO, eMB_ICONERROR ) == eIDNO; - m_buffer.clear(); - return handled; + m_buffer << "Break into the debugger?\n"; + bool handled = gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_YESNO, eMB_ICONERROR ) == eIDNO; + m_buffer.clear(); + return handled; #else - m_buffer << "Please report this error to the developers\n"; - gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_OK, eMB_ICONERROR ); - m_buffer.clear(); + m_buffer << "Please report this error to the developers\n"; + gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_OK, eMB_ICONERROR ); + m_buffer.clear(); #endif + } + return true; } - return true; -} }; typedef Static GlobalPopupDebugMessageHandler; @@ -405,8 +405,8 @@ bool check_version(){ if ( !bVerIsGood ) { StringOutputStream msg( 256 ); msg << "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n" - "Make sure you run the right/latest editor binary you installed\n" - << AppPath_get(); + "Make sure you run the right/latest editor binary you installed\n" + << AppPath_get(); gtk_MessageBox( 0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONDEFAULT ); } return bVerIsGood; @@ -442,8 +442,8 @@ void create_global_pid(){ #if !defined( _DEBUG ) StringOutputStream msg( 256 ); msg << "Radiant failed to start properly the last time it was run.\n" - "The failure may be related to current global preferences.\n" - "Do you want to reset global preferences to defaults?"; + "The failure may be related to current global preferences.\n" + "Do you want to reset global preferences to defaults?"; if ( gtk_MessageBox( 0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION ) == eIDYES ) { g_GamesDialog.Reset(); @@ -501,8 +501,8 @@ void create_local_pid(){ #if !defined( _DEBUG ) StringOutputStream msg; msg << "Radiant failed to start properly the last time it was run.\n" - "The failure may be caused by current preferences.\n" - "Do you want to reset all preferences to defaults?"; + "The failure may be caused by current preferences.\n" + "Do you want to reset all preferences to defaults?"; if ( gtk_MessageBox( 0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION ) == eIDYES ) { Preferences_Reset(); @@ -564,7 +564,7 @@ void fontconfig_workaround(){ TextFileOutputStream file( path.c_str() ); if ( !file.failed() ) { - file << "\n\ + file << "\n\ \n\ \n\ \n\ @@ -614,15 +614,15 @@ int main( int argc, char* argv[] ){ // redirect Gtk warnings to the console g_log_set_handler( "Gdk", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | - G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); g_log_set_handler( "Gtk", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | - G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); g_log_set_handler( "GtkGLExt", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | - G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); g_log_set_handler( "GLib", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | - G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); g_log_set_handler( 0, (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | - G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); + G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 ); GlobalDebugMessageHandler::instance().setHandler( GlobalPopupDebugMessageHandler::instance() ); diff --git a/radiant/mainframe.cpp b/radiant/mainframe.cpp index 4941e96c..5e729378 100644 --- a/radiant/mainframe.cpp +++ b/radiant/mainframe.cpp @@ -141,21 +141,21 @@ layout_globals_t g_layout_globals; // VFS class VFSModuleObserver : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -VFSModuleObserver() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - QE_InitVFS(); - GlobalFileSystem().initialise(); + VFSModuleObserver() : m_unrealised( 1 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - GlobalFileSystem().shutdown(); + void realise(){ + if ( --m_unrealised == 0 ) { + QE_InitVFS(); + GlobalFileSystem().initialise(); + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + GlobalFileSystem().shutdown(); + } } -} }; VFSModuleObserver g_VFSModuleObserver; @@ -271,21 +271,21 @@ void Radiant_detachHomePathsObserver( ModuleObserver& observer ){ class HomePathsModuleObserver : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -HomePathsModuleObserver() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - HomePaths_Realise(); - g_homePathObservers.realise(); + HomePathsModuleObserver() : m_unrealised( 1 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - g_homePathObservers.unrealise(); + void realise(){ + if ( --m_unrealised == 0 ) { + HomePaths_Realise(); + g_homePathObservers.realise(); + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + g_homePathObservers.unrealise(); + } } -} }; HomePathsModuleObserver g_HomePathsModuleObserver; @@ -414,17 +414,17 @@ const char* GameToolsPath_get(){ void Paths_constructPreferences( PreferencesPage& page ){ page.appendPathEntry( "Engine Path", true, - StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ), - StringExportCallback( StringExportCaller( g_strEnginePath ) ) - ); + StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ), + StringExportCallback( StringExportCaller( g_strEnginePath ) ) + ); } void Paths_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Paths", "Path Settings" ) ); Paths_constructPreferences( page ); page.appendPathEntry( "Extra Resource Path", true, - StringImportCallback( EnginePathImportCaller( g_strExtraResourcePath ) ), - StringExportCallback( StringExportCaller( g_strExtraResourcePath ) ) - ); + StringImportCallback( EnginePathImportCaller( g_strExtraResourcePath ) ), + StringExportCallback( StringExportCaller( g_strExtraResourcePath ) ) + ); } void Paths_registerPreferencesPage(){ @@ -435,35 +435,35 @@ void Paths_registerPreferencesPage(){ class PathsDialog : public Dialog { public: -GtkWindow* BuildDialog(){ - GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN ); + GtkWindow* BuildDialog(){ + GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN ); - GtkVBox* vbox2 = create_dialog_vbox( 0, 4 ); - gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) ); + GtkVBox* vbox2 = create_dialog_vbox( 0, 4 ); + gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) ); - const char* engine; + const char* engine; #if defined( WIN32 ) - engine = g_pGameDescription->getRequiredKeyValue( "engine_win32" ); + engine = g_pGameDescription->getRequiredKeyValue( "engine_win32" ); #elif defined( __linux__ ) || defined ( __FreeBSD__ ) - engine = g_pGameDescription->getRequiredKeyValue( "engine_linux" ); + engine = g_pGameDescription->getRequiredKeyValue( "engine_linux" ); #elif defined( __APPLE__ ) - engine = g_pGameDescription->getRequiredKeyValue( "engine_macos" ); + engine = g_pGameDescription->getRequiredKeyValue( "engine_macos" ); #else #error "unsupported platform" #endif - StringOutputStream text( 256 ); - text << "Select directory, where game executable sits (typically \"" << engine << "\")\n"; - GtkLabel* label = GTK_LABEL( gtk_label_new( text.c_str() ) ); - gtk_widget_show( GTK_WIDGET( label ) ); - gtk_container_add( GTK_CONTAINER( vbox2 ), GTK_WIDGET( label ) ); + StringOutputStream text( 256 ); + text << "Select directory, where game executable sits (typically \"" << engine << "\")\n"; + GtkLabel* label = GTK_LABEL( gtk_label_new( text.c_str() ) ); + gtk_widget_show( GTK_WIDGET( label ) ); + gtk_container_add( GTK_CONTAINER( vbox2 ), GTK_WIDGET( label ) ); - { - PreferencesPage preferencesPage( *this, GTK_WIDGET( vbox2 ) ); - Paths_constructPreferences( preferencesPage ); + { + PreferencesPage preferencesPage( *this, GTK_WIDGET( vbox2 ) ); + Paths_constructPreferences( preferencesPage ); + } + + return create_simple_modal_dialog_window( "Engine Path Configuration", m_modal, GTK_WIDGET( frame ) ); } - - return create_simple_modal_dialog_window( "Engine Path Configuration", m_modal, GTK_WIDGET( frame ) ); -} }; PathsDialog g_PathsDialog; @@ -538,29 +538,29 @@ void gamemode_set( const char* gamemode ){ class CLoadModule { -const char* m_path; + const char* m_path; public: -CLoadModule( const char* path ) : m_path( path ){ -} -void operator()( const char* name ) const { - char fullname[1024]; - ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" ); - strcpy( fullname, m_path ); - strcat( fullname, name ); - globalOutputStream() << "Found '" << fullname << "'\n"; - GlobalModuleServer_loadModule( fullname ); -} + CLoadModule( const char* path ) : m_path( path ){ + } + void operator()( const char* name ) const { + char fullname[1024]; + ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" ); + strcpy( fullname, m_path ); + strcat( fullname, name ); + globalOutputStream() << "Found '" << fullname << "'\n"; + GlobalModuleServer_loadModule( fullname ); + } }; const char* const c_library_extension = #if defined( WIN32 ) - "dll" + "dll" #elif defined ( __APPLE__ ) - "dylib" + "dylib" #elif defined( __linux__ ) || defined ( __FreeBSD__ ) - "so" + "so" #endif -; + ; void Radiant_loadModules( const char* path ){ Directory_forEach( path, MatchFileExtension( c_library_extension, CLoadModule( path ) ) ); @@ -591,19 +591,19 @@ void SetWorldspawnColour( const Vector3& colour ){ class WorldspawnColourEntityClassObserver : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - SetWorldspawnColour( g_xywindow_globals.color_brushes ); + WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { + void realise(){ + if ( --m_unrealised == 0 ) { + SetWorldspawnColour( g_xywindow_globals.color_brushes ); + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + } } -} }; WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver; @@ -674,8 +674,8 @@ void Radiant_Restart(){ mapname << "\"" << Map_Name( g_map ) << "\""; char *argv[] = { string_clone( environment_get_app_filepath() ), - Map_Unnamed( g_map )? NULL : string_clone( mapname.c_str() ), - NULL }; + Map_Unnamed( g_map )? NULL : string_clone( mapname.c_str() ), + NULL }; #ifdef WIN32 const int status = !_spawnv( P_NOWAIT, argv[0], argv ); #else @@ -888,18 +888,18 @@ typedef Callback1 SetColourCallback; class ChooseColour { -GetColourCallback m_get; -SetColourCallback m_set; + GetColourCallback m_get; + SetColourCallback m_set; public: -ChooseColour( const GetColourCallback& get, const SetColourCallback& set ) - : m_get( get ), m_set( set ){ -} -void operator()(){ - Vector3 colour; - m_get( colour ); - color_dialog( GTK_WIDGET( MainFrame_getWindow() ), colour ); - m_set( colour ); -} + ChooseColour( const GetColourCallback& get, const SetColourCallback& set ) + : m_get( get ), m_set( set ){ + } + void operator()(){ + Vector3 colour; + m_get( colour ); + color_dialog( GTK_WIDGET( MainFrame_getWindow() ), colour ); + m_set( colour ); + } }; @@ -957,33 +957,33 @@ typedef FreeCaller1 TextureBrowserColo class ColoursMenu { public: -ChooseColour m_textureback; -ChooseColour m_xyback; -ChooseColour m_gridmajor; -ChooseColour m_gridminor; -ChooseColour m_gridtext; -ChooseColour m_gridblock; -ChooseColour m_cameraback; -ChooseColour m_brush; -ChooseColour m_selectedbrush; -ChooseColour m_selectedbrush3d; -ChooseColour m_clipper; -ChooseColour m_viewname; + ChooseColour m_textureback; + ChooseColour m_xyback; + ChooseColour m_gridmajor; + ChooseColour m_gridminor; + ChooseColour m_gridtext; + ChooseColour m_gridblock; + ChooseColour m_cameraback; + ChooseColour m_brush; + ChooseColour m_selectedbrush; + ChooseColour m_selectedbrush3d; + ChooseColour m_clipper; + ChooseColour m_viewname; -ColoursMenu() : - m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ), - m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ), - m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ), - m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ), - m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ), - m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ), - m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ), - m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ), - m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), SelectedBrushColourSetCaller() ), - m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), SelectedBrush3dColourSetCaller() ), - m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ), - m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){ -} + ColoursMenu() : + m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ), + m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ), + m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ), + m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ), + m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ), + m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ), + m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ), + m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ), + m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), SelectedBrushColourSetCaller() ), + m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), SelectedBrush3dColourSetCaller() ), + m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ), + m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){ + } }; ColoursMenu g_ColoursMenu; @@ -1109,26 +1109,26 @@ void SelectionSystem_DefaultMode(){ bool EdgeMode(){ return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge; + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge; } bool VertexMode(){ return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex; + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex; } bool FaceMode(){ return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace; + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace; } template class BoolFunctionExport { public: -static void apply( const BoolImportCallback& importCallback ){ - importCallback( BoolFunction() ); -} + static void apply( const BoolImportCallback& importCallback ){ + importCallback( BoolFunction() ); + } }; typedef FreeCaller1::apply> EdgeModeApplyCaller; @@ -1154,7 +1154,7 @@ void ComponentModeChanged(){ void ComponentMode_SelectionChanged( const Selectable& selectable ){ if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().countSelected() == 0 ) { + && GlobalSelectionSystem().countSelected() == 0 ) { SelectionSystem_DefaultMode(); ComponentModeChanged(); } @@ -1235,51 +1235,51 @@ void SelectFaceMode(){ class CloneSelected : public scene::Graph::Walker { -const bool m_makeUnique; -const scene::Node* m_world; + const bool m_makeUnique; + const scene::Node* m_world; public: -CloneSelected( bool makeUnique ) : m_makeUnique( makeUnique ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.size() == 1 ) { + CloneSelected( bool makeUnique ) : m_makeUnique( makeUnique ), m_world( Map_FindWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.size() == 1 ) { + return true; + } + + if ( path.top().get_pointer() == m_world ) { // ignore worldspawn, but keep checking children + return true; + } + + if ( !path.top().get().isRoot() ) { + if ( Instance_isSelected( instance ) ) { + return false; + } + if( m_makeUnique && instance.childSelected() ){ /* clone group entity primitives to new group entity */ + NodeSmartReference clone( Node_Clone_Selected( path.top() ) ); + Map_gatherNamespaced( clone ); + Node_getTraversable( path.parent().get() )->insert( clone ); + return false; + } + } + return true; } - - if ( path.top().get_pointer() == m_world ) { // ignore worldspawn, but keep checking children - return true; - } - - if ( !path.top().get().isRoot() ) { - if ( Instance_isSelected( instance ) ) { - return false; + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( path.size() == 1 ) { + return; } - if( m_makeUnique && instance.childSelected() ){ /* clone group entity primitives to new group entity */ - NodeSmartReference clone( Node_Clone_Selected( path.top() ) ); - Map_gatherNamespaced( clone ); - Node_getTraversable( path.parent().get() )->insert( clone ); - return false; + + if ( path.top().get_pointer() == m_world ) { // ignore worldspawn + return; + } + + if ( !path.top().get().isRoot() ) { + if ( Instance_isSelected( instance ) ) { + NodeSmartReference clone( Node_Clone( path.top() ) ); + Map_gatherNamespaced( clone ); + Node_getTraversable( path.parent().get() )->insert( clone ); + } } } - - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( path.size() == 1 ) { - return; - } - - if ( path.top().get_pointer() == m_world ) { // ignore worldspawn - return; - } - - if ( !path.top().get().isRoot() ) { - if ( Instance_isSelected( instance ) ) { - NodeSmartReference clone( Node_Clone( path.top() ) ); - Map_gatherNamespaced( clone ); - Node_getTraversable( path.parent().get() )->insert( clone ); - } - } -} }; void Scene_Clone_Selected( scene::Graph& graph, bool makeUnique ){ @@ -1739,21 +1739,21 @@ void Texdef_ShiftDown(){ class SnappableSnapToGridSelected : public scene::Graph::Walker { -float m_snap; + float m_snap; public: -SnappableSnapToGridSelected( float snap ) - : m_snap( snap ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Snappable* snappable = Node_getSnappable( path.top() ); - if ( snappable != 0 - && Instance_isSelected( instance ) ) { - snappable->snapto( m_snap ); - } + SnappableSnapToGridSelected( float snap ) + : m_snap( snap ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Snappable* snappable = Node_getSnappable( path.top() ); + if ( snappable != 0 + && Instance_isSelected( instance ) ) { + snappable->snapto( m_snap ); + } + } + return true; } - return true; -} }; void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){ @@ -1762,21 +1762,21 @@ void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){ class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker { -float m_snap; + float m_snap; public: -ComponentSnappableSnapToGridSelected( float snap ) - : m_snap( snap ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance ); - if ( componentSnappable != 0 - && Instance_isSelected( instance ) ) { - componentSnappable->snapComponents( m_snap ); - } + ComponentSnappableSnapToGridSelected( float snap ) + : m_snap( snap ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance ); + if ( componentSnappable != 0 + && Instance_isSelected( instance ) ) { + componentSnappable->snapComponents( m_snap ); + } + } + return true; } - return true; -} }; void Scene_SnapToGrid_Component_Selected( scene::Graph& graph, float snap ){ @@ -1832,8 +1832,8 @@ void window_realize_remove_decoration( GtkWidget* widget, gpointer data ){ class WaitDialog { public: -GtkWindow* m_window; -GtkLabel* m_label; + GtkWindow* m_window; + GtkLabel* m_label; }; WaitDialog create_wait_dialog( const char* title, const char* text, bool modal ){ @@ -1919,7 +1919,7 @@ void ScreenUpdates_Disable( const char* message, const char* title ){ bool isActiveApp = MainFrame_isActiveApp(); g_wait = create_wait_dialog( title, message, - !XYWnd::m_mnuDrop || !gtk_widget_get_visible( GTK_WIDGET( XYWnd::m_mnuDrop ) ) ); //hack: avoid hiding entity menu, clicked with ctrl, by tex/model loading popup + !XYWnd::m_mnuDrop || !gtk_widget_get_visible( GTK_WIDGET( XYWnd::m_mnuDrop ) ) ); //hack: avoid hiding entity menu, clicked with ctrl, by tex/model loading popup if ( isActiveApp ) { gtk_widget_show( GTK_WIDGET( g_wait.m_window ) ); @@ -2671,7 +2671,7 @@ GtkWidget* create_main_statusbar( GtkWidget *pStatusLabel[c_status__count] ){ else{ GtkLabel* label = create_main_statusbar_label(); if( i == c_status_grid ) - gtk_widget_set_tooltip_markup( GTK_WIDGET( frame ), " G: Grid size\n F: map Format\n C: camera Clip distance \n L: texture Lock" ); + gtk_widget_set_tooltip_markup( GTK_WIDGET( frame ), " G: Grid size\n F: map Format\n C: camera Clip distance \n L: texture Lock" ); else gtk_label_set_ellipsize( label, i == c_status_texture? PANGO_ELLIPSIZE_START : PANGO_ELLIPSIZE_END ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( label ) ); @@ -2689,35 +2689,35 @@ WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" ); class WindowFocusPrinter { -const char* m_name; + const char* m_name; -static gboolean frame_event( GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self ){ - globalOutputStream() << self->m_name << " frame_event\n"; - return FALSE; -} -static gboolean keys_changed( GtkWidget *widget, WindowFocusPrinter* self ){ - globalOutputStream() << self->m_name << " keys_changed\n"; - return FALSE; -} -static gboolean notify( GtkWindow* window, gpointer dummy, WindowFocusPrinter* self ){ - if ( gtk_window_is_active( window ) ) { - globalOutputStream() << self->m_name << " takes toplevel focus\n"; + static gboolean frame_event( GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self ){ + globalOutputStream() << self->m_name << " frame_event\n"; + return FALSE; } - else - { - globalOutputStream() << self->m_name << " loses toplevel focus\n"; + static gboolean keys_changed( GtkWidget *widget, WindowFocusPrinter* self ){ + globalOutputStream() << self->m_name << " keys_changed\n"; + return FALSE; + } + static gboolean notify( GtkWindow* window, gpointer dummy, WindowFocusPrinter* self ){ + if ( gtk_window_is_active( window ) ) { + globalOutputStream() << self->m_name << " takes toplevel focus\n"; + } + else + { + globalOutputStream() << self->m_name << " loses toplevel focus\n"; + } + return FALSE; } - return FALSE; -} public: -WindowFocusPrinter( const char* name ) : m_name( name ){ -} -void connect( GtkWindow* toplevel_window ){ - g_signal_connect( G_OBJECT( toplevel_window ), "notify::has_toplevel_focus", G_CALLBACK( notify ), this ); - g_signal_connect( G_OBJECT( toplevel_window ), "notify::is_active", G_CALLBACK( notify ), this ); - g_signal_connect( G_OBJECT( toplevel_window ), "keys_changed", G_CALLBACK( keys_changed ), this ); - g_signal_connect( G_OBJECT( toplevel_window ), "frame_event", G_CALLBACK( frame_event ), this ); -} + WindowFocusPrinter( const char* name ) : m_name( name ){ + } + void connect( GtkWindow* toplevel_window ){ + g_signal_connect( G_OBJECT( toplevel_window ), "notify::has_toplevel_focus", G_CALLBACK( notify ), this ); + g_signal_connect( G_OBJECT( toplevel_window ), "notify::is_active", G_CALLBACK( notify ), this ); + g_signal_connect( G_OBJECT( toplevel_window ), "keys_changed", G_CALLBACK( keys_changed ), this ); + g_signal_connect( G_OBJECT( toplevel_window ), "frame_event", G_CALLBACK( frame_event ), this ); + } }; WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" ); @@ -2726,17 +2726,17 @@ WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" ); class MainWindowActive { -static gboolean notify( GtkWindow* window, gpointer dummy, MainWindowActive* self ){ - if ( g_wait.m_window != 0 && gtk_window_is_active( window ) && !gtk_widget_get_visible( GTK_WIDGET( g_wait.m_window ) ) ) { - gtk_widget_show( GTK_WIDGET( g_wait.m_window ) ); - } + static gboolean notify( GtkWindow* window, gpointer dummy, MainWindowActive* self ){ + if ( g_wait.m_window != 0 && gtk_window_is_active( window ) && !gtk_widget_get_visible( GTK_WIDGET( g_wait.m_window ) ) ) { + gtk_widget_show( GTK_WIDGET( g_wait.m_window ) ); + } - return FALSE; -} + return FALSE; + } public: -void connect( GtkWindow* toplevel_window ){ - g_signal_connect( G_OBJECT( toplevel_window ), "notify::is-active", G_CALLBACK( notify ), this ); -} + void connect( GtkWindow* toplevel_window ){ + g_signal_connect( G_OBJECT( toplevel_window ), "notify::is-active", G_CALLBACK( notify ), this ); + } }; MainWindowActive g_MainWindowActive; @@ -3316,7 +3316,7 @@ void MainFrame::Create(){ EverySecondTimer_enable(); if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED || - g_layout_globals.nState & GDK_WINDOW_STATE_ICONIFIED ) { + g_layout_globals.nState & GDK_WINDOW_STATE_ICONIFIED ) { gtk_window_maximize( window ); } if ( g_layout_globals.nState & GDK_WINDOW_STATE_FULLSCREEN ) { @@ -3443,9 +3443,9 @@ void MainFrame::SetGridStatus(){ StringOutputStream status( 64 ); const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON " : "OFF "; status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize() - << " F:" << GridStatus_getTexdefTypeIdLabel() - << " C:" << GridStatus_getFarClipDistance() - << " L:" << lock; + << " F:" << GridStatus_getTexdefTypeIdLabel() + << " C:" << GridStatus_getFarClipDistance() + << " L:" << lock; SetStatusText( c_status_grid, status.c_str() ); } @@ -3500,44 +3500,44 @@ void Layout_constructPreferences( PreferencesPage& page ){ { const char* layouts[] = { "window1.png", "window2.png", "window3.png", "window4.png" }; page.appendRadioIcons( - "Window Layout", - STRING_ARRAY_RANGE( layouts ), - LatchedImportCaller( g_Layout_viewStyle ), - IntExportCaller( g_Layout_viewStyle.m_latched ) - ); + "Window Layout", + STRING_ARRAY_RANGE( layouts ), + LatchedImportCaller( g_Layout_viewStyle ), + IntExportCaller( g_Layout_viewStyle.m_latched ) + ); } page.appendCheckBox( - "", "Detachable Menus", - LatchedImportCaller( g_Layout_enableDetachableMenus ), - BoolExportCaller( g_Layout_enableDetachableMenus.m_latched ) - ); + "", "Detachable Menus", + LatchedImportCaller( g_Layout_enableDetachableMenus ), + BoolExportCaller( g_Layout_enableDetachableMenus.m_latched ) + ); page.appendCheckBox( - "", "Main Toolbar", - LatchedImportCaller( g_Layout_enableMainToolbar ), - BoolExportCaller( g_Layout_enableMainToolbar.m_latched ) - ); + "", "Main Toolbar", + LatchedImportCaller( g_Layout_enableMainToolbar ), + BoolExportCaller( g_Layout_enableMainToolbar.m_latched ) + ); if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) { page.appendCheckBox( - "", "Patch Toolbar", - LatchedImportCaller( g_Layout_enablePatchToolbar ), - BoolExportCaller( g_Layout_enablePatchToolbar.m_latched ) - ); + "", "Patch Toolbar", + LatchedImportCaller( g_Layout_enablePatchToolbar ), + BoolExportCaller( g_Layout_enablePatchToolbar.m_latched ) + ); } page.appendCheckBox( - "", "Plugin Toolbar", - LatchedImportCaller( g_Layout_enablePluginToolbar ), - BoolExportCaller( g_Layout_enablePluginToolbar.m_latched ) - ); + "", "Plugin Toolbar", + LatchedImportCaller( g_Layout_enablePluginToolbar ), + BoolExportCaller( g_Layout_enablePluginToolbar.m_latched ) + ); page.appendCheckBox( - "", "Filter Toolbar", - LatchedImportCaller( g_Layout_enableFilterToolbar ), - BoolExportCaller( g_Layout_enableFilterToolbar.m_latched ) - ); + "", "Filter Toolbar", + LatchedImportCaller( g_Layout_enableFilterToolbar ), + BoolExportCaller( g_Layout_enableFilterToolbar.m_latched ) + ); page.appendCheckBox( - "", "Single Scrollable Toolbar", - LatchedImportCaller( g_Layout_SingleToolbar ), - BoolExportCaller( g_Layout_SingleToolbar.m_latched ) - ); + "", "Single Scrollable Toolbar", + LatchedImportCaller( g_Layout_SingleToolbar ), + BoolExportCaller( g_Layout_SingleToolbar.m_latched ) + ); } void Layout_constructPage( PreferenceGroup& group ){ @@ -3726,15 +3726,15 @@ void MainFrame_Construct(){ g_strEnginePath_was_empty_1st_start = true; const char* ENGINEPATH_ATTRIBUTE = #if defined( WIN32 ) - "enginepath_win32" + "enginepath_win32" #elif defined( __APPLE__ ) - "enginepath_macos" + "enginepath_macos" #elif defined( __linux__ ) || defined ( __FreeBSD__ ) - "enginepath_linux" + "enginepath_linux" #else #error "unknown platform" #endif - ; + ; g_strEnginePath = StringOutputStream( 256 )( DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) ) ).c_str(); } diff --git a/radiant/mainframe.h b/radiant/mainframe.h index 15238367..90b11540 100644 --- a/radiant/mainframe.h +++ b/radiant/mainframe.h @@ -51,91 +51,91 @@ const int c_status__count = 7; class MainFrame { public: -enum EViewStyle -{ - eRegular = 0, - eFloating = 1, - eSplit = 2, - eRegularLeft = 3, -}; + enum EViewStyle + { + eRegular = 0, + eFloating = 1, + eSplit = 2, + eRegularLeft = 3, + }; -MainFrame(); -~MainFrame(); + MainFrame(); + ~MainFrame(); -GtkWindow* m_window; + GtkWindow* m_window; private: -void Create(); -void SaveWindowInfo(); -void Shutdown(); + void Create(); + void SaveWindowInfo(); + void Shutdown(); public: -GtkWidget* m_vSplit; -GtkWidget* m_hSplit; -GtkWidget* m_vSplit2; + GtkWidget* m_vSplit; + GtkWidget* m_hSplit; + GtkWidget* m_vSplit2; private: -XYWnd* m_pXYWnd; -XYWnd* m_pYZWnd; -XYWnd* m_pXZWnd; -CamWnd* m_pCamWnd; -ZWnd* m_pZWnd; -XYWnd* m_pActiveXY; + XYWnd* m_pXYWnd; + XYWnd* m_pYZWnd; + XYWnd* m_pXZWnd; + CamWnd* m_pCamWnd; + ZWnd* m_pZWnd; + XYWnd* m_pActiveXY; -CopiedString m_status[c_status__count]; -GtkWidget *m_statusLabel[c_status__count]; + CopiedString m_status[c_status__count]; + GtkWidget *m_statusLabel[c_status__count]; -EViewStyle m_nCurrentStyle; -WindowPositionTracker m_position_tracker; + EViewStyle m_nCurrentStyle; + WindowPositionTracker m_position_tracker; -IdleDraw m_idleRedrawStatusText; + IdleDraw m_idleRedrawStatusText; public: -void SetStatusText( int status_n, const char* status ); -void UpdateStatusText(); -void RedrawStatusText(); -typedef MemberCaller RedrawStatusTextCaller; + void SetStatusText( int status_n, const char* status ); + void UpdateStatusText(); + void RedrawStatusText(); + typedef MemberCaller RedrawStatusTextCaller; -void SetGridStatus(); -typedef MemberCaller SetGridStatusCaller; + void SetGridStatus(); + typedef MemberCaller SetGridStatusCaller; -void SetActiveXY( XYWnd* p ); -XYWnd* ActiveXY(){ - return m_pActiveXY; -} -XYWnd* GetXYWnd(){ - return m_pXYWnd; -} -XYWnd* GetXZWnd(){ - return m_pXZWnd; -} -XYWnd* GetYZWnd(){ - return m_pYZWnd; -} -ZWnd* GetZWnd(){ - return m_pZWnd; -} -CamWnd* GetCamWnd(){ - return m_pCamWnd; -} + void SetActiveXY( XYWnd* p ); + XYWnd* ActiveXY(){ + return m_pActiveXY; + } + XYWnd* GetXYWnd(){ + return m_pXYWnd; + } + XYWnd* GetXZWnd(){ + return m_pXZWnd; + } + XYWnd* GetYZWnd(){ + return m_pYZWnd; + } + ZWnd* GetZWnd(){ + return m_pZWnd; + } + CamWnd* GetCamWnd(){ + return m_pCamWnd; + } -template -void forEachXYWnd( const Functor& functor ){ - for( XYWnd* xywnd : { GetXYWnd(), GetXZWnd(), GetYZWnd() } ) - if( xywnd ) - functor( xywnd ); -} + template + void forEachXYWnd( const Functor& functor ){ + for( XYWnd* xywnd : { GetXYWnd(), GetXZWnd(), GetYZWnd() } ) + if( xywnd ) + functor( xywnd ); + } -EViewStyle CurrentStyle(){ - return m_nCurrentStyle; -} -bool FloatingGroupDialog(){ - return CurrentStyle() == eFloating || CurrentStyle() == eSplit; -} + EViewStyle CurrentStyle(){ + return m_nCurrentStyle; + } + bool FloatingGroupDialog(){ + return CurrentStyle() == eFloating || CurrentStyle() == eSplit; + } }; extern MainFrame* g_pParentWnd; @@ -162,12 +162,12 @@ void ScreenUpdates_process(); class ScopeDisableScreenUpdates { public: -ScopeDisableScreenUpdates( const char* message, const char* title ){ - ScreenUpdates_Disable( message, title ); -} -~ScopeDisableScreenUpdates(){ - ScreenUpdates_Enable(); -} + ScopeDisableScreenUpdates( const char* message, const char* title ){ + ScreenUpdates_Disable( message, title ); + } + ~ScopeDisableScreenUpdates(){ + ScreenUpdates_Enable(); + } }; diff --git a/radiant/map.cpp b/radiant/map.cpp index b7814aec..1dad48d7 100644 --- a/radiant/map.cpp +++ b/radiant/map.cpp @@ -82,106 +82,106 @@ class NameObserver { -UniqueNames& m_names; -CopiedString m_name; + UniqueNames& m_names; + CopiedString m_name; -void construct(){ - if ( !empty() ) { - //globalOutputStream() << "construct " << makeQuoted(c_str()) << "\n"; - m_names.insert( name_read( c_str() ) ); + void construct(){ + if ( !empty() ) { + //globalOutputStream() << "construct " << makeQuoted(c_str()) << "\n"; + m_names.insert( name_read( c_str() ) ); + } } -} -void destroy(){ - if ( !empty() ) { - //globalOutputStream() << "destroy " << makeQuoted(c_str()) << "\n"; - m_names.erase( name_read( c_str() ) ); + void destroy(){ + if ( !empty() ) { + //globalOutputStream() << "destroy " << makeQuoted(c_str()) << "\n"; + m_names.erase( name_read( c_str() ) ); + } } -} -NameObserver& operator=( const NameObserver& other ); + NameObserver& operator=( const NameObserver& other ); public: -NameObserver( UniqueNames& names ) : m_names( names ){ - construct(); -} -NameObserver( const NameObserver& other ) : m_names( other.m_names ), m_name( other.m_name ){ - construct(); -} -~NameObserver(){ - destroy(); -} -bool empty() const { - return string_empty( c_str() ); -} -const char* c_str() const { - return m_name.c_str(); -} -void nameChanged( const char* name ){ - destroy(); - m_name = name; - construct(); -} -typedef MemberCaller1 NameChangedCaller; + NameObserver( UniqueNames& names ) : m_names( names ){ + construct(); + } + NameObserver( const NameObserver& other ) : m_names( other.m_names ), m_name( other.m_name ){ + construct(); + } + ~NameObserver(){ + destroy(); + } + bool empty() const { + return string_empty( c_str() ); + } + const char* c_str() const { + return m_name.c_str(); + } + void nameChanged( const char* name ){ + destroy(); + m_name = name; + construct(); + } + typedef MemberCaller1 NameChangedCaller; }; class BasicNamespace : public Namespace { -typedef std::map Names; -Names m_names; -UniqueNames m_uniqueNames; + typedef std::map Names; + Names m_names; + UniqueNames m_uniqueNames; public: -~BasicNamespace(){ - ASSERT_MESSAGE( m_names.empty(), "namespace: names still registered at shutdown" ); -} -void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ){ - std::pair result = m_names.insert( Names::value_type( setName, m_uniqueNames ) ); - ASSERT_MESSAGE( result.second, "cannot attach name" ); - attachObserver( NameObserver::NameChangedCaller( ( *result.first ).second ) ); - //globalOutputStream() << "attach: " << reinterpret_cast(setName) << "\n"; -} -void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ){ - Names::iterator i = m_names.find( setName ); - ASSERT_MESSAGE( i != m_names.end(), "cannot detach name" ); - //globalOutputStream() << "detach: " << reinterpret_cast(setName) << "\n"; - detachObserver( NameObserver::NameChangedCaller( ( *i ).second ) ); - m_names.erase( i ); -} - -void makeUnique( const char* name, const NameCallback& setName ) const { - char buffer[1024]; - name_write( buffer, m_uniqueNames.make_unique( name_read( name ) ) ); - setName( buffer ); -} - -void mergeNames( const BasicNamespace& other ) const { - typedef std::list SetNameCallbacks; - typedef std::map NameGroups; - NameGroups groups; - - UniqueNames uniqueNames( other.m_uniqueNames ); - - for ( Names::const_iterator i = m_names.begin(); i != m_names.end(); ++i ) - { - groups[( *i ).second.c_str()].push_back( ( *i ).first ); + ~BasicNamespace(){ + ASSERT_MESSAGE( m_names.empty(), "namespace: names still registered at shutdown" ); + } + void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ){ + std::pair result = m_names.insert( Names::value_type( setName, m_uniqueNames ) ); + ASSERT_MESSAGE( result.second, "cannot attach name" ); + attachObserver( NameObserver::NameChangedCaller( ( *result.first ).second ) ); + //globalOutputStream() << "attach: " << reinterpret_cast(setName) << "\n"; + } + void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ){ + Names::iterator i = m_names.find( setName ); + ASSERT_MESSAGE( i != m_names.end(), "cannot detach name" ); + //globalOutputStream() << "detach: " << reinterpret_cast(setName) << "\n"; + detachObserver( NameObserver::NameChangedCaller( ( *i ).second ) ); + m_names.erase( i ); } - for ( NameGroups::iterator i = groups.begin(); i != groups.end(); ++i ) - { - name_t uniqueName( uniqueNames.make_unique( name_read( ( *i ).first.c_str() ) ) ); - uniqueNames.insert( uniqueName ); - + void makeUnique( const char* name, const NameCallback& setName ) const { char buffer[1024]; - name_write( buffer, uniqueName ); + name_write( buffer, m_uniqueNames.make_unique( name_read( name ) ) ); + setName( buffer ); + } - //globalOutputStream() << "renaming " << makeQuoted((*i).first.c_str()) << " to " << makeQuoted(buffer) << "\n"; + void mergeNames( const BasicNamespace& other ) const { + typedef std::list SetNameCallbacks; + typedef std::map NameGroups; + NameGroups groups; - SetNameCallbacks& setNameCallbacks = ( *i ).second; + UniqueNames uniqueNames( other.m_uniqueNames ); - for ( SetNameCallbacks::const_iterator j = setNameCallbacks.begin(); j != setNameCallbacks.end(); ++j ) + for ( Names::const_iterator i = m_names.begin(); i != m_names.end(); ++i ) { - ( *j )( buffer ); + groups[( *i ).second.c_str()].push_back( ( *i ).first ); + } + + for ( NameGroups::iterator i = groups.begin(); i != groups.end(); ++i ) + { + name_t uniqueName( uniqueNames.make_unique( name_read( ( *i ).first.c_str() ) ) ); + uniqueNames.insert( uniqueName ); + + char buffer[1024]; + name_write( buffer, uniqueName ); + + //globalOutputStream() << "renaming " << makeQuoted((*i).first.c_str()) << " to " << makeQuoted(buffer) << "\n"; + + SetNameCallbacks& setNameCallbacks = ( *i ).second; + + for ( SetNameCallbacks::const_iterator j = setNameCallbacks.begin(); j != setNameCallbacks.end(); ++j ) + { + ( *j )( buffer ); + } } } -} }; BasicNamespace g_defaultNamespace; @@ -189,17 +189,17 @@ BasicNamespace g_cloneNamespace; class NamespaceAPI { -Namespace* m_namespace; + Namespace* m_namespace; public: -typedef Namespace Type; -STRING_CONSTANT( Name, "*" ); + typedef Namespace Type; + STRING_CONSTANT( Name, "*" ); -NamespaceAPI(){ - m_namespace = &g_defaultNamespace; -} -Namespace* getTable(){ - return m_namespace; -} + NamespaceAPI(){ + m_namespace = &g_defaultNamespace; + } + Namespace* getTable(){ + return m_namespace; + } }; typedef SingletonModule NamespaceModule; @@ -223,10 +223,10 @@ void Node_gatherNamespaced( scene::Node& node ){ class GatherNamespaced : public scene::Traversable::Walker { public: -bool pre( scene::Node& node ) const { - Node_gatherNamespaced( node ); - return true; -} + bool pre( scene::Node& node ) const { + Node_gatherNamespaced( node ); + return true; + } }; void Map_gatherNamespaced( scene::Node& root ){ @@ -251,23 +251,23 @@ void Map_mergeClonedNames( bool makeUnique /*= true*/ ){ class WorldNode { -scene::Node* m_node; + scene::Node* m_node; public: -WorldNode() - : m_node( 0 ){ -} -void set( scene::Node* node ){ - if ( m_node != 0 ) { - m_node->DecRef(); + WorldNode() + : m_node( 0 ){ } - m_node = node; - if ( m_node != 0 ) { - m_node->IncRef(); + void set( scene::Node* node ){ + if ( m_node != 0 ) { + m_node->DecRef(); + } + m_node = node; + if ( m_node != 0 ) { + m_node->IncRef(); + } + } + scene::Node* get() const { + return m_node; } -} -scene::Node* get() const { - return m_node; -} }; class Map; @@ -279,52 +279,52 @@ void Map_SetWorldspawn( Map& map, scene::Node* node ); class Map : public ModuleObserver { public: -CopiedString m_name; -Resource* m_resource; -bool m_valid; + CopiedString m_name; + Resource* m_resource; + bool m_valid; -bool m_modified; -void ( *m_modified_changed )( const Map& ); + bool m_modified; + void ( *m_modified_changed )( const Map& ); -Signal0 m_mapValidCallbacks; + Signal0 m_mapValidCallbacks; -WorldNode m_world_node; // "classname" "worldspawn" ! + WorldNode m_world_node; // "classname" "worldspawn" ! -Map() : m_resource( 0 ), m_valid( false ), m_modified_changed( Map_UpdateTitle ){ -} + Map() : m_resource( 0 ), m_valid( false ), m_modified_changed( Map_UpdateTitle ){ + } -void realise(){ - if ( m_resource != 0 ) { - if ( Map_Unnamed( *this ) ) { - g_map.m_resource->setNode( NewMapRoot( "" ).get_pointer() ); - MapFile* map = Node_getMapFile( *g_map.m_resource->getNode() ); - if ( map != 0 ) { - map->save(); + void realise(){ + if ( m_resource != 0 ) { + if ( Map_Unnamed( *this ) ) { + g_map.m_resource->setNode( NewMapRoot( "" ).get_pointer() ); + MapFile* map = Node_getMapFile( *g_map.m_resource->getNode() ); + if ( map != 0 ) { + map->save(); + } } + else + { + m_resource->load(); + } + + GlobalSceneGraph().insert_root( *m_resource->getNode() ); + + AutoSave_clear(); + + Map_SetValid( g_map, true ); } - else - { - m_resource->load(); + } + void unrealise(){ + if ( m_resource != 0 ) { + Map_SetValid( g_map, false ); + Map_SetWorldspawn( g_map, 0 ); + + + GlobalUndoSystem().clear(); + + GlobalSceneGraph().erase_root(); } - - GlobalSceneGraph().insert_root( *m_resource->getNode() ); - - AutoSave_clear(); - - Map_SetValid( g_map, true ); } -} -void unrealise(){ - if ( m_resource != 0 ) { - Map_SetValid( g_map, false ); - Map_SetWorldspawn( g_map, 0 ); - - - GlobalUndoSystem().clear(); - - GlobalSceneGraph().erase_root(); - } -} }; Map g_map; @@ -422,22 +422,22 @@ void Map_Free(){ class EntityFindByClassname : public scene::Graph::Walker { -const char* m_name; -Entity*& m_entity; + const char* m_name; + Entity*& m_entity; public: -EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ - m_entity = 0; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_entity == 0 ) { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 - && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { - m_entity = entity; - } + EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ + m_entity = 0; + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_entity == 0 ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + m_entity = entity; + } + } + return true; } - return true; -} }; Entity* Scene_FindEntityByClass( const char* name ){ @@ -512,14 +512,14 @@ inline bool node_is_worldspawn( scene::Node& node ){ class entity_updateworldspawn : public scene::Traversable::Walker { public: -bool pre( scene::Node& node ) const { - if ( node_is_worldspawn( node ) ) { - if ( Map_GetWorldspawn( g_map ) == 0 ) { - Map_SetWorldspawn( g_map, &node ); + bool pre( scene::Node& node ) const { + if ( node_is_worldspawn( node ) ) { + if ( Map_GetWorldspawn( g_map ) == 0 ) { + Map_SetWorldspawn( g_map, &node ); + } } + return false; } - return false; -} }; scene::Node* Map_FindWorldspawn( Map& map ){ @@ -533,16 +533,16 @@ scene::Node* Map_FindWorldspawn( Map& map ){ class CollectAllWalker : public scene::Traversable::Walker { -scene::Node& m_root; -UnsortedNodeSet& m_nodes; + scene::Node& m_root; + UnsortedNodeSet& m_nodes; public: -CollectAllWalker( scene::Node& root, UnsortedNodeSet& nodes ) : m_root( root ), m_nodes( nodes ){ -} -bool pre( scene::Node& node ) const { - m_nodes.insert( NodeSmartReference( node ) ); - Node_getTraversable( m_root )->erase( node ); - return false; -} + CollectAllWalker( scene::Node& root, UnsortedNodeSet& nodes ) : m_root( root ), m_nodes( nodes ){ + } + bool pre( scene::Node& node ) const { + m_nodes.insert( NodeSmartReference( node ) ); + Node_getTraversable( m_root )->erase( node ); + return false; + } }; void Node_insertChildFirst( scene::Node& parent, scene::Node& child ){ @@ -576,95 +576,95 @@ scene::Node& Map_FindOrInsertWorldspawn( Map& map ){ class MapMergeAll : public scene::Traversable::Walker { -mutable scene::Path m_path; + mutable scene::Path m_path; public: -MapMergeAll( const scene::Path& root ) - : m_path( root ){ -} -bool pre( scene::Node& node ) const { - Node_getTraversable( m_path.top() )->insert( node ); - m_path.push( makeReference( node ) ); - selectPath( m_path, true ); - return false; -} -void post( scene::Node& node ) const { - m_path.pop(); -} + MapMergeAll( const scene::Path& root ) + : m_path( root ){ + } + bool pre( scene::Node& node ) const { + Node_getTraversable( m_path.top() )->insert( node ); + m_path.push( makeReference( node ) ); + selectPath( m_path, true ); + return false; + } + void post( scene::Node& node ) const { + m_path.pop(); + } }; class MapMergeEntities : public scene::Traversable::Walker { -mutable scene::Path m_path; + mutable scene::Path m_path; public: -MapMergeEntities( const scene::Path& root ) - : m_path( root ){ -} -bool pre( scene::Node& node ) const { - if ( node_is_worldspawn( node ) ) { - scene::Node* world_node = Map_FindWorldspawn( g_map ); - if ( world_node == 0 ) { - Map_SetWorldspawn( g_map, &node ); - Node_getTraversable( m_path.top().get() )->insert( node ); + MapMergeEntities( const scene::Path& root ) + : m_path( root ){ + } + bool pre( scene::Node& node ) const { + if ( node_is_worldspawn( node ) ) { + scene::Node* world_node = Map_FindWorldspawn( g_map ); + if ( world_node == 0 ) { + Map_SetWorldspawn( g_map, &node ); + Node_getTraversable( m_path.top().get() )->insert( node ); + m_path.push( makeReference( node ) ); + Node_getTraversable( node )->traverse( SelectChildren( m_path ) ); + } + else + { + m_path.push( makeReference( *world_node ) ); + Node_getTraversable( node )->traverse( MapMergeAll( m_path ) ); + } + } + else + { + Node_getTraversable( m_path.top() )->insert( node ); m_path.push( makeReference( node ) ); - Node_getTraversable( node )->traverse( SelectChildren( m_path ) ); - } - else - { - m_path.push( makeReference( *world_node ) ); - Node_getTraversable( node )->traverse( MapMergeAll( m_path ) ); + if ( node_is_group( node ) ) { + Node_getTraversable( node )->traverse( SelectChildren( m_path ) ); + } + else + { + selectPath( m_path, true ); + } } + return false; } - else - { - Node_getTraversable( m_path.top() )->insert( node ); - m_path.push( makeReference( node ) ); - if ( node_is_group( node ) ) { - Node_getTraversable( node )->traverse( SelectChildren( m_path ) ); - } - else - { - selectPath( m_path, true ); - } + void post( scene::Node& node ) const { + m_path.pop(); } - return false; -} -void post( scene::Node& node ) const { - m_path.pop(); -} }; class BasicContainer : public scene::Node::Symbiot { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -TraversableNodeSet m_traverse; + scene::Node m_node; + TraversableNodeSet m_traverse; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_traverse; -} + scene::Traversable& get( NullType){ + return m_traverse; + } -BasicContainer() : m_node( this, this, StaticTypeCasts::instance().get() ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + BasicContainer() : m_node( this, this, StaticTypeCasts::instance().get() ){ + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } }; /// Merges the map graph rooted at \p node into the global scene-graph. @@ -733,31 +733,31 @@ inline scene::Node& node_clone( scene::Node& node ){ class CloneAll : public scene::Traversable::Walker { -mutable scene::Path m_path; + mutable scene::Path m_path; public: -CloneAll( scene::Node& root ) - : m_path( makeReference( root ) ){ -} -bool pre( scene::Node& node ) const { - if ( node.isRoot() ) { - return false; + CloneAll( scene::Node& root ) + : m_path( makeReference( root ) ){ } + bool pre( scene::Node& node ) const { + if ( node.isRoot() ) { + return false; + } - m_path.push( makeReference( node_clone( node ) ) ); - m_path.top().get().IncRef(); + m_path.push( makeReference( node_clone( node ) ) ); + m_path.top().get().IncRef(); - return true; -} -void post( scene::Node& node ) const { - if ( node.isRoot() ) { - return; + return true; } + void post( scene::Node& node ) const { + if ( node.isRoot() ) { + return; + } - Node_getTraversable( m_path.parent() )->insert( m_path.top() ); + Node_getTraversable( m_path.parent() )->insert( m_path.top() ); - m_path.top().get().DecRef(); - m_path.pop(); -} + m_path.top().get().DecRef(); + m_path.pop(); + } }; scene::Node& Node_Clone( scene::Node& node ){ @@ -773,35 +773,35 @@ bool Node_instanceSelected( scene::Node& node ); class CloneAllSelected : public scene::Traversable::Walker { -mutable scene::Path m_path; + mutable scene::Path m_path; public: -CloneAllSelected( scene::Node& root ) - : m_path( makeReference( root ) ){ -} -bool pre( scene::Node& node ) const { - if ( node.isRoot() ) { - return false; + CloneAllSelected( scene::Node& root ) + : m_path( makeReference( root ) ){ } + bool pre( scene::Node& node ) const { + if ( node.isRoot() ) { + return false; + } - if( Node_instanceSelected( node ) ){ - m_path.push( makeReference( node_clone( node ) ) ); - m_path.top().get().IncRef(); + if( Node_instanceSelected( node ) ){ + m_path.push( makeReference( node_clone( node ) ) ); + m_path.top().get().IncRef(); + } + + return true; } + void post( scene::Node& node ) const { + if ( node.isRoot() ) { + return; + } - return true; -} -void post( scene::Node& node ) const { - if ( node.isRoot() ) { - return; + if( Node_instanceSelected( node ) ){ + Node_getTraversable( m_path.parent() )->insert( m_path.top() ); + + m_path.top().get().DecRef(); + m_path.pop(); + } } - - if( Node_instanceSelected( node ) ){ - Node_getTraversable( m_path.parent() )->insert( m_path.top() ); - - m_path.top().get().DecRef(); - m_path.pop(); - } -} }; scene::Node& Node_Clone_Selected( scene::Node& node ){ @@ -818,22 +818,24 @@ typedef std::map EntityBreakdown; class EntityBreakdownWalker : public scene::Graph::Walker { -EntityBreakdown& m_entitymap; + EntityBreakdown& m_entitymap; public: -EntityBreakdownWalker( EntityBreakdown& entitymap ) - : m_entitymap( entitymap ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ) { - const EntityClass& eclass = entity->getEntityClass(); - if ( m_entitymap.find( eclass.name() ) == m_entitymap.end() ) { - m_entitymap[eclass.name()] = 1; - } - else{ ++m_entitymap[eclass.name()]; } + EntityBreakdownWalker( EntityBreakdown& entitymap ) + : m_entitymap( entitymap ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ) { + const EntityClass& eclass = entity->getEntityClass(); + if ( m_entitymap.find( eclass.name() ) == m_entitymap.end() ) { + m_entitymap[eclass.name()] = 1; + } + else{ + ++m_entitymap[eclass.name()]; + } + } + return true; } - return true; -} }; void Scene_EntityBreakdown( EntityBreakdown& entitymap ){ @@ -842,33 +844,33 @@ void Scene_EntityBreakdown( EntityBreakdown& entitymap ){ class CountStuffWalker : public scene::Graph::Walker { -int& m_ents_ingame; -int& m_groupents; -int& m_groupents_ingame; + int& m_ents_ingame; + int& m_groupents; + int& m_groupents_ingame; public: -CountStuffWalker( int& ents_ingame, int& groupents, int& groupents_ingame ) - : m_ents_ingame( ents_ingame ), m_groupents( groupents ), m_groupents_ingame( groupents_ingame ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - if( entity->isContainer() ){ - ++m_groupents; - if( !string_equal_nocase( "func_group", entity->getKeyValue( "classname" ) ) && - !string_equal_nocase( "_decal", entity->getKeyValue( "classname" ) ) && - !string_equal_nocase_n( "func_detail", entity->getKeyValue( "classname" ), 11 ) ){ - ++m_groupents_ingame; + CountStuffWalker( int& ents_ingame, int& groupents, int& groupents_ingame ) + : m_ents_ingame( ents_ingame ), m_groupents( groupents ), m_groupents_ingame( groupents_ingame ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + if( entity->isContainer() ){ + ++m_groupents; + if( !string_equal_nocase( "func_group", entity->getKeyValue( "classname" ) ) && + !string_equal_nocase( "_decal", entity->getKeyValue( "classname" ) ) && + !string_equal_nocase_n( "func_detail", entity->getKeyValue( "classname" ), 11 ) ){ + ++m_groupents_ingame; + ++m_ents_ingame; + } + return true; + } + if( !string_equal_nocase_n( "light", entity->getKeyValue( "classname" ), 5 ) && + !string_equal_nocase( "misc_model", entity->getKeyValue( "classname" ) ) ){ ++m_ents_ingame; } - return true; - } - if( !string_equal_nocase_n( "light", entity->getKeyValue( "classname" ), 5 ) && - !string_equal_nocase( "misc_model", entity->getKeyValue( "classname" ) ) ){ - ++m_ents_ingame; } + return true; } - return true; -} }; void Scene_CountStuff( int& ents_ingame, int& groupents, int& groupents_ingame ){ @@ -908,16 +910,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Total Brushes:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_brushes = label; } @@ -925,16 +927,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Total Patches:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_patches = label; } @@ -942,16 +944,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Total Entities:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_ents = label; } @@ -959,16 +961,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Ingame Entities:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_ents_ingame = label; } @@ -976,16 +978,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Group Entities:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_groupents = label; } @@ -993,16 +995,16 @@ void DoMapInfo(){ GtkWidget* label = gtk_label_new( "Ingame Group Entities:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); } { GtkWidget* label = gtk_label_new( "" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 2, 3, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 3, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 3, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0.0, 0.5 ); w_groupents_ingame = label; } @@ -1121,17 +1123,17 @@ void DoMapInfo(){ class ScopeTimer { -Timer m_timer; -const char* m_message; + Timer m_timer; + const char* m_message; public: -ScopeTimer( const char* message ) - : m_message( message ){ - m_timer.start(); -} -~ScopeTimer(){ - double elapsed_time = m_timer.elapsed_msec() / 1000.f; - globalOutputStream() << m_message << " timer: " << FloatFormat( elapsed_time, 5, 2 ) << " second(s) elapsed\n"; -} + ScopeTimer( const char* message ) + : m_message( message ){ + m_timer.start(); + } + ~ScopeTimer(){ + double elapsed_time = m_timer.elapsed_msec() / 1000.f; + globalOutputStream() << m_message << " timer: " << FloatFormat( elapsed_time, 5, 2 ) << " second(s) elapsed\n"; + } }; /* @@ -1172,52 +1174,52 @@ void Map_LoadFile( const char *filename ){ class Excluder { public: -virtual bool excluded( scene::Node& node ) const = 0; + virtual bool excluded( scene::Node& node ) const = 0; }; class ExcludeWalker : public scene::Traversable::Walker { -const scene::Traversable::Walker& m_walker; -const Excluder* m_exclude; -mutable bool m_skip; + const scene::Traversable::Walker& m_walker; + const Excluder* m_exclude; + mutable bool m_skip; public: -ExcludeWalker( const scene::Traversable::Walker& walker, const Excluder& exclude ) - : m_walker( walker ), m_exclude( &exclude ), m_skip( false ){ -} -bool pre( scene::Node& node ) const { - if ( m_exclude->excluded( node ) || node.isRoot() ) { - m_skip = true; - return false; + ExcludeWalker( const scene::Traversable::Walker& walker, const Excluder& exclude ) + : m_walker( walker ), m_exclude( &exclude ), m_skip( false ){ } - else - { - m_walker.pre( node ); + bool pre( scene::Node& node ) const { + if ( m_exclude->excluded( node ) || node.isRoot() ) { + m_skip = true; + return false; + } + else + { + m_walker.pre( node ); + } + return true; } - return true; -} -void post( scene::Node& node ) const { - if ( m_skip ) { - m_skip = false; + void post( scene::Node& node ) const { + if ( m_skip ) { + m_skip = false; + } + else + { + m_walker.post( node ); + } } - else - { - m_walker.post( node ); - } -} }; class AnyInstanceSelected : public scene::Instantiable::Visitor { -bool& m_selected; + bool& m_selected; public: -AnyInstanceSelected( bool& selected ) : m_selected( selected ){ - m_selected = false; -} -void visit( scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - m_selected = true; + AnyInstanceSelected( bool& selected ) : m_selected( selected ){ + m_selected = false; + } + void visit( scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + m_selected = true; + } } -} }; bool Node_instanceSelected( scene::Node& node ){ @@ -1230,23 +1232,23 @@ bool Node_instanceSelected( scene::Node& node ){ class SelectedDescendantWalker : public scene::Traversable::Walker { -bool& m_selected; + bool& m_selected; public: -SelectedDescendantWalker( bool& selected ) : m_selected( selected ){ - m_selected = false; -} - -bool pre( scene::Node& node ) const { - if ( node.isRoot() ) { - return false; + SelectedDescendantWalker( bool& selected ) : m_selected( selected ){ + m_selected = false; } - if ( Node_instanceSelected( node ) ) { - m_selected = true; - } + bool pre( scene::Node& node ) const { + if ( node.isRoot() ) { + return false; + } - return true; -} + if ( Node_instanceSelected( node ) ) { + m_selected = true; + } + + return true; + } }; bool Node_selectedDescendant( scene::Node& node ){ @@ -1258,52 +1260,52 @@ bool Node_selectedDescendant( scene::Node& node ){ class SelectionExcluder : public Excluder { public: -bool excluded( scene::Node& node ) const { - return !Node_selectedDescendant( node ); -} + bool excluded( scene::Node& node ) const { + return !Node_selectedDescendant( node ); + } }; class IncludeSelectedWalker : public scene::Traversable::Walker { -const scene::Traversable::Walker& m_walker; -mutable std::size_t m_selected; -mutable bool m_skip; + const scene::Traversable::Walker& m_walker; + mutable std::size_t m_selected; + mutable bool m_skip; -bool selectedParent() const { - return m_selected != 0; -} + bool selectedParent() const { + return m_selected != 0; + } public: -IncludeSelectedWalker( const scene::Traversable::Walker& walker ) - : m_walker( walker ), m_selected( 0 ), m_skip( false ){ -} -bool pre( scene::Node& node ) const { - // include node if: - // node is not a 'root' AND ( node is selected OR any child of node is selected OR any parent of node is selected ) - if ( !node.isRoot() && ( Node_selectedDescendant( node ) || selectedParent() ) ) { - if ( Node_instanceSelected( node ) ) { - ++m_selected; + IncludeSelectedWalker( const scene::Traversable::Walker& walker ) + : m_walker( walker ), m_selected( 0 ), m_skip( false ){ + } + bool pre( scene::Node& node ) const { + // include node if: + // node is not a 'root' AND ( node is selected OR any child of node is selected OR any parent of node is selected ) + if ( !node.isRoot() && ( Node_selectedDescendant( node ) || selectedParent() ) ) { + if ( Node_instanceSelected( node ) ) { + ++m_selected; + } + m_walker.pre( node ); + return true; } - m_walker.pre( node ); - return true; - } - else - { - m_skip = true; - return false; - } -} -void post( scene::Node& node ) const { - if ( m_skip ) { - m_skip = false; - } - else - { - if ( Node_instanceSelected( node ) ) { - --m_selected; + else + { + m_skip = true; + return false; + } + } + void post( scene::Node& node ) const { + if ( m_skip ) { + m_skip = false; + } + else + { + if ( Node_instanceSelected( node ) ) { + --m_selected; + } + m_walker.post( node ); } - m_walker.post( node ); } -} }; void Map_Traverse_Selected( scene::Node& root, const scene::Traversable::Walker& walker ){ @@ -1331,9 +1333,9 @@ void Map_Traverse( scene::Node& root, const scene::Traversable::Walker& walker ) class RegionExcluder : public Excluder { public: -bool excluded( scene::Node& node ) const { - return node.excluded(); -} + bool excluded( scene::Node& node ) const { + return node.excluded(); + } }; void Map_Traverse_Region( scene::Node& root, const scene::Traversable::Walker& walker ){ @@ -1515,16 +1517,16 @@ inline void exclude_node( scene::Node& node, bool exclude ){ class ExcludeAllWalker : public scene::Graph::Walker { -bool m_exclude; + bool m_exclude; public: -ExcludeAllWalker( bool exclude ) - : m_exclude( exclude ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - exclude_node( path.top(), m_exclude ); + ExcludeAllWalker( bool exclude ) + : m_exclude( exclude ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + exclude_node( path.top(), m_exclude ); - return true; -} + return true; + } }; void Scene_Exclude_All( bool exclude ){ @@ -1533,16 +1535,16 @@ void Scene_Exclude_All( bool exclude ){ class ExcludeSelectedWalker : public scene::Graph::Walker { -bool m_exclude; + bool m_exclude; public: -ExcludeSelectedWalker( bool exclude ) - : m_exclude( exclude ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( !path.top().get().isRoot() ) /* don't touch model node: disabling one will disable all instances! */ - exclude_node( path.top(), ( instance.isSelected() || instance.childSelected() || instance.parentSelected() ) == m_exclude ); - return true; -} + ExcludeSelectedWalker( bool exclude ) + : m_exclude( exclude ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( !path.top().get().isRoot() ) /* don't touch model node: disabling one will disable all instances! */ + exclude_node( path.top(), ( instance.isSelected() || instance.childSelected() || instance.parentSelected() ) == m_exclude ); + return true; + } }; void Scene_Exclude_Selected( bool exclude ){ @@ -1551,21 +1553,21 @@ void Scene_Exclude_Selected( bool exclude ){ class ExcludeRegionedWalker : public scene::Graph::Walker { -const bool m_exclude; -const AABB m_region = aabb_for_minmax( g_region_mins, g_region_maxs ); + const bool m_exclude; + const AABB m_region = aabb_for_minmax( g_region_mins, g_region_maxs ); public: -ExcludeRegionedWalker( bool exclude ) - : m_exclude( exclude ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( !path.top().get().isRoot() ){ /* don't touch model node: disabling one will disable all its instances! */ - const bool exclude = m_exclude == aabb_intersects_aabb( instance.worldAABB(), m_region ); - exclude_node( path.top(), exclude ); - if( exclude ) - Instance_setSelected( instance, false ); + ExcludeRegionedWalker( bool exclude ) + : m_exclude( exclude ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( !path.top().get().isRoot() ){ /* don't touch model node: disabling one will disable all its instances! */ + const bool exclude = m_exclude == aabb_intersects_aabb( instance.worldAABB(), m_region ); + exclude_node( path.top(), exclude ); + if( exclude ) + Instance_setSelected( instance, false ); + } + return true; } - return true; -} }; void Scene_Exclude_Region( bool exclude ){ @@ -1805,27 +1807,27 @@ class ParentSelectedBrushesToEntityWalker : public scene::Graph::Walker scene::Node* m_world; mutable bool m_emptyOldParent; public: -ParentSelectedBrushesToEntityWalker( scene::Node& parent ) : m_parent( parent ), m_world( Map_FindWorldspawn( g_map ) ), m_emptyOldParent( false ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - return path.top().get_pointer() != &m_parent; /* skip traverse of target node */ -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( Node_isPrimitive( path.top() ) ){ - if ( Instance_isSelected( instance ) ){ - NodeSmartReference node( path.top().get() ); - scene::Traversable* parent_traversable = Node_getTraversable( path.parent() ); - parent_traversable->erase( node ); - Node_getTraversable( m_parent )->insert( node ); - m_emptyOldParent = parent_traversable->empty(); + ParentSelectedBrushesToEntityWalker( scene::Node& parent ) : m_parent( parent ), m_world( Map_FindWorldspawn( g_map ) ), m_emptyOldParent( false ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + return path.top().get_pointer() != &m_parent; /* skip traverse of target node */ + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( Node_isPrimitive( path.top() ) ){ + if ( Instance_isSelected( instance ) ){ + NodeSmartReference node( path.top().get() ); + scene::Traversable* parent_traversable = Node_getTraversable( path.parent() ); + parent_traversable->erase( node ); + Node_getTraversable( m_parent )->insert( node ); + m_emptyOldParent = parent_traversable->empty(); + } + } + else if ( m_emptyOldParent ){ + m_emptyOldParent = false; + if ( Node_isEntity( path.top() ) && path.top().get_pointer() != m_world && Node_getTraversable( path.top() )->empty() ) /* delete empty entity left */ + Path_deleteTop( path ); } } - else if ( m_emptyOldParent ){ - m_emptyOldParent = false; - if ( Node_isEntity( path.top() ) && path.top().get_pointer() != m_world && Node_getTraversable( path.top() )->empty() ) /* delete empty entity left */ - Path_deleteTop( path ); - } -} }; void Scene_parentSelectedBrushesToEntity( scene::Graph& graph, scene::Node& parent ){ @@ -1838,25 +1840,25 @@ void Scene_parentSubgraphSelectedBrushesToEntity( scene::Graph& graph, scene::No class CountSelectedBrushes : public scene::Graph::Walker { -std::size_t& m_count; -mutable std::size_t m_depth; + std::size_t& m_count; + mutable std::size_t m_depth; public: -CountSelectedBrushes( std::size_t& count ) : m_count( count ), m_depth( 0 ){ - m_count = 0; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( ++m_depth != 1 && path.top().get().isRoot() ) { - return false; + CountSelectedBrushes( std::size_t& count ) : m_count( count ), m_depth( 0 ){ + m_count = 0; } - if ( Instance_isSelected( instance ) - && Node_isPrimitive( path.top() ) ) { - ++m_count; + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( ++m_depth != 1 && path.top().get().isRoot() ) { + return false; + } + if ( Instance_isSelected( instance ) + && Node_isPrimitive( path.top() ) ) { + ++m_count; + } + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} }; std::size_t Scene_countSelectedBrushes( scene::Graph& graph ){ @@ -1936,15 +1938,15 @@ void Scene_parentSelected(){ if ( GlobalSelectionSystem().countSelected() > 1 ) { class ParentSelectedBrushesToEntityWalker : public SelectionSystem::Visitor { - const scene::Path& m_parent; -public: - ParentSelectedBrushesToEntityWalker( const scene::Path& parent ) : m_parent( parent ){ - } - void visit( scene::Instance& instance ) const { - if ( &m_parent != &instance.path() ) { - Path_parent( m_parent, instance.path() ); + const scene::Path& m_parent; + public: + ParentSelectedBrushesToEntityWalker( const scene::Path& parent ) : m_parent( parent ){ + } + void visit( scene::Instance& instance ) const { + if ( &m_parent != &instance.path() ) { + Path_parent( m_parent, instance.path() ); + } } - } }; ParentSelectedBrushesToEntityWalker visitor( GlobalSelectionSystem().ultimateSelected().path() ); @@ -2088,34 +2090,34 @@ void RegionSelected(){ class BrushFindByIndexWalker : public scene::Traversable::Walker { -mutable std::size_t m_index; -scene::Path& m_path; + mutable std::size_t m_index; + scene::Path& m_path; public: -BrushFindByIndexWalker( std::size_t index, scene::Path& path ) - : m_index( index ), m_path( path ){ -} -bool pre( scene::Node& node ) const { - if ( Node_isPrimitive( node ) && m_index-- == 0 ) { - m_path.push( makeReference( node ) ); + BrushFindByIndexWalker( std::size_t index, scene::Path& path ) + : m_index( index ), m_path( path ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isPrimitive( node ) && m_index-- == 0 ) { + m_path.push( makeReference( node ) ); + } + return false; } - return false; -} }; class EntityFindByIndexWalker : public scene::Traversable::Walker { -mutable std::size_t m_index; -scene::Path& m_path; + mutable std::size_t m_index; + scene::Path& m_path; public: -EntityFindByIndexWalker( std::size_t index, scene::Path& path ) - : m_index( index ), m_path( path ){ -} -bool pre( scene::Node& node ) const { - if ( Node_isEntity( node ) && m_index-- == 0 ) { - m_path.push( makeReference( node ) ); + EntityFindByIndexWalker( std::size_t index, scene::Path& path ) + : m_index( index ), m_path( path ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isEntity( node ) && m_index-- == 0 ) { + m_path.push( makeReference( node ) ); + } + return false; } - return false; -} }; void Scene_FindEntityBrush( std::size_t entity, std::size_t brush, scene::Path& path ){ @@ -2154,44 +2156,44 @@ void SelectBrush( int entitynum, int brushnum ){ class BrushFindIndexWalker : public scene::Traversable::Walker { -mutable const scene::Node* m_node; -std::size_t& m_count; + mutable const scene::Node* m_node; + std::size_t& m_count; public: -BrushFindIndexWalker( const scene::Node& node, std::size_t& count ) - : m_node( &node ), m_count( count ){ -} -bool pre( scene::Node& node ) const { - if ( Node_isPrimitive( node ) ) { - if ( m_node == &node ) { - m_node = 0; - } - if ( m_node ) { - ++m_count; - } + BrushFindIndexWalker( const scene::Node& node, std::size_t& count ) + : m_node( &node ), m_count( count ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isPrimitive( node ) ) { + if ( m_node == &node ) { + m_node = 0; + } + if ( m_node ) { + ++m_count; + } + } + return true; } - return true; -} }; class EntityFindIndexWalker : public scene::Traversable::Walker { -mutable const scene::Node* m_node; -std::size_t& m_count; + mutable const scene::Node* m_node; + std::size_t& m_count; public: -EntityFindIndexWalker( const scene::Node& node, std::size_t& count ) - : m_node( &node ), m_count( count ){ -} -bool pre( scene::Node& node ) const { - if ( Node_isEntity( node ) ) { - if ( m_node == &node ) { - m_node = 0; - } - if ( m_node ) { - ++m_count; - } + EntityFindIndexWalker( const scene::Node& node, std::size_t& count ) + : m_node( &node ), m_count( count ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isEntity( node ) ) { + if ( m_node == &node ) { + m_node = 0; + } + if ( m_node ) { + ++m_count; + } + } + return true; } - return true; -} }; static void GetSelectionIndex( int *ent, int *brush ){ @@ -2243,22 +2245,22 @@ void DoFind(){ GtkWidget* label = gtk_label_new( "Entity number" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( "Brush number" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_grab_focus( GTK_WIDGET( entry ) ); entity = entry; } @@ -2266,8 +2268,8 @@ void DoFind(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); brush = entry; } @@ -2326,7 +2328,7 @@ void map_autocaulk_selected(){ if( path.size() == 2 ){ Entity* entity = Node_getEntity( path.top() ); if( entity != 0 && entity->isContainer() && string_equal_nocase_n( entity->getEntityClass().name(), "trigger_", 8 ) - && ( instance.childSelected() || instance.isSelected() ) ) + && ( instance.childSelected() || instance.isSelected() ) ) m_trigger = &instance; else return false; @@ -2353,7 +2355,7 @@ void map_autocaulk_selected(){ StringOutputStream filename( 256 ); filename << PathExtensionless( g_map.m_name.c_str() ) << "_ac.map"; - {// write .map + { // write .map const Vector3 spawn( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ) ); Vector3 mins, maxs; Select_GetBounds( mins, maxs ); @@ -2373,7 +2375,7 @@ void map_autocaulk_selected(){ // all brushes to the worldspawn file << "{\n" - "\"classname\" \"worldspawn\""; + "\"classname\" \"worldspawn\""; TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( file ); class WriteBrushesWalker : public scene::Traversable::Walker { @@ -2405,9 +2407,9 @@ void map_autocaulk_selected(){ file << "\n}\n"; // spawn file << "{\n" - "\"classname\" \"info_player_start\"\n" - "\"origin\" \"" << spawn[0] << " " << spawn[1] << " " << spawn[2] << "\"\n" - "}\n"; + "\"classname\" \"info_player_start\"\n" + "\"origin\" \"" << spawn[0] << " " << spawn[1] << " " << spawn[2] << "\"\n" + "}\n"; // point entities const MapFormat& format = MapFormat_forFile( filename.c_str() ); auto traverse_selected_point_entities = []( scene::Node& root, const scene::Traversable::Walker& walker ){ @@ -2446,22 +2448,22 @@ void map_autocaulk_selected(){ writer.release(); } - { // compile + { // compile StringOutputStream str( 256 ); str << AppPath_get() << "q3map2." << RADIANT_EXECUTABLE - << " -game quake3" - << " -fs_basepath \"" << EnginePath_get() - << "\" -fs_homepath \"" << g_qeglobals.m_userEnginePath.c_str() - << "\" -fs_game " << gamename_get() - << " -autocaulk -fulldetail" - << " \"" << filename.c_str() << "\""; + << " -game quake3" + << " -fs_basepath \"" << EnginePath_get() + << "\" -fs_homepath \"" << g_qeglobals.m_userEnginePath.c_str() + << "\" -fs_game " << gamename_get() + << " -autocaulk -fulldetail" + << " \"" << filename.c_str() << "\""; // run Q_Exec( NULL, str.c_str(), NULL, false, true ); } typedef std::map CaulkMap; CaulkMap map; - { // load + { // load filename.clear(); filename << PathExtensionless( g_map.m_name.c_str() ) << "_ac.caulk"; @@ -2489,7 +2491,7 @@ void map_autocaulk_selected(){ tokeniser.release(); } - { // apply + { // apply class CaulkBrushesWalker : public scene::Traversable::Walker { const CaulkMap& m_map; @@ -2569,26 +2571,26 @@ void Map_constructPreferences( PreferencesPage& page ){ class MapEntityClasses : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -MapEntityClasses() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - if ( g_map.m_resource != 0 ) { - ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Map" ); - g_map.m_resource->realise(); + MapEntityClasses() : m_unrealised( 1 ){ + } + void realise(){ + if ( --m_unrealised == 0 ) { + if ( g_map.m_resource != 0 ) { + ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Map" ); + g_map.m_resource->realise(); + } } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - if ( g_map.m_resource != 0 ) { - g_map.m_resource->flush(); - g_map.m_resource->unrealise(); + void unrealise(){ + if ( ++m_unrealised == 1 ) { + if ( g_map.m_resource != 0 ) { + g_map.m_resource->flush(); + g_map.m_resource->unrealise(); + } } } -} }; MapEntityClasses g_MapEntityClasses; @@ -2596,24 +2598,24 @@ MapEntityClasses g_MapEntityClasses; class MapModuleObserver : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -MapModuleObserver() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { - ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "maps_directory: user-game-path is empty" ); - StringOutputStream buffer( 256 ); - buffer << g_qeglobals.m_userGamePath.c_str() << "maps/"; - Q_mkdir( buffer.c_str() ); - g_mapsPath = buffer.c_str(); + MapModuleObserver() : m_unrealised( 1 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - g_mapsPath = ""; + void realise(){ + if ( --m_unrealised == 0 ) { + ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "maps_directory: user-game-path is empty" ); + StringOutputStream buffer( 256 ); + buffer << g_qeglobals.m_userGamePath.c_str() << "maps/"; + Q_mkdir( buffer.c_str() ); + g_mapsPath = buffer.c_str(); + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + g_mapsPath = ""; + } } -} }; MapModuleObserver g_MapModuleObserver; diff --git a/radiant/map.h b/radiant/map.h index 8656cce2..369b15c0 100644 --- a/radiant/map.h +++ b/radiant/map.h @@ -37,31 +37,31 @@ bool Map_Valid( const Map& map ); class DeferredDraw { -Callback m_draw; -bool m_defer; -bool m_deferred; + Callback m_draw; + bool m_defer; + bool m_deferred; public: -DeferredDraw( const Callback& draw ) : m_draw( draw ), m_defer( false ), m_deferred( false ){ -} -void defer(){ - m_defer = true; -} -void draw(){ - if ( m_defer ) { - m_deferred = true; + DeferredDraw( const Callback& draw ) : m_draw( draw ), m_defer( false ), m_deferred( false ){ } - else - { - m_draw(); + void defer(){ + m_defer = true; } -} -void flush(){ - if ( m_defer && m_deferred ) { - m_draw(); + void draw(){ + if ( m_defer ) { + m_deferred = true; + } + else + { + m_draw(); + } + } + void flush(){ + if ( m_defer && m_deferred ) { + m_draw(); + } + m_deferred = false; + m_defer = false; } - m_deferred = false; - m_defer = false; -} }; inline void DeferredDraw_onMapValidChanged( DeferredDraw& self ){ diff --git a/radiant/modelwindow.cpp b/radiant/modelwindow.cpp index 0ea0d258..f7b797b1 100644 --- a/radiant/modelwindow.cpp +++ b/radiant/modelwindow.cpp @@ -57,100 +57,100 @@ /* specialized copy of class CompiledGraph */ class ModelGraph final : public scene::Graph, public scene::Instantiable::Observer { -typedef std::map InstanceMap; + typedef std::map InstanceMap; -InstanceMap m_instances; -scene::Path m_rootpath; + InstanceMap m_instances; + scene::Path m_rootpath; -scene::Instantiable::Observer& m_observer; + scene::Instantiable::Observer& m_observer; public: -ModelGraph( scene::Instantiable::Observer& observer ) : m_observer( observer ){ -} + ModelGraph( scene::Instantiable::Observer& observer ) : m_observer( observer ){ + } -void addSceneChangedCallback( const SignalHandler& handler ){ - ASSERT_MESSAGE( 0, "Reached unreachable: addSceneChangedCallback()" ); -} -void sceneChanged(){ - ASSERT_MESSAGE( 0, "Reached unreachable: sceneChanged()" ); -} + void addSceneChangedCallback( const SignalHandler& handler ){ + ASSERT_MESSAGE( 0, "Reached unreachable: addSceneChangedCallback()" ); + } + void sceneChanged(){ + ASSERT_MESSAGE( 0, "Reached unreachable: sceneChanged()" ); + } -scene::Node& root(){ - ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); - return m_rootpath.top(); -} -void insert_root( scene::Node& root ){ - //globalOutputStream() << "insert_root\n"; + scene::Node& root(){ + ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); + return m_rootpath.top(); + } + void insert_root( scene::Node& root ){ + //globalOutputStream() << "insert_root\n"; - ASSERT_MESSAGE( m_rootpath.empty(), "scenegraph root already exists" ); + ASSERT_MESSAGE( m_rootpath.empty(), "scenegraph root already exists" ); - root.IncRef(); + root.IncRef(); - Node_traverseSubgraph( root, InstanceSubgraphWalker( this, scene::Path(), 0 ) ); + Node_traverseSubgraph( root, InstanceSubgraphWalker( this, scene::Path(), 0 ) ); - m_rootpath.push( makeReference( root ) ); -} -void erase_root(){ - //globalOutputStream() << "erase_root\n"; + m_rootpath.push( makeReference( root ) ); + } + void erase_root(){ + //globalOutputStream() << "erase_root\n"; - ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); + ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); - scene::Node& root = m_rootpath.top(); + scene::Node& root = m_rootpath.top(); - m_rootpath.pop(); + m_rootpath.pop(); - Node_traverseSubgraph( root, UninstanceSubgraphWalker( this, scene::Path() ) ); + Node_traverseSubgraph( root, UninstanceSubgraphWalker( this, scene::Path() ) ); - root.DecRef(); -} -void boundsChanged(){ - ASSERT_MESSAGE( 0, "Reached unreachable: boundsChanged()" ); -} + root.DecRef(); + } + void boundsChanged(){ + ASSERT_MESSAGE( 0, "Reached unreachable: boundsChanged()" ); + } -void traverse( const Walker& walker ){ - ASSERT_MESSAGE( 0, "Reached unreachable: traverse()" ); -} + void traverse( const Walker& walker ){ + ASSERT_MESSAGE( 0, "Reached unreachable: traverse()" ); + } -void traverse_subgraph( const Walker& walker, const scene::Path& start ){ - ASSERT_MESSAGE( 0, "Reached unreachable: traverse_subgraph()" ); -} + void traverse_subgraph( const Walker& walker, const scene::Path& start ){ + ASSERT_MESSAGE( 0, "Reached unreachable: traverse_subgraph()" ); + } -scene::Instance* find( const scene::Path& path ){ - ASSERT_MESSAGE( 0, "Reached unreachable: find()" ); - return nullptr; -} + scene::Instance* find( const scene::Path& path ){ + ASSERT_MESSAGE( 0, "Reached unreachable: find()" ); + return nullptr; + } -void insert( scene::Instance* instance ){ - m_instances.insert( InstanceMap::value_type( PathConstReference( instance->path() ), instance ) ); - m_observer.insert( instance ); -} -void erase( scene::Instance* instance ){ - m_instances.erase( PathConstReference( instance->path() ) ); - m_observer.erase( instance ); -} + void insert( scene::Instance* instance ){ + m_instances.insert( InstanceMap::value_type( PathConstReference( instance->path() ), instance ) ); + m_observer.insert( instance ); + } + void erase( scene::Instance* instance ){ + m_instances.erase( PathConstReference( instance->path() ) ); + m_observer.erase( instance ); + } -SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ){ - ASSERT_MESSAGE( 0, "Reached unreachable: addBoundsChangedCallback()" ); - return Handle>( nullptr ); -} -void removeBoundsChangedCallback( SignalHandlerId id ){ - ASSERT_MESSAGE( 0, "Reached unreachable: removeBoundsChangedCallback()" ); -} + SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ){ + ASSERT_MESSAGE( 0, "Reached unreachable: addBoundsChangedCallback()" ); + return Handle>( nullptr ); + } + void removeBoundsChangedCallback( SignalHandlerId id ){ + ASSERT_MESSAGE( 0, "Reached unreachable: removeBoundsChangedCallback()" ); + } -TypeId getNodeTypeId( const char* name ){ - ASSERT_MESSAGE( 0, "Reached unreachable: getNodeTypeId()" ); - return 0; -} + TypeId getNodeTypeId( const char* name ){ + ASSERT_MESSAGE( 0, "Reached unreachable: getNodeTypeId()" ); + return 0; + } -TypeId getInstanceTypeId( const char* name ){ - ASSERT_MESSAGE( 0, "Reached unreachable: getInstanceTypeId()" ); - return 0; -} + TypeId getInstanceTypeId( const char* name ){ + ASSERT_MESSAGE( 0, "Reached unreachable: getInstanceTypeId()" ); + return 0; + } -void clear(){ - DeleteSubgraph( root() ); -} + void clear(){ + DeleteSubgraph( root() ); + } }; @@ -158,177 +158,177 @@ void clear(){ /// \brief A sequence of node references which notifies an observer of inserts and deletions, and uses the global undo system to provide undo for modifications. class TraversableModelNodeSet : public scene::Traversable { -UnsortedNodeSet m_children; -Observer* m_observer; + UnsortedNodeSet m_children; + Observer* m_observer; -void copy( const TraversableModelNodeSet& other ){ - m_children = other.m_children; -} -void notifyInsertAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->insert( *i ); + void copy( const TraversableModelNodeSet& other ){ + m_children = other.m_children; + } + void notifyInsertAll(){ + if ( m_observer ) { + for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) + { + m_observer->insert( *i ); + } } } -} -void notifyEraseAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->erase( *i ); + void notifyEraseAll(){ + if ( m_observer ) { + for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) + { + m_observer->erase( *i ); + } } } -} public: -TraversableModelNodeSet() - : m_observer( 0 ){ -} -TraversableModelNodeSet( const TraversableModelNodeSet& other ) - : scene::Traversable( other ), m_observer( 0 ){ - copy( other ); - notifyInsertAll(); -} -~TraversableModelNodeSet(){ - notifyEraseAll(); -} -TraversableModelNodeSet& operator=( const TraversableModelNodeSet& other ){ + TraversableModelNodeSet() + : m_observer( 0 ){ + } + TraversableModelNodeSet( const TraversableModelNodeSet& other ) + : scene::Traversable( other ), m_observer( 0 ){ + copy( other ); + notifyInsertAll(); + } + ~TraversableModelNodeSet(){ + notifyEraseAll(); + } + TraversableModelNodeSet& operator=( const TraversableModelNodeSet& other ){ #if 1 // optimised change-tracking using diff algorithm - if ( m_observer ) { - nodeset_diff( m_children, other.m_children, m_observer ); - } - copy( other ); + if ( m_observer ) { + nodeset_diff( m_children, other.m_children, m_observer ); + } + copy( other ); #else - TraversableModelNodeSet tmp( other ); - tmp.swap( *this ); + TraversableModelNodeSet tmp( other ); + tmp.swap( *this ); #endif - return *this; -} -void swap( TraversableModelNodeSet& other ){ - std::swap( m_children, other.m_children ); - std::swap( m_observer, other.m_observer ); -} + return *this; + } + void swap( TraversableModelNodeSet& other ){ + std::swap( m_children, other.m_children ); + std::swap( m_observer, other.m_observer ); + } -void attach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == 0, "TraversableModelNodeSet::attach: observer cannot be attached" ); - m_observer = observer; - notifyInsertAll(); -} -void detach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == observer, "TraversableModelNodeSet::detach: observer cannot be detached" ); - notifyEraseAll(); - m_observer = 0; -} + void attach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == 0, "TraversableModelNodeSet::attach: observer cannot be attached" ); + m_observer = observer; + notifyInsertAll(); + } + void detach( Observer* observer ){ + ASSERT_MESSAGE( m_observer == observer, "TraversableModelNodeSet::detach: observer cannot be detached" ); + notifyEraseAll(); + m_observer = 0; + } /// \brief \copydoc scene::Traversable::insert() -void insert( scene::Node& node ){ - ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableModelNodeSet::insert: sanity check failed" ); + void insert( scene::Node& node ){ + ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableModelNodeSet::insert: sanity check failed" ); - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) == m_children.end(), "TraversableModelNodeSet::insert - element already exists" ); + ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) == m_children.end(), "TraversableModelNodeSet::insert - element already exists" ); - m_children.insert( NodeSmartReference( node ) ); + m_children.insert( NodeSmartReference( node ) ); - if ( m_observer ) { - m_observer->insert( node ); + if ( m_observer ) { + m_observer->insert( node ); + } } -} /// \brief \copydoc scene::Traversable::erase() -void erase( scene::Node& node ){ - ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableModelNodeSet::erase: sanity check failed" ); + void erase( scene::Node& node ){ + ASSERT_MESSAGE( (volatile intptr_t)&node != 0, "TraversableModelNodeSet::erase: sanity check failed" ); - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) != m_children.end(), "TraversableModelNodeSet::erase - failed to find element" ); + ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) != m_children.end(), "TraversableModelNodeSet::erase - failed to find element" ); - if ( m_observer ) { - m_observer->erase( node ); + if ( m_observer ) { + m_observer->erase( node ); + } + + m_children.erase( NodeSmartReference( node ) ); } - - m_children.erase( NodeSmartReference( node ) ); -} /// \brief \copydoc scene::Traversable::traverse() -void traverse( const Walker& walker ){ - UnsortedNodeSet::iterator i = m_children.begin(); - while ( i != m_children.end() ) - { - // post-increment the iterator - Node_traverseSubgraph( *i++, walker ); - // the Walker can safely remove the current node from - // this container without invalidating the iterator + void traverse( const Walker& walker ){ + UnsortedNodeSet::iterator i = m_children.begin(); + while ( i != m_children.end() ) + { + // post-increment the iterator + Node_traverseSubgraph( *i++, walker ); + // the Walker can safely remove the current node from + // this container without invalidating the iterator + } } -} /// \brief \copydoc scene::Traversable::empty() -bool empty() const { - return m_children.empty(); -} + bool empty() const { + return m_children.empty(); + } }; /* specialized copy of class MapRoot */ class ModelGraphRoot : public scene::Node::Symbiot, public scene::Instantiable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; + + scene::Node m_node; + IdentityTransform m_transform; + TraversableModelNodeSet m_traverse; + InstanceSet m_instances; public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + typedef LazyStatic StaticTypeCasts; -scene::Node m_node; -IdentityTransform m_transform; -TraversableModelNodeSet m_traverse; -InstanceSet m_instances; -public: -typedef LazyStatic StaticTypeCasts; + scene::Traversable& get( NullType){ + return m_traverse; + } + TransformNode& get( NullType){ + return m_transform; + } -scene::Traversable& get( NullType){ - return m_traverse; -} -TransformNode& get( NullType){ - return m_transform; -} + ModelGraphRoot() : m_node( this, this, StaticTypeCasts::instance().get() ){ + m_node.m_isRoot = true; -ModelGraphRoot() : m_node( this, this, StaticTypeCasts::instance().get() ){ - m_node.m_isRoot = true; + m_traverse.attach( this ); + } + ~ModelGraphRoot(){ + } + void release(){ + m_traverse.detach( this ); + delete this; + } + scene::Node& node(){ + return m_node; + } - m_traverse.attach( this ); -} -~ModelGraphRoot(){ -} -void release(){ - m_traverse.detach( this ); - delete this; -} -scene::Node& node(){ - return m_node; -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + scene::Node& clone() const { + return ( new ModelGraphRoot( *this ) )->node(); + } -scene::Node& clone() const { - return ( new ModelGraphRoot( *this ) )->node(); -} - -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new SelectableInstance( path, parent ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new SelectableInstance( path, parent ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; @@ -342,88 +342,88 @@ class ModelNode : public scene::Instantiable, public scene::Traversable::Observer { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -SingletonModel m_model; -MatrixTransform m_transform; + scene::Node m_node; + InstanceSet m_instances; + SingletonModel m_model; + MatrixTransform m_transform; -void construct(){ - m_model.attach( this ); -} -void destroy(){ - m_model.detach( this ); -} + void construct(){ + m_model.attach( this ); + } + void destroy(){ + m_model.detach( this ); + } public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -scene::Traversable& get( NullType){ - return m_model.getTraversable(); -} -TransformNode& get( NullType){ - return m_transform; -} + scene::Traversable& get( NullType){ + return m_model.getTraversable(); + } + TransformNode& get( NullType){ + return m_transform; + } -ModelNode() : - m_node( this, this, StaticTypeCasts::instance().get() ){ - construct(); -} -ModelNode( const ModelNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Traversable::Observer( other ), - m_node( this, this, StaticTypeCasts::instance().get() ){ - construct(); -} -~ModelNode(){ - destroy(); -} + ModelNode() : + m_node( this, this, StaticTypeCasts::instance().get() ){ + construct(); + } + ModelNode( const ModelNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Traversable::Observer( other ), + m_node( this, this, StaticTypeCasts::instance().get() ){ + construct(); + } + ~ModelNode(){ + destroy(); + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} + void insert( scene::Node& child ){ + m_instances.insert( child ); + } + void erase( scene::Node& child ){ + m_instances.erase( child ); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new SelectableInstance( path, parent ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new SelectableInstance( path, parent ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } -void setModel( const char* modelname ){ - m_model.modelChanged( modelname ); -} + void setModel( const char* modelname ){ + m_model.modelChanged( modelname ); + } }; @@ -474,8 +474,8 @@ class CellPos int m_index = 0; public: - CellPos( int width, int cellSize, int fontHeight ) - : m_cellSize( cellSize ), m_fontHeight( fontHeight ), + CellPos( int width, int cellSize, int fontHeight ) : + m_cellSize( cellSize ), m_fontHeight( fontHeight ), m_fontDescent( GlobalOpenGL().m_font->getPixelDescent() ), m_plusWidth( 8 ), m_plusHeight( 0 ), @@ -669,19 +669,20 @@ public: const float scale = m_cellPos.getCellSize() / aabb.extents[ vector3_max_abs_component_index( aabb.extents ) ]; aabb.extents.z() *= 2; // prioritize Z for orientation const Matrix4 rotation = matrix4_rotation_for_euler_xyz_degrees( - vector3_min_abs_component_index( aabb.extents ) == 0? Vector3( 0, 0, -90 ) - : vector3_min_abs_component_index( aabb.extents ) == 2? Vector3( 90, 0, 0 ) - : g_vector3_identity ); - const_cast( transformNode->localToParent() ) = matrix4_multiplied_by_matrix4( - matrix4_translation_for_vec3( m_cellPos.getOrigin() ), - matrix4_multiplied_by_matrix4( - rotation, - matrix4_multiplied_by_matrix4( - matrix4_scale_for_vec3( Vector3( scale, scale, scale ) ), - matrix4_translation_for_vec3( -aabb.origin ) - ) - ) - ); + vector3_min_abs_component_index( aabb.extents ) == 0? Vector3( 0, 0, -90 ) + : vector3_min_abs_component_index( aabb.extents ) == 2? Vector3( 90, 0, 0 ) + : g_vector3_identity ); + const_cast( transformNode->localToParent() ) = + matrix4_multiplied_by_matrix4( + matrix4_translation_for_vec3( m_cellPos.getOrigin() ), + matrix4_multiplied_by_matrix4( + rotation, + matrix4_multiplied_by_matrix4( + matrix4_scale_for_vec3( Vector3( scale, scale, scale ) ), + matrix4_translation_for_vec3( -aabb.origin ) + ) + ) + ); instance->parent()->transformChangedLocal(); instance->transformChangedLocal(); //% globalOutputStream() << transformNode->localToParent() << " transformNode->localToParent()\n"; @@ -694,47 +695,47 @@ public: class ModelRenderer : public Renderer { -struct state_type -{ - state_type() : - m_state( 0 ){ - } - Shader* m_state; -}; + struct state_type + { + state_type() : + m_state( 0 ){ + } + Shader* m_state; + }; public: -ModelRenderer( RenderStateFlags globalstate ) : - m_globalstate( globalstate ){ - m_state_stack.push_back( state_type() ); -} - -void SetState( Shader* state, EStyle style ){ - ASSERT_NOTNULL( state ); - if ( style == eFullMaterials ) { - m_state_stack.back().m_state = state; + ModelRenderer( RenderStateFlags globalstate ) : + m_globalstate( globalstate ){ + m_state_stack.push_back( state_type() ); } -} -EStyle getStyle() const { - return eFullMaterials; -} -void PushState(){ - m_state_stack.push_back( m_state_stack.back() ); -} -void PopState(){ - ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); - m_state_stack.pop_back(); -} -void Highlight( EHighlightMode mode, bool bEnable = true ){ -} -void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){ - m_state_stack.back().m_state->addRenderable( renderable, localToWorld ); -} -void render( const Matrix4& modelview, const Matrix4& projection ){ - GlobalShaderCache().render( m_globalstate, modelview, projection ); -} + void SetState( Shader* state, EStyle style ){ + ASSERT_NOTNULL( state ); + if ( style == eFullMaterials ) { + m_state_stack.back().m_state = state; + } + } + EStyle getStyle() const { + return eFullMaterials; + } + void PushState(){ + m_state_stack.push_back( m_state_stack.back() ); + } + void PopState(){ + ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); + m_state_stack.pop_back(); + } + void Highlight( EHighlightMode mode, bool bEnable = true ){ + } + void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){ + m_state_stack.back().m_state->addRenderable( renderable, localToWorld ); + } + + void render( const Matrix4& modelview, const Matrix4& projection ){ + GlobalShaderCache().render( m_globalstate, modelview, projection ); + } private: -std::vector m_state_stack; -RenderStateFlags m_globalstate; + std::vector m_state_stack; + RenderStateFlags m_globalstate; }; /* @@ -762,21 +763,21 @@ void ModelBrowser_render(){ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); const unsigned int globalstate = RENDER_DEPTHTEST - | RENDER_COLOURWRITE - | RENDER_DEPTHWRITE - | RENDER_ALPHATEST - | RENDER_BLEND - | RENDER_CULLFACE - | RENDER_COLOURARRAY - | RENDER_POLYGONSMOOTH - | RENDER_LINESMOOTH - | RENDER_FOG - | RENDER_COLOURCHANGE - | RENDER_FILL - | RENDER_LIGHTING - | RENDER_TEXTURE - | RENDER_SMOOTH - | RENDER_SCALED; + | RENDER_COLOURWRITE + | RENDER_DEPTHWRITE + | RENDER_ALPHATEST + | RENDER_BLEND + | RENDER_CULLFACE + | RENDER_COLOURARRAY + | RENDER_POLYGONSMOOTH + | RENDER_LINESMOOTH + | RENDER_FOG + | RENDER_COLOURCHANGE + | RENDER_FILL + | RENDER_LIGHTING + | RENDER_TEXTURE + | RENDER_SMOOTH + | RENDER_SCALED; Matrix4 m_projection; @@ -789,17 +790,9 @@ void ModelBrowser_render(){ m_projection[13] = 0.0f; m_projection[14] = -1.0f; - m_projection[1] = - m_projection[2] = - m_projection[3] = - - m_projection[4] = - m_projection[6] = - m_projection[7] = - - m_projection[8] = - m_projection[9] = - m_projection[11] = 0.0f; + m_projection[1] = m_projection[2] = m_projection[3] = + m_projection[4] = m_projection[6] = m_projection[7] = + m_projection[8] = m_projection[9] = m_projection[11] = 0.0f; m_projection[15] = 1.0f; @@ -812,17 +805,17 @@ void ModelBrowser_render(){ // axis base //XZ: - m_modelview[0] = 1; - m_modelview[1] = 0; - m_modelview[2] = 0; + m_modelview[0] = 1; + m_modelview[1] = 0; + m_modelview[2] = 0; - m_modelview[4] = 0; - m_modelview[5] = 0; - m_modelview[6] = 1; + m_modelview[4] = 0; + m_modelview[5] = 0; + m_modelview[6] = 1; - m_modelview[8] = 0; - m_modelview[9] = 1; - m_modelview[10] = 0; + m_modelview[8] = 0; + m_modelview[9] = 1; + m_modelview[10] = 0; m_modelview[3] = m_modelview[7] = m_modelview[11] = 0; @@ -842,7 +835,7 @@ void ModelBrowser_render(){ if( g_ModelBrowser.m_currentFolder != nullptr ){ - { // prepare for 2d stuff + { // prepare for 2d stuff glDisable( GL_BLEND ); if ( GlobalOpenGL().GL_1_3() ) { @@ -860,7 +853,7 @@ void ModelBrowser_render(){ glDisable( GL_DEPTH_TEST ); } - { // brighter background squares + { // brighter background squares glColor4f( 0.3f, 0.3f, 0.3f, 1.f ); glDepthMask( GL_FALSE ); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); @@ -916,7 +909,7 @@ void ModelBrowser_render(){ renderer.render( m_modelview, m_projection ); } - { // prepare for 2d stuff + { // prepare for 2d stuff glColor4f( 1, 1, 1, 1 ); glDisable( GL_BLEND ); @@ -935,7 +928,7 @@ void ModelBrowser_render(){ glDisable( GL_DEPTH_TEST ); glLineWidth( 1 ); } - { // render model file names + { // render model file names CellPos cellPos = g_ModelBrowser.constructCellPos(); for( const CopiedString& string : g_ModelBrowser.m_currentFolder->m_files ){ const Vector3 pos = cellPos.getTextPos(); @@ -1196,7 +1189,7 @@ public: const ModelFoldersMap& m_modelFoldersMap; bool m_avoid_pk3dir; ModelPaths_ArchiveVisitor( const StringSetWithLambda& modelExtensions, ModelFS& modelFS, const ModelFoldersMap& modelFoldersMap ) - : m_modelExtensions( modelExtensions ), m_modelFS( modelFS ), m_modelFoldersMap( modelFoldersMap ){ + : m_modelExtensions( modelExtensions ), m_modelFS( modelFS ), m_modelFoldersMap( modelFoldersMap ){ } void visit( const char* name ) override { if( m_modelExtensions.find( path_get_extension( name ) ) != m_modelExtensions.end() && ( !m_avoid_pk3dir || !string_in_string_nocase( name, ".pk3dir/" ) ) ){ @@ -1213,9 +1206,9 @@ void ModelPaths_addFromArchive( ModelPaths_ArchiveVisitor& visitor, const char * for( const auto& folder : visitor.m_modelFoldersMap ){ /* should better avoid .pk3dir traversal right in archive implementation for normal folders */ visitor.m_avoid_pk3dir = string_empty( folder.first.c_str() ) // root - && folder.second > 1 // deep nuff - && string_equal_suffix( archiveName, "/" ) // normal folder, not archive - && !string_equal_suffix_nocase( archiveName, ".pk3dir/" ); // not .pk3dir + && folder.second > 1 // deep nuff + && string_equal_suffix( archiveName, "/" ) // normal folder, not archive + && !string_equal_suffix_nocase( archiveName, ".pk3dir/" ); // not .pk3dir archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, folder.second ), folder.first.c_str() ); } } @@ -1274,14 +1267,14 @@ GtkWidget* ModelBrowser_constructWindow( GtkWindow* toplevel ){ gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0 ); gtk_widget_show( vbox ); - { // menu bar + { // menu bar GtkToolbar* toolbar = toolbar_new(); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( toolbar ), FALSE, FALSE, 0 ); GtkToolButton* button = toolbar_append_button( toolbar, "Reload Model Folders Tree View", "texbro_refresh.png", FreeCaller() ); // gtk_widget_set_size_request( GTK_WIDGET( button ), 22, 22 ); } - { // TreeView + { // TreeView GtkWidget* scr = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( scr ), 0 ); // vertical only scrolling for treeview @@ -1309,7 +1302,7 @@ GtkWidget* ModelBrowser_constructWindow( GtkWindow* toplevel ){ gtk_box_pack_start( GTK_BOX( vbox ), scr, TRUE, TRUE, 0 ); } - { // gl_widget scrollbar + { // gl_widget scrollbar GtkWidget* w = g_ModelBrowser.m_gl_scroll = gtk_vscrollbar_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, 0, 0, 1, 1, 0 ) ) ); gtk_table_attach( GTK_TABLE( table ), w, 2, 3, 0, 1, GTK_SHRINK, GTK_FILL, 0, 0 ); gtk_widget_show( w ); @@ -1317,7 +1310,7 @@ GtkWidget* ModelBrowser_constructWindow( GtkWindow* toplevel ){ GtkAdjustment *vadjustment = gtk_range_get_adjustment( GTK_RANGE( w ) ); g_signal_connect( G_OBJECT( vadjustment ), "value_changed", G_CALLBACK( ModelBrowser_scrollbarScroll ), &g_ModelBrowser ); } - { // gl_widget + { // gl_widget GtkWidget* w = g_ModelBrowser.m_gl_widget = glwidget_new( TRUE ); g_object_ref( G_OBJECT( w ) ); @@ -1378,11 +1371,11 @@ void ModelBrowser_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Model Browser", "Model Browser Preferences" ) ); page.appendSpinner( "Model View Size", 80.0, 16.0, 8192.0, - IntImportCallback( CellSizeImportCaller( g_ModelBrowser.m_cellSize ) ), - IntExportCallback( IntExportCaller( g_ModelBrowser.m_cellSize ) ) ); + IntImportCallback( CellSizeImportCaller( g_ModelBrowser.m_cellSize ) ), + IntExportCallback( IntExportCaller( g_ModelBrowser.m_cellSize ) ) ); page.appendEntry( "List of *folderToLoad/depth*", - StringImportCallback( FoldersToLoadImportCaller( g_ModelBrowser.m_prefFoldersToLoad ) ), - StringExportCallback( StringExportCaller( g_ModelBrowser.m_prefFoldersToLoad ) ) ); + StringImportCallback( FoldersToLoadImportCaller( g_ModelBrowser.m_prefFoldersToLoad ) ), + StringExportCallback( StringExportCaller( g_ModelBrowser.m_prefFoldersToLoad ) ) ); } void ModelBrowser_registerPreferencesPage(){ PreferencesDialog_addSettingsPage( FreeCaller1() ); diff --git a/radiant/mru.cpp b/radiant/mru.cpp index f0b28130..46908ad8 100644 --- a/radiant/mru.cpp +++ b/radiant/mru.cpp @@ -50,28 +50,28 @@ inline const char* MRU_GetText( std::size_t index ){ class EscapedMnemonic { -StringBuffer m_buffer; + StringBuffer m_buffer; public: -EscapedMnemonic( std::size_t capacity ) : m_buffer( capacity ){ - m_buffer.push_back( '_' ); -} -const char* c_str() const { - return m_buffer.c_str(); -} -void push_back( char c ){ // not escaped - m_buffer.push_back( c ); -} -std::size_t write( const char* buffer, std::size_t length ){ - for ( const char* end = buffer + length; buffer != end; ++buffer ) - { - if ( *buffer == '_' ) { - m_buffer.push_back( '_' ); - } - - m_buffer.push_back( *buffer ); + EscapedMnemonic( std::size_t capacity ) : m_buffer( capacity ){ + m_buffer.push_back( '_' ); + } + const char* c_str() const { + return m_buffer.c_str(); + } + void push_back( char c ){ // not escaped + m_buffer.push_back( c ); + } + std::size_t write( const char* buffer, std::size_t length ){ + for ( const char* end = buffer + length; buffer != end; ++buffer ) + { + if ( *buffer == '_' ) { + m_buffer.push_back( '_' ); + } + + m_buffer.push_back( *buffer ); + } + return length; } - return length; -} }; template @@ -171,16 +171,16 @@ void MRU_Activate( std::size_t index ){ class LoadMRU { -std::size_t m_number; + std::size_t m_number; public: -LoadMRU( std::size_t number ) - : m_number( number ){ -} -void load(){ - if ( ConfirmModified( "Open Map" ) ) { - MRU_Activate( m_number - 1 ); + LoadMRU( std::size_t number ) + : m_number( number ){ + } + void load(){ + if ( ConfirmModified( "Open Map" ) ) { + MRU_Activate( m_number - 1 ); + } } -} }; typedef MemberCaller LoadMRUCaller; @@ -216,7 +216,7 @@ void MRU_constructMenu( GtkMenu* menu ){ gtk_widget_hide( GTK_WIDGET( item ) ); MRU_AddWidget( item, 3 ); } - { + { GtkMenuItem* item = create_menu_item_with_mnemonic( menu, "_5", LoadMRUCaller( g_load_mru5 ) ); gtk_widget_hide( GTK_WIDGET( item ) ); MRU_AddWidget( item, 4 ); @@ -231,7 +231,7 @@ void MRU_constructMenu( GtkMenu* menu ){ gtk_widget_hide( GTK_WIDGET( item ) ); MRU_AddWidget( item, 6 ); } - { + { GtkMenuItem* item = create_menu_item_with_mnemonic( menu, "_8", LoadMRUCaller( g_load_mru8 ) ); gtk_widget_hide( GTK_WIDGET( item ) ); MRU_AddWidget( item, 7 ); diff --git a/radiant/nullmodel.cpp b/radiant/nullmodel.cpp index e23bb7c0..14c7ce04 100644 --- a/radiant/nullmodel.cpp +++ b/radiant/nullmodel.cpp @@ -43,136 +43,136 @@ class NullModel : public Bounded, public Cullable { -Shader* m_state; -AABB m_aabb_local; -RenderableSolidAABB m_aabb_solid; -RenderableWireframeAABB m_aabb_wire; + Shader* m_state; + AABB m_aabb_local; + RenderableSolidAABB m_aabb_solid; + RenderableWireframeAABB m_aabb_wire; public: -NullModel() : m_aabb_local( Vector3( 0, 0, 0 ), Vector3( 8, 8, 8 ) ), m_aabb_solid( m_aabb_local ), m_aabb_wire( m_aabb_local ){ - m_state = GlobalShaderCache().capture( "" ); -} -~NullModel(){ - GlobalShaderCache().release( "" ); -} - -VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { - return volume.TestAABB( m_aabb_local, localToWorld ); -} - -const AABB& localAABB() const { - return m_aabb_local; -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( m_state, Renderer::eFullMaterials ); - renderer.addRenderable( m_aabb_solid, localToWorld ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.addRenderable( m_aabb_wire, localToWorld ); -} - -void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ - test.BeginMesh( localToWorld ); - - SelectionIntersection best; - aabb_testselect( m_aabb_local, test, best ); - if ( best.valid() ) { - selector.addIntersection( best ); + NullModel() : m_aabb_local( Vector3( 0, 0, 0 ), Vector3( 8, 8, 8 ) ), m_aabb_solid( m_aabb_local ), m_aabb_wire( m_aabb_local ){ + m_state = GlobalShaderCache().capture( "" ); + } + ~NullModel(){ + GlobalShaderCache().release( "" ); + } + + VolumeIntersectionValue intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const { + return volume.TestAABB( m_aabb_local, localToWorld ); + } + + const AABB& localAABB() const { + return m_aabb_local; + } + + void renderSolid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( m_state, Renderer::eFullMaterials ); + renderer.addRenderable( m_aabb_solid, localToWorld ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.addRenderable( m_aabb_wire, localToWorld ); + } + + void testSelect( Selector& selector, SelectionTest& test, const Matrix4& localToWorld ){ + test.BeginMesh( localToWorld ); + + SelectionIntersection best; + aabb_testselect( m_aabb_local, test, best ); + if ( best.valid() ) { + selector.addIntersection( best ); + } } -} }; class NullModelInstance : public scene::Instance, public Renderable, public SelectionTestable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -NullModel& m_nullmodel; + NullModel& m_nullmodel; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Bounded& get( NullType){ - return m_nullmodel; -} -Cullable& get( NullType){ - return m_nullmodel; -} + Bounded& get( NullType){ + return m_nullmodel; + } + Cullable& get( NullType){ + return m_nullmodel; + } -NullModelInstance( const scene::Path& path, scene::Instance* parent, NullModel& nullmodel ) : - Instance( path, parent, this, StaticTypeCasts::instance().get() ), - m_nullmodel( nullmodel ){ -} + NullModelInstance( const scene::Path& path, scene::Instance* parent, NullModel& nullmodel ) : + Instance( path, parent, this, StaticTypeCasts::instance().get() ), + m_nullmodel( nullmodel ){ + } -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_nullmodel.renderSolid( renderer, volume, Instance::localToWorld() ); -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_nullmodel.renderWireframe( renderer, volume, Instance::localToWorld() ); -} + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_nullmodel.renderSolid( renderer, volume, Instance::localToWorld() ); + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_nullmodel.renderWireframe( renderer, volume, Instance::localToWorld() ); + } -void testSelect( Selector& selector, SelectionTest& test ){ - m_nullmodel.testSelect( selector, test, Instance::localToWorld() ); -} + void testSelect( Selector& selector, SelectionTest& test ){ + m_nullmodel.testSelect( selector, test, Instance::localToWorld() ); + } }; class NullModelNode : public scene::Node::Symbiot, public scene::Instantiable { -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + } + NodeTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -NullModel m_nullmodel; + scene::Node m_node; + InstanceSet m_instances; + NullModel m_nullmodel; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -NullModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ - m_node.m_isRoot = true; -} + NullModelNode() : m_node( this, this, StaticTypeCasts::instance().get() ){ + m_node.m_isRoot = true; + } -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new NullModelInstance( path, parent, m_nullmodel ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new NullModelInstance( path, parent, m_nullmodel ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; NodeSmartReference NewNullModel(){ diff --git a/radiant/parse.cpp b/radiant/parse.cpp index ac5dd3b2..36e3485f 100644 --- a/radiant/parse.cpp +++ b/radiant/parse.cpp @@ -26,19 +26,19 @@ class ScriptLibraryAPI { -_QERScripLibTable m_scriptlibrary; + _QERScripLibTable m_scriptlibrary; public: -typedef _QERScripLibTable Type; -STRING_CONSTANT( Name, "*" ); + typedef _QERScripLibTable Type; + STRING_CONSTANT( Name, "*" ); -ScriptLibraryAPI(){ - m_scriptlibrary.m_pfnNewScriptTokeniser = &NewScriptTokeniser; - m_scriptlibrary.m_pfnNewSimpleTokeniser = &NewSimpleTokeniser; - m_scriptlibrary.m_pfnNewSimpleTokenWriter = &NewSimpleTokenWriter; -} -_QERScripLibTable* getTable(){ - return &m_scriptlibrary; -} + ScriptLibraryAPI(){ + m_scriptlibrary.m_pfnNewScriptTokeniser = &NewScriptTokeniser; + m_scriptlibrary.m_pfnNewSimpleTokeniser = &NewSimpleTokeniser; + m_scriptlibrary.m_pfnNewSimpleTokenWriter = &NewSimpleTokenWriter; + } + _QERScripLibTable* getTable(){ + return &m_scriptlibrary; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/patch.cpp b/radiant/patch.cpp index c2eb9b35..08aa9972 100644 --- a/radiant/patch.cpp +++ b/radiant/patch.cpp @@ -197,7 +197,8 @@ void Patch::setDims( std::size_t w, std::size_t h ){ h = MIN_PATCH_HEIGHT; } - m_width = w; m_height = h; + m_width = w; + m_height = h; if ( m_width * m_height != m_ctrl.size() ) { m_ctrl.resize( m_width * m_height ); @@ -221,10 +222,10 @@ bool Patch::isValid() const { for ( const_iterator i = m_ctrl.begin(); i != m_ctrl.end(); ++i ) { if ( !float_valid( ( *i ).m_vertex.x() ) - || !float_valid( ( *i ).m_vertex.y() ) - || !float_valid( ( *i ).m_vertex.z() ) - || !float_valid( ( *i ).m_texcoord.x() ) - || !float_valid( ( *i ).m_texcoord.y() ) ) { + || !float_valid( ( *i ).m_vertex.y() ) + || !float_valid( ( *i ).m_vertex.z() ) + || !float_valid( ( *i ).m_texcoord.x() ) + || !float_valid( ( *i ).m_texcoord.y() ) ) { globalErrorStream() << "patch has invalid control points\n"; return false; } @@ -654,7 +655,13 @@ Vector3 Patch::Calculate_AvgNormal() const { inline int texture_axis( const Vector3& normal ){ // axis dominance order: Z, X, Y - return ( normal.x() >= normal.y() ) ? ( normal.x() > normal.z() ) ? 0 : 2 : ( normal.y() > normal.z() ) ? 1 : 2; + return ( normal.x() >= normal.y() ) + ? ( normal.x() > normal.z() ) + ? 0 + : 2 + : ( normal.y() > normal.z() ) + ? 1 + : 2; } void Patch::CapTexture(){ @@ -668,18 +675,18 @@ void Patch::CapTexture(){ { Vector3 tmp( vector3_cross( - vector3_subtracted( p2.m_vertex, m_ctrl[0].m_vertex ), - vector3_subtracted( p3.m_vertex, m_ctrl[0].m_vertex ) - ) ); + vector3_subtracted( p2.m_vertex, m_ctrl[0].m_vertex ), + vector3_subtracted( p3.m_vertex, m_ctrl[0].m_vertex ) + ) ); if ( !vector3_equal( tmp, g_vector3_identity ) ) { vector3_add( normal, tmp ); } } { Vector3 tmp( vector3_cross( - vector3_subtracted( p1.m_vertex, p3.m_vertex ), - vector3_subtracted( m_ctrl[0].m_vertex, p3.m_vertex ) - ) ); + vector3_subtracted( p1.m_vertex, p3.m_vertex ), + vector3_subtracted( m_ctrl[0].m_vertex, p3.m_vertex ) + ) ); if ( !vector3_equal( tmp, g_vector3_identity ) ) { vector3_add( normal, tmp ); } @@ -1049,7 +1056,8 @@ void Patch::RemovePoints( EMatrixMajor mt, bool bFirst ){ for ( std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride ) { if ( h == pos ) { - p1 += 2 * row_stride2; h += 2; + p1 += 2 * row_stride2; + h += 2; } *p2 = *p1; } @@ -1076,107 +1084,107 @@ void Patch::ConstructSeam( EPatchCap eType, Vector3* p, std::size_t width ){ switch ( eType ) { case eCapIBevel: - { - setDims( 3, 3 ); - m_ctrl[0].m_vertex = p[0]; - m_ctrl[1].m_vertex = p[1]; - m_ctrl[2].m_vertex = p[1]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[1]; - m_ctrl[5].m_vertex = p[1]; - m_ctrl[6].m_vertex = p[2]; - m_ctrl[7].m_vertex = p[1]; - m_ctrl[8].m_vertex = p[1]; - } - break; + { + setDims( 3, 3 ); + m_ctrl[0].m_vertex = p[0]; + m_ctrl[1].m_vertex = p[1]; + m_ctrl[2].m_vertex = p[1]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[1]; + m_ctrl[5].m_vertex = p[1]; + m_ctrl[6].m_vertex = p[2]; + m_ctrl[7].m_vertex = p[1]; + m_ctrl[8].m_vertex = p[1]; + } + break; case eCapBevel: - { - setDims( 3, 3 ); - Vector3 p3( vector3_added( p[2], vector3_subtracted( p[0], p[1] ) ) ); - m_ctrl[0].m_vertex = p3; - m_ctrl[1].m_vertex = p3; - m_ctrl[2].m_vertex = p[2]; - m_ctrl[3].m_vertex = p3; - m_ctrl[4].m_vertex = p3; - m_ctrl[5].m_vertex = p[1]; - m_ctrl[6].m_vertex = p3; - m_ctrl[7].m_vertex = p3; - m_ctrl[8].m_vertex = p[0]; - } - break; + { + setDims( 3, 3 ); + Vector3 p3( vector3_added( p[2], vector3_subtracted( p[0], p[1] ) ) ); + m_ctrl[0].m_vertex = p3; + m_ctrl[1].m_vertex = p3; + m_ctrl[2].m_vertex = p[2]; + m_ctrl[3].m_vertex = p3; + m_ctrl[4].m_vertex = p3; + m_ctrl[5].m_vertex = p[1]; + m_ctrl[6].m_vertex = p3; + m_ctrl[7].m_vertex = p3; + m_ctrl[8].m_vertex = p[0]; + } + break; case eCapEndCap: - { - Vector3 p5( vector3_mid( p[0], p[4] ) ); + { + Vector3 p5( vector3_mid( p[0], p[4] ) ); - setDims( 3, 3 ); - m_ctrl[0].m_vertex = p[0]; - m_ctrl[1].m_vertex = p5; - m_ctrl[2].m_vertex = p[4]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[2]; - m_ctrl[5].m_vertex = p[3]; - m_ctrl[6].m_vertex = p[2]; - m_ctrl[7].m_vertex = p[2]; - m_ctrl[8].m_vertex = p[2]; - } - break; + setDims( 3, 3 ); + m_ctrl[0].m_vertex = p[0]; + m_ctrl[1].m_vertex = p5; + m_ctrl[2].m_vertex = p[4]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[2]; + m_ctrl[5].m_vertex = p[3]; + m_ctrl[6].m_vertex = p[2]; + m_ctrl[7].m_vertex = p[2]; + m_ctrl[8].m_vertex = p[2]; + } + break; case eCapIEndCap: - { - setDims( 5, 3 ); - m_ctrl[0].m_vertex = p[4]; - m_ctrl[1].m_vertex = p[3]; - m_ctrl[2].m_vertex = p[2]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[0]; - m_ctrl[5].m_vertex = p[3]; - m_ctrl[6].m_vertex = p[3]; - m_ctrl[7].m_vertex = p[2]; - m_ctrl[8].m_vertex = p[1]; - m_ctrl[9].m_vertex = p[1]; - m_ctrl[10].m_vertex = p[3]; - m_ctrl[11].m_vertex = p[3]; - m_ctrl[12].m_vertex = p[2]; - m_ctrl[13].m_vertex = p[1]; - m_ctrl[14].m_vertex = p[1]; - } - break; + { + setDims( 5, 3 ); + m_ctrl[0].m_vertex = p[4]; + m_ctrl[1].m_vertex = p[3]; + m_ctrl[2].m_vertex = p[2]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[0]; + m_ctrl[5].m_vertex = p[3]; + m_ctrl[6].m_vertex = p[3]; + m_ctrl[7].m_vertex = p[2]; + m_ctrl[8].m_vertex = p[1]; + m_ctrl[9].m_vertex = p[1]; + m_ctrl[10].m_vertex = p[3]; + m_ctrl[11].m_vertex = p[3]; + m_ctrl[12].m_vertex = p[2]; + m_ctrl[13].m_vertex = p[1]; + m_ctrl[14].m_vertex = p[1]; + } + break; case eCapCylinder: - { - std::size_t mid = ( width - 1 ) >> 1; - - bool degenerate = ( mid % 2 ) != 0; - - std::size_t newHeight = mid + ( degenerate ? 2 : 1 ); - - setDims( 3, newHeight ); - - if ( degenerate ) { - ++mid; - for ( std::size_t i = width; i != width + 2; ++i ) - { - p[i] = p[width - 1]; - } - } - { - PatchControl* pCtrl = m_ctrl.data(); - for ( std::size_t i = 0; i != m_height; ++i, pCtrl += m_width ) - { - pCtrl->m_vertex = p[i]; - } - } - { - PatchControl* pCtrl = m_ctrl.data() + 2; - std::size_t h = m_height - 1; - for ( std::size_t i = 0; i != m_height; ++i, pCtrl += m_width ) - { - pCtrl->m_vertex = p[h + ( h - i )]; - } - } + std::size_t mid = ( width - 1 ) >> 1; - Redisperse( COL ); - } - break; + bool degenerate = ( mid % 2 ) != 0; + + std::size_t newHeight = mid + ( degenerate ? 2 : 1 ); + + setDims( 3, newHeight ); + + if ( degenerate ) { + ++mid; + for ( std::size_t i = width; i != width + 2; ++i ) + { + p[i] = p[width - 1]; + } + } + + { + PatchControl* pCtrl = m_ctrl.data(); + for ( std::size_t i = 0; i != m_height; ++i, pCtrl += m_width ) + { + pCtrl->m_vertex = p[i]; + } + } + { + PatchControl* pCtrl = m_ctrl.data() + 2; + std::size_t h = m_height - 1; + for ( std::size_t i = 0; i != m_height; ++i, pCtrl += m_width ) + { + pCtrl->m_vertex = p[h + ( h - i )]; + } + } + + Redisperse( COL ); + } + break; default: ERROR_MESSAGE( "invalid patch-cap type" ); return; @@ -1327,11 +1335,11 @@ void Patch::ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std constructPlane( aabb, axis, width, height ); } else if ( eType == eSqCylinder - || eType == eCylinder - || eType == eDenseCylinder - || eType == eVeryDenseCylinder - || eType == eCone - || eType == eSphere ) { + || eType == eCylinder + || eType == eDenseCylinder + || eType == eVeryDenseCylinder + || eType == eCone + || eType == eSphere ) { unsigned char *pIndex; unsigned char pCylIndex[] = { @@ -1350,7 +1358,8 @@ void Patch::ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std PatchControl *pStart; switch ( eType ) { - case eSqCylinder: setDims( 9, 3 ); + case eSqCylinder: + setDims( 9, 3 ); pStart = m_ctrl.data(); break; case eDenseCylinder: @@ -1359,7 +1368,8 @@ void Patch::ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std setDims( 9, 3 ); pStart = m_ctrl.data() + 1; break; - case eCone: setDims( 9, 3 ); + case eCone: + setDims( 9, 3 ); pStart = m_ctrl.data() + 1; break; case eSphere: @@ -1387,33 +1397,33 @@ void Patch::ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std switch ( eType ) { case eSqCylinder: - { - PatchControl* pCtrl = m_ctrl.data(); - for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) { - pCtrl[8].m_vertex = pCtrl[0].m_vertex; + PatchControl* pCtrl = m_ctrl.data(); + for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) + { + pCtrl[8].m_vertex = pCtrl[0].m_vertex; + } } - } - break; + break; case eDenseCylinder: case eVeryDenseCylinder: case eCylinder: - { - PatchControl* pCtrl = m_ctrl.data(); - for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; + PatchControl* pCtrl = m_ctrl.data(); + for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } } - } - break; + break; case eCone: - { - PatchControl* pCtrl = m_ctrl.data(); - for ( std::size_t h = 0; h < 2; h++, pCtrl += 9 ) { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; + PatchControl* pCtrl = m_ctrl.data(); + for ( std::size_t h = 0; h < 2; h++, pCtrl += 9 ) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } } - } { PatchControl* pCtrl = m_ctrl.data() + 9 * 2; for ( std::size_t w = 0; w < 9; w++, pCtrl++ ) @@ -1425,13 +1435,13 @@ void Patch::ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std } break; case eSphere: - { - PatchControl* pCtrl = m_ctrl.data() + 9; - for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; + PatchControl* pCtrl = m_ctrl.data() + 9; + for ( std::size_t h = 0; h < 3; h++, pCtrl += 9 ) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } } - } { PatchControl* pCtrl = m_ctrl.data(); for ( std::size_t w = 0; w < 9; w++, pCtrl++ ) @@ -1625,31 +1635,31 @@ void RenderablePatchSolid::RenderNormals() const { { { Vector3 vNormal( - vector3_added( - vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), - vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->normal ), 8 ) - ) - ); + vector3_added( + vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), + vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->normal ), 8 ) + ) + ); glVertex3fv( vertex3f_to_array( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ) ); glVertex3fv( &vNormal[0] ); } { Vector3 vNormal( - vector3_added( - vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), - vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->tangent ), 8 ) - ) - ); + vector3_added( + vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), + vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->tangent ), 8 ) + ) + ); glVertex3fv( vertex3f_to_array( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ) ); glVertex3fv( &vNormal[0] ); } { Vector3 vNormal( - vector3_added( - vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), - vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->bitangent ), 8 ) - ) - ); + vector3_added( + vertex3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ), + vector3_scaled( normal3f_to_vector3( ( m_tess.m_vertices.data() + ( j * width + i ) )->bitangent ), 8 ) + ) + ); glVertex3fv( vertex3f_to_array( ( m_tess.m_vertices.data() + ( j * width + i ) )->vertex ) ); glVertex3fv( &vNormal[0] ); } @@ -1911,12 +1921,12 @@ void Patch::TesselateSubMatrixFixed( ArbitraryMeshVertex* vertices, std::size_t } void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, - std::size_t offStartX, std::size_t offStartY, - std::size_t offEndX, std::size_t offEndY, - std::size_t nFlagsX, std::size_t nFlagsY, - Vector3& left, Vector3& mid, Vector3& right, - Vector2& texLeft, Vector2& texMid, Vector2& texRight, - bool bTranspose ){ + std::size_t offStartX, std::size_t offStartY, + std::size_t offEndX, std::size_t offEndY, + std::size_t nFlagsX, std::size_t nFlagsY, + Vector3& left, Vector3& mid, Vector3& right, + Vector2& texLeft, Vector2& texMid, Vector2& texRight, + bool bTranspose ){ int newFlagsX, newFlagsY; Vector3 tmp; @@ -1928,25 +1938,25 @@ void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree // texcoords BezierInterpolate2( texcoord_for_index( m_tess.m_vertices, offStartX + offStartY ), - texcoord_0_0, - texcoord_for_index( m_tess.m_vertices, BX->index + offStartY ), - texcoord_0_1, - texcoord_for_index( m_tess.m_vertices, offEndX + offStartY ) ); + texcoord_0_0, + texcoord_for_index( m_tess.m_vertices, BX->index + offStartY ), + texcoord_0_1, + texcoord_for_index( m_tess.m_vertices, offEndX + offStartY ) ); BezierInterpolate2( texcoord_for_index( m_tess.m_vertices, offStartX + offEndY ), - texcoord_2_0, - texcoord_for_index( m_tess.m_vertices, BX->index + offEndY ), - texcoord_2_1, - texcoord_for_index( m_tess.m_vertices, offEndX + offEndY ) ); + texcoord_2_0, + texcoord_for_index( m_tess.m_vertices, BX->index + offEndY ), + texcoord_2_1, + texcoord_for_index( m_tess.m_vertices, offEndX + offEndY ) ); texTmp = texMid; BezierInterpolate2( texLeft, - texcoord_1_0, - texTmp, - texcoord_1_1, - texRight ); + texcoord_1_0, + texTmp, + texcoord_1_1, + texRight ); if ( !BezierCurveTree_isLeaf( BY ) ) { texcoord_for_index( m_tess.m_vertices, BX->index + BY->index ) = texTmp; @@ -1974,26 +1984,26 @@ void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree // verts BezierInterpolate3( vertex_for_index( m_tess.m_vertices, offStartX + offStartY ), - vertex_0_0, - vertex_for_index( m_tess.m_vertices, BX->index + offStartY ), - vertex_0_1, - vertex_for_index( m_tess.m_vertices, offEndX + offStartY ) ); + vertex_0_0, + vertex_for_index( m_tess.m_vertices, BX->index + offStartY ), + vertex_0_1, + vertex_for_index( m_tess.m_vertices, offEndX + offStartY ) ); BezierInterpolate3( vertex_for_index( m_tess.m_vertices, offStartX + offEndY ), - vertex_2_0, - vertex_for_index( m_tess.m_vertices, BX->index + offEndY ), - vertex_2_1, - vertex_for_index( m_tess.m_vertices, offEndX + offEndY ) ); + vertex_2_0, + vertex_for_index( m_tess.m_vertices, BX->index + offEndY ), + vertex_2_1, + vertex_for_index( m_tess.m_vertices, offEndX + offEndY ) ); tmp = mid; BezierInterpolate3( left, - vertex_1_0, - tmp, - vertex_1_1, - right ); + vertex_1_0, + tmp, + vertex_1_1, + right ); if ( !BezierCurveTree_isLeaf( BY ) ) { vertex_for_index( m_tess.m_vertices, BX->index + BY->index ) = tmp; @@ -2205,12 +2215,12 @@ void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree Vector2 stTemp( p2 ); TesselateSubMatrix( BY, BX->left, - offStartY, offStartX, - offEndY, BX->index, - newFlagsY, newFlagsX, - vertex_0_0, vertex_1_0, vertex_2_0, - texcoord_0_0, texcoord_1_0, texcoord_2_0, - !bTranspose ); + offStartY, offStartX, + offEndY, BX->index, + newFlagsY, newFlagsX, + vertex_0_0, vertex_1_0, vertex_2_0, + texcoord_0_0, texcoord_1_0, texcoord_2_0, + !bTranspose ); newFlagsY = nTemp; p = vTemp; @@ -2218,37 +2228,38 @@ void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree } if ( ( nFlagsY & DEGEN_2a ) && ( nFlagsY & DEGEN_2b ) ) { - newFlagsY |= DEGEN_2a; newFlagsY |= DEGEN_2b; + newFlagsY |= DEGEN_2a; + newFlagsY |= DEGEN_2b; } TesselateSubMatrix( BY, BX->right, - offStartY, BX->index, - offEndY, offEndX, - newFlagsY, newFlagsX, - vertex_0_1, vertex_1_1, vertex_2_1, - texcoord_0_1, texcoord_1_1, texcoord_2_1, - !bTranspose ); + offStartY, BX->index, + offEndY, offEndX, + newFlagsY, newFlagsX, + vertex_0_1, vertex_1_1, vertex_2_1, + texcoord_0_1, texcoord_1_1, texcoord_2_1, + !bTranspose ); } else { if ( !BezierCurveTree_isLeaf( BX->left ) ) { TesselateSubMatrix( BX->left, BY, - offStartX, offStartY, - BX->index, offEndY, - newFlagsX, newFlagsY, - left, vertex_1_0, tmp, - texLeft, texcoord_1_0, texTmp, - bTranspose ); + offStartX, offStartY, + BX->index, offEndY, + newFlagsX, newFlagsY, + left, vertex_1_0, tmp, + texLeft, texcoord_1_0, texTmp, + bTranspose ); } if ( !BezierCurveTree_isLeaf( BX->right ) ) { TesselateSubMatrix( BX->right, BY, - BX->index, offStartY, - offEndX, offEndY, - newFlagsX, newFlagsY, - tmp, vertex_1_1, right, - texTmp, texcoord_1_1, texRight, - bTranspose ); + BX->index, offStartY, + offEndX, offEndY, + newFlagsX, newFlagsY, + tmp, vertex_1_1, right, + texTmp, texcoord_1_1, texRight, + bTranspose ); } } @@ -2393,57 +2404,57 @@ inline void vertex_clear_normal( ArbitraryMeshVertex& vertex ){ inline void tangents_remove_degenerate( Vector3 tangents[6], Vector2 textureTangents[6], unsigned int flags ){ if ( flags & DEGEN_0a ) { const std::size_t i = - ( flags & DEGEN_0b ) - ? ( flags & DEGEN_1a ) - ? ( flags & DEGEN_1b ) - ? ( flags & DEGEN_2a ) - ? 5 - : 4 - : 3 - : 2 - : 1; + ( flags & DEGEN_0b ) + ? ( flags & DEGEN_1a ) + ? ( flags & DEGEN_1b ) + ? ( flags & DEGEN_2a ) + ? 5 + : 4 + : 3 + : 2 + : 1; tangents[0] = tangents[i]; textureTangents[0] = textureTangents[i]; } if ( flags & DEGEN_0b ) { const std::size_t i = - ( flags & DEGEN_0a ) - ? ( flags & DEGEN_1b ) - ? ( flags & DEGEN_1a ) - ? ( flags & DEGEN_2b ) - ? 4 - : 5 - : 2 - : 3 - : 0; + ( flags & DEGEN_0a ) + ? ( flags & DEGEN_1b ) + ? ( flags & DEGEN_1a ) + ? ( flags & DEGEN_2b ) + ? 4 + : 5 + : 2 + : 3 + : 0; tangents[1] = tangents[i]; textureTangents[1] = textureTangents[i]; } if ( flags & DEGEN_2a ) { const std::size_t i = - ( flags & DEGEN_2b ) - ? ( flags & DEGEN_1a ) - ? ( flags & DEGEN_1b ) - ? ( flags & DEGEN_0a ) - ? 1 - : 0 - : 3 - : 2 - : 5; + ( flags & DEGEN_2b ) + ? ( flags & DEGEN_1a ) + ? ( flags & DEGEN_1b ) + ? ( flags & DEGEN_0a ) + ? 1 + : 0 + : 3 + : 2 + : 5; tangents[4] = tangents[i]; textureTangents[4] = textureTangents[i]; } if ( flags & DEGEN_2b ) { const std::size_t i = - ( flags & DEGEN_2a ) - ? ( flags & DEGEN_1b ) - ? ( flags & DEGEN_1a ) - ? ( flags & DEGEN_0b ) - ? 0 - : 1 - : 2 - : 3 - : 4; + ( flags & DEGEN_2a ) + ? ( flags & DEGEN_1b ) + ? ( flags & DEGEN_1a ) + ? ( flags & DEGEN_0b ) + ? 0 + : 1 + : 2 + : 3 + : 4; tangents[5] = tangents[i]; textureTangents[5] = textureTangents[i]; } @@ -2864,19 +2875,19 @@ void Patch::BuildVertexArray(){ { if ( !leafX ) { TesselateSubMatrix( m_tess.m_curveTreeU[i >> 1], m_tess.m_curveTreeV[j >> 1], - offStartX, offStartY, offEndX, offEndY, // array offsets - nFlagsX, nFlagsY, - subMatrix[1][0]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[1][2]->m_vertex, - subMatrix[1][0]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[1][2]->m_texcoord, - false ); + offStartX, offStartY, offEndX, offEndY, // array offsets + nFlagsX, nFlagsY, + subMatrix[1][0]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[1][2]->m_vertex, + subMatrix[1][0]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[1][2]->m_texcoord, + false ); } else if ( !leafY ) { TesselateSubMatrix( m_tess.m_curveTreeV[j >> 1], m_tess.m_curveTreeU[i >> 1], - offStartY, offStartX, offEndY, offEndX, // array offsets - nFlagsY, nFlagsX, - subMatrix[0][1]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[2][1]->m_vertex, - subMatrix[0][1]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[2][1]->m_texcoord, - true ); + offStartY, offStartX, offEndY, offEndX, // array offsets + nFlagsY, nFlagsX, + subMatrix[0][1]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[2][1]->m_vertex, + subMatrix[0][1]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[2][1]->m_texcoord, + true ); } } @@ -2905,7 +2916,7 @@ Vector3 getAverageNormal(const Vector3& normal1, const Vector3& normal2) // Now calculate the length correction out of the angle // of the two normals - /* float factor = cos(n1.angle(n2) * 0.5); */ + /* float factor = cos(n1.angle(n2) * 0.5); */ float factor = (float) vector3_dot( normal1, normal2 ); if ( factor > 1.0 ) factor = 1; if ( factor < -1.0 ) factor = -1; @@ -2924,16 +2935,16 @@ Vector3 getAverageNormal(const Vector3& normal1, const Vector3& normal2) } void Patch::createThickenedOpposite(const Patch& sourcePatch, - const float thickness, - const int axis, - bool& no12, - bool& no34) + const float thickness, + const int axis, + bool& no12, + bool& no34) { // Clone the dimensions from the other patch setDims(sourcePatch.getWidth(), sourcePatch.getHeight()); // Also inherit the tesselation from the source patch - //setFixedSubdivisions(sourcePatch.subdivionsFixed(), sourcePatch.getSubdivisions()); + //setFixedSubdivisions(sourcePatch.subdivionsFixed(), sourcePatch.getSubdivisions()); // Copy the shader from the source patch SetShader(sourcePatch.GetShader()); @@ -2942,18 +2953,18 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, Vector3 extrudeAxis(0,0,0); switch (axis) { - case 0: // X-Axis - extrudeAxis = Vector3(1,0,0); - break; - case 1: // Y-Axis - extrudeAxis = Vector3(0,1,0); - break; - case 2: // Z-Axis - extrudeAxis = Vector3(0,0,1); - break; - default: - // Default value already set during initialisation - break; + case 0: // X-Axis + extrudeAxis = Vector3(1,0,0); + break; + case 1: // Y-Axis + extrudeAxis = Vector3(0,1,0); + break; + case 2: // Z-Axis + extrudeAxis = Vector3(0,0,1); + break; + default: + // Default value already set during initialisation + break; } //check if certain seams are required + cycling in normals calculation is needed @@ -3037,7 +3048,7 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, // Cull redundant tangents (parallel) if ( vector3_length_squared( colTangent[1] + colTangent[0] ) == 0 || - vector3_length_squared( colTangent[1] - colTangent[0] ) == 0 ){ + vector3_length_squared( colTangent[1] - colTangent[0] ) == 0 ){ colTangent[1] = Vector3(0,0,0); } } @@ -3093,7 +3104,7 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, // Cull redundant tangents (parallel) if ( vector3_length_squared( rowTangent[1] + rowTangent[0] ) == 0 || - vector3_length_squared( rowTangent[1] - rowTangent[0] ) == 0 ){ + vector3_length_squared( rowTangent[1] - rowTangent[0] ) == 0 ){ rowTangent[1] = Vector3(0,0,0); } } @@ -3101,19 +3112,19 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, //clean parallel pairs... if ( vector3_length_squared( rowTangent[0] + colTangent[0] ) == 0 || - vector3_length_squared( rowTangent[0] - colTangent[0] ) == 0 ){ + vector3_length_squared( rowTangent[0] - colTangent[0] ) == 0 ){ rowTangent[0] = Vector3(0,0,0); } if ( vector3_length_squared( rowTangent[1] + colTangent[1] ) == 0 || - vector3_length_squared( rowTangent[1] - colTangent[1] ) == 0 ){ + vector3_length_squared( rowTangent[1] - colTangent[1] ) == 0 ){ rowTangent[1] = Vector3(0,0,0); } if ( vector3_length_squared( rowTangent[0] + colTangent[1] ) == 0 || - vector3_length_squared( rowTangent[0] - colTangent[1] ) == 0 ){ + vector3_length_squared( rowTangent[0] - colTangent[1] ) == 0 ){ colTangent[1] = Vector3(0,0,0); } if ( vector3_length_squared( rowTangent[1] + colTangent[0] ) == 0 || - vector3_length_squared( rowTangent[1] - colTangent[0] ) == 0 ){ + vector3_length_squared( rowTangent[1] - colTangent[0] ) == 0 ){ rowTangent[1] = Vector3(0,0,0); } @@ -3133,7 +3144,7 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, else{ // If two column + two row tangents are available, take the length-corrected average if ( ( fabs( colTangent[1][0] ) + fabs( colTangent[1][1] ) + fabs( colTangent[1][2] ) ) > 0 && - ( fabs( rowTangent[1][0] ) + fabs( rowTangent[1][1] ) + fabs( rowTangent[1][2] ) ) > 0 ) + ( fabs( rowTangent[1][0] ) + fabs( rowTangent[1][1] ) + fabs( rowTangent[1][2] ) ) > 0 ) { // Two column normals to calculate Vector3 normal1 = vector3_normalised( vector3_cross( rowTangent[0], colTangent[0] ) ); @@ -3213,8 +3224,8 @@ void Patch::createThickenedOpposite(const Patch& sourcePatch, } void Patch::createThickenedWall(const Patch& sourcePatch, - const Patch& targetPatch, - const int wallIndex) + const Patch& targetPatch, + const int wallIndex) { // Copy the shader from the source patch SetShader(sourcePatch.GetShader()); @@ -3240,34 +3251,34 @@ void Patch::createThickenedWall(const Patch& sourcePatch, // Determine which of the four edges have to be connected // and calculate the start, end & stepsize for the following loop switch (wallIndex) { - case 0: - cols = sourceWidth; - start = 0; - end = sourceWidth - 1; - incr = 1; - //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationX); - break; - case 1: - cols = sourceWidth; - start = sourceWidth * (sourceHeight-1); - end = sourceWidth*sourceHeight - 1; - incr = 1; - //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationX); - break; - case 2: - cols = sourceHeight; - start = 0; - end = sourceWidth*(sourceHeight-1); - incr = sourceWidth; - //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationY); - break; - case 3: - cols = sourceHeight; - start = sourceWidth - 1; - end = sourceWidth*sourceHeight - 1; - incr = sourceWidth; - //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationY); - break; + case 0: + cols = sourceWidth; + start = 0; + end = sourceWidth - 1; + incr = 1; + //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationX); + break; + case 1: + cols = sourceWidth; + start = sourceWidth * (sourceHeight-1); + end = sourceWidth*sourceHeight - 1; + incr = 1; + //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationX); + break; + case 2: + cols = sourceHeight; + start = 0; + end = sourceWidth*(sourceHeight-1); + incr = sourceWidth; + //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationY); + break; + case 3: + cols = sourceHeight; + start = sourceWidth - 1; + end = sourceWidth*sourceHeight - 1; + incr = sourceWidth; + //setFixedSubdivisions(sourceTesselationFixed, sourceTesselationY); + break; } setDims(cols, rows); @@ -3302,21 +3313,21 @@ void Patch::createThickenedWall(const Patch& sourcePatch, class PatchFilterWrapper : public Filter { -bool m_active; -bool m_invert; -PatchFilter& m_filter; + bool m_active; + bool m_invert; + PatchFilter& m_filter; public: -PatchFilterWrapper( PatchFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ -} -void setActive( bool active ){ - m_active = active; -} -bool active(){ - return m_active; -} -bool filter( const Patch& patch ){ - return m_invert ^ m_filter.filter( patch ); -} + PatchFilterWrapper( PatchFilter& filter, bool invert ) : m_invert( invert ), m_filter( filter ){ + } + void setActive( bool active ){ + m_active = active; + } + bool active(){ + return m_active; + } + bool filter( const Patch& patch ){ + return m_invert ^ m_filter.filter( patch ); + } }; diff --git a/radiant/patch.h b/radiant/patch.h index b0c8ce56..79b977a2 100644 --- a/radiant/patch.h +++ b/radiant/patch.h @@ -156,7 +156,7 @@ class Patch; class PatchFilter { public: -virtual bool filter( const Patch& patch ) const = 0; + virtual bool filter( const Patch& patch ) const = 0; }; bool patch_filtered( Patch& patch ); @@ -188,129 +188,85 @@ inline void PatchControlArray_invert( Array& ctrl, std::size_t wid class PatchTesselation { public: -PatchTesselation() - : m_numStrips( 0 ), m_lenStrips( 0 ), m_nArrayWidth( 0 ), m_nArrayHeight( 0 ){ -} -Array m_vertices; -Array m_indices; -std::size_t m_numStrips; -std::size_t m_lenStrips; + PatchTesselation() + : m_numStrips( 0 ), m_lenStrips( 0 ), m_nArrayWidth( 0 ), m_nArrayHeight( 0 ){ + } + Array m_vertices; + Array m_indices; + std::size_t m_numStrips; + std::size_t m_lenStrips; -Array m_arrayWidth; -std::size_t m_nArrayWidth; -Array m_arrayHeight; -std::size_t m_nArrayHeight; + Array m_arrayWidth; + std::size_t m_nArrayWidth; + Array m_arrayHeight; + std::size_t m_nArrayHeight; -Array m_curveTreeU; -Array m_curveTreeV; + Array m_curveTreeU; + Array m_curveTreeV; }; class RenderablePatchWireframe : public OpenGLRenderable { -PatchTesselation& m_tess; + PatchTesselation& m_tess; public: -RenderablePatchWireframe( PatchTesselation& tess ) : m_tess( tess ){ -} -void render( RenderStateFlags state ) const { - { - #if NV_DRIVER_BUG - glVertexPointer( 3, GL_FLOAT, 0, 0 ); - glDrawArrays( GL_TRIANGLE_FAN, 0, 0 ); - #endif - - std::size_t n = 0; - glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->vertex ); - for ( std::size_t i = 0; i <= m_tess.m_curveTreeV.size(); ++i ) - { - glDrawArrays( GL_LINE_STRIP, GLint( n ), GLsizei( m_tess.m_nArrayWidth ) ); - - if ( i == m_tess.m_curveTreeV.size() ) { - break; - } - - if ( !BezierCurveTree_isLeaf( m_tess.m_curveTreeV[i] ) ) { - glDrawArrays( GL_LINE_STRIP, GLint( m_tess.m_curveTreeV[i]->index ), GLsizei( m_tess.m_nArrayWidth ) ); - } - - n += ( m_tess.m_arrayHeight[i] * m_tess.m_nArrayWidth ); - - } + RenderablePatchWireframe( PatchTesselation& tess ) : m_tess( tess ){ } - - { - const ArbitraryMeshVertex* p = m_tess.m_vertices.data(); - std::size_t n = m_tess.m_nArrayWidth * sizeof( ArbitraryMeshVertex ); - for ( std::size_t i = 0; i <= m_tess.m_curveTreeU.size(); ++i ) + void render( RenderStateFlags state ) const { { - glVertexPointer( 3, GL_FLOAT, GLsizei( n ), &p->vertex ); - glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_tess.m_nArrayHeight ) ); +#if NV_DRIVER_BUG + glVertexPointer( 3, GL_FLOAT, 0, 0 ); + glDrawArrays( GL_TRIANGLE_FAN, 0, 0 ); +#endif + + std::size_t n = 0; + glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->vertex ); + for ( std::size_t i = 0; i <= m_tess.m_curveTreeV.size(); ++i ) + { + glDrawArrays( GL_LINE_STRIP, GLint( n ), GLsizei( m_tess.m_nArrayWidth ) ); + + if ( i == m_tess.m_curveTreeV.size() ) { + break; + } + + if ( !BezierCurveTree_isLeaf( m_tess.m_curveTreeV[i] ) ) { + glDrawArrays( GL_LINE_STRIP, GLint( m_tess.m_curveTreeV[i]->index ), GLsizei( m_tess.m_nArrayWidth ) ); + } + + n += ( m_tess.m_arrayHeight[i] * m_tess.m_nArrayWidth ); - if ( i == m_tess.m_curveTreeU.size() ) { - break; } + } - if ( !BezierCurveTree_isLeaf( m_tess.m_curveTreeU[i] ) ) { - glVertexPointer( 3, GL_FLOAT, GLsizei( n ), &( m_tess.m_vertices.data() + ( m_tess.m_curveTreeU[i]->index ) )->vertex ); + { + const ArbitraryMeshVertex* p = m_tess.m_vertices.data(); + std::size_t n = m_tess.m_nArrayWidth * sizeof( ArbitraryMeshVertex ); + for ( std::size_t i = 0; i <= m_tess.m_curveTreeU.size(); ++i ) + { + glVertexPointer( 3, GL_FLOAT, GLsizei( n ), &p->vertex ); glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_tess.m_nArrayHeight ) ); - } - p += m_tess.m_arrayWidth[i]; + if ( i == m_tess.m_curveTreeU.size() ) { + break; + } + + if ( !BezierCurveTree_isLeaf( m_tess.m_curveTreeU[i] ) ) { + glVertexPointer( 3, GL_FLOAT, GLsizei( n ), &( m_tess.m_vertices.data() + ( m_tess.m_curveTreeU[i]->index ) )->vertex ); + glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_tess.m_nArrayHeight ) ); + } + + p += m_tess.m_arrayWidth[i]; + } } } -} }; class RenderablePatchFixedWireframe : public OpenGLRenderable { -PatchTesselation& m_tess; + PatchTesselation& m_tess; public: -RenderablePatchFixedWireframe( PatchTesselation& tess ) : m_tess( tess ){ -} -void render( RenderStateFlags state ) const { - glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->vertex ); - const RenderIndex* strip_indices = m_tess.m_indices.data(); - for ( std::size_t i = 0; i < m_tess.m_numStrips; i++, strip_indices += m_tess.m_lenStrips ) - { - glDrawElements( GL_QUAD_STRIP, GLsizei( m_tess.m_lenStrips ), RenderIndexTypeID, strip_indices ); + RenderablePatchFixedWireframe( PatchTesselation& tess ) : m_tess( tess ){ } -} -}; - -class RenderablePatchSolid : public OpenGLRenderable -{ -PatchTesselation& m_tess; -public: -RenderablePatchSolid( PatchTesselation& tess ) : m_tess( tess ){ -} -void RenderNormals() const; -void render( RenderStateFlags state ) const { -#if 0 - if ( ( state & RENDER_FILL ) == 0 ) { - RenderablePatchWireframe( m_tess ).render( state ); - } - else -#endif - { - if ( ( state & RENDER_BUMP ) != 0 ) { - if ( GlobalShaderCache().useShaderLanguage() ) { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); - glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); - glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->tangent ); - glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->bitangent ); - } - else - { - glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); - glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); - glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->tangent ); - glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->bitangent ); - } - } - else - { - glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); - glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); - } + void render( RenderStateFlags state ) const { glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->vertex ); const RenderIndex* strip_indices = m_tess.m_indices.data(); for ( std::size_t i = 0; i < m_tess.m_numStrips; i++, strip_indices += m_tess.m_lenStrips ) @@ -318,11 +274,55 @@ void render( RenderStateFlags state ) const { glDrawElements( GL_QUAD_STRIP, GLsizei( m_tess.m_lenStrips ), RenderIndexTypeID, strip_indices ); } } +}; + +class RenderablePatchSolid : public OpenGLRenderable +{ + PatchTesselation& m_tess; +public: + RenderablePatchSolid( PatchTesselation& tess ) : m_tess( tess ){ + } + void RenderNormals() const; + void render( RenderStateFlags state ) const { +#if 0 + if ( ( state & RENDER_FILL ) == 0 ) { + RenderablePatchWireframe( m_tess ).render( state ); + } + else +#endif + { + if ( ( state & RENDER_BUMP ) != 0 ) { + if ( GlobalShaderCache().useShaderLanguage() ) { + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); + glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); + glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->tangent ); + glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->bitangent ); + } + else + { + glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); + glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); + glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->tangent ); + glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->bitangent ); + } + } + else + { + glNormalPointer( GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->normal ); + glTexCoordPointer( 2, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->texcoord ); + } + glVertexPointer( 3, GL_FLOAT, sizeof( ArbitraryMeshVertex ), &m_tess.m_vertices.data()->vertex ); + const RenderIndex* strip_indices = m_tess.m_indices.data(); + for ( std::size_t i = 0; i < m_tess.m_numStrips; i++, strip_indices += m_tess.m_lenStrips ) + { + glDrawElements( GL_QUAD_STRIP, GLsizei( m_tess.m_lenStrips ), RenderIndexTypeID, strip_indices ); + } + } #if defined( _DEBUG ) && !defined( _DEBUG_QUICKER ) - RenderNormals(); + RenderNormals(); #endif -} + } }; // parametric surface defined by quadratic bezier control curves @@ -337,689 +337,689 @@ class Patch : public Filterable, public Nameable { -class xml_state_t -{ -public: -enum EState -{ - eDefault, - ePatch, - eMatrix, - eShader, -}; -xml_state_t( EState state ) - : m_state( state ) -{} -EState state() const { - return m_state; -} -const char* content() const { - return m_content.c_str(); -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_content.write( buffer, length ); -} -private: -EState m_state; -StringOutputStream m_content; -}; + class xml_state_t + { + public: + enum EState + { + eDefault, + ePatch, + eMatrix, + eShader, + }; + xml_state_t( EState state ) + : m_state( state ) + {} + EState state() const { + return m_state; + } + const char* content() const { + return m_content.c_str(); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_content.write( buffer, length ); + } + private: + EState m_state; + StringOutputStream m_content; + }; -std::vector m_xml_state; + std::vector m_xml_state; -typedef Array PatchControlArray; + typedef Array PatchControlArray; -class SavedState : public UndoMemento -{ -public: -SavedState( - std::size_t width, - std::size_t height, - const PatchControlArray& ctrl, - const char* shader, - bool patchDef3, - std::size_t subdivisions_x, - std::size_t subdivisions_y - ) : - m_width( width ), - m_height( height ), - m_shader( shader ), - m_ctrl( ctrl ), - m_patchDef3( patchDef3 ), - m_subdivisions_x( subdivisions_x ), - m_subdivisions_y( subdivisions_y ){ -} + class SavedState : public UndoMemento + { + public: + SavedState( + std::size_t width, + std::size_t height, + const PatchControlArray& ctrl, + const char* shader, + bool patchDef3, + std::size_t subdivisions_x, + std::size_t subdivisions_y + ) : + m_width( width ), + m_height( height ), + m_shader( shader ), + m_ctrl( ctrl ), + m_patchDef3( patchDef3 ), + m_subdivisions_x( subdivisions_x ), + m_subdivisions_y( subdivisions_y ){ + } -void release(){ - delete this; -} + void release(){ + delete this; + } -std::size_t m_width, m_height; -CopiedString m_shader; -PatchControlArray m_ctrl; -bool m_patchDef3; -std::size_t m_subdivisions_x; -std::size_t m_subdivisions_y; -}; + std::size_t m_width, m_height; + CopiedString m_shader; + PatchControlArray m_ctrl; + bool m_patchDef3; + std::size_t m_subdivisions_x; + std::size_t m_subdivisions_y; + }; public: -class Observer -{ -public: -virtual void allocate( std::size_t size ) = 0; -}; + class Observer + { + public: + virtual void allocate( std::size_t size ) = 0; + }; private: -typedef UniqueSet Observers; -Observers m_observers; + typedef UniqueSet Observers; + Observers m_observers; -scene::Node* m_node; + scene::Node* m_node; -AABB m_aabb_local; // local bbox + AABB m_aabb_local; // local bbox -CopiedString m_shader; -Shader* m_state; + CopiedString m_shader; + Shader* m_state; -std::size_t m_width; -std::size_t m_height; + std::size_t m_width; + std::size_t m_height; public: -bool m_patchDef3; -std::size_t m_subdivisions_x; -std::size_t m_subdivisions_y; + bool m_patchDef3; + std::size_t m_subdivisions_x; + std::size_t m_subdivisions_y; private: -UndoObserver* m_undoable_observer; -MapFile* m_map; + UndoObserver* m_undoable_observer; + MapFile* m_map; // dynamically allocated array of control points, size is m_width*m_height -PatchControlArray m_ctrl; -PatchControlArray m_ctrlTransformed; + PatchControlArray m_ctrl; + PatchControlArray m_ctrlTransformed; -PatchTesselation m_tess; -RenderablePatchSolid m_render_solid; -RenderablePatchWireframe m_render_wireframe; -RenderablePatchFixedWireframe m_render_wireframe_fixed; + PatchTesselation m_tess; + RenderablePatchSolid m_render_solid; + RenderablePatchWireframe m_render_wireframe; + RenderablePatchFixedWireframe m_render_wireframe_fixed; -static Shader* m_state_ctrl; -static Shader* m_state_lattice; -VertexBuffer m_ctrl_vertices; -RenderableVertexBuffer m_render_ctrl; -IndexBuffer m_lattice_indices; -RenderableIndexBuffer m_render_lattice; + static Shader* m_state_ctrl; + static Shader* m_state_lattice; + VertexBuffer m_ctrl_vertices; + RenderableVertexBuffer m_render_ctrl; + IndexBuffer m_lattice_indices; + RenderableIndexBuffer m_render_lattice; -bool m_bOverlay; + bool m_bOverlay; -bool m_transformChanged; -Callback m_evaluateTransform; -Callback m_boundsChanged; + bool m_transformChanged; + Callback m_evaluateTransform; + Callback m_boundsChanged; -void construct(){ - m_bOverlay = false; - m_width = m_height = 0; + void construct(){ + m_bOverlay = false; + m_width = m_height = 0; - m_patchDef3 = false; - m_subdivisions_x = 0; - m_subdivisions_y = 0; + m_patchDef3 = false; + m_subdivisions_x = 0; + m_subdivisions_y = 0; - check_shader(); - captureShader(); + check_shader(); + captureShader(); - m_xml_state.push_back( xml_state_t::eDefault ); -} + m_xml_state.push_back( xml_state_t::eDefault ); + } public: -Callback m_lightsChanged; + Callback m_lightsChanged; //static int m_CycleCapIndex; // = 0; -static EPatchType m_type; + static EPatchType m_type; -STRING_CONSTANT( Name, "Patch" ); + STRING_CONSTANT( Name, "Patch" ); -Patch( scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : - m_node( &node ), - m_shader( texdef_name_default() ), - m_state( 0 ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_solid( m_tess ), - m_render_wireframe( m_tess ), - m_render_wireframe_fixed( m_tess ), - m_render_ctrl( GL_POINTS, m_ctrl_vertices ), - m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), - m_transformChanged( false ), - m_evaluateTransform( evaluateTransform ), - m_boundsChanged( boundsChanged ){ - construct(); -} -Patch( const Patch& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : - m_node( &node ), - m_shader( texdef_name_default() ), - m_state( 0 ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_solid( m_tess ), - m_render_wireframe( m_tess ), - m_render_wireframe_fixed( m_tess ), - m_render_ctrl( GL_POINTS, m_ctrl_vertices ), - m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), - m_transformChanged( false ), - m_evaluateTransform( evaluateTransform ), - m_boundsChanged( boundsChanged ){ - construct(); - - m_patchDef3 = other.m_patchDef3; - m_subdivisions_x = other.m_subdivisions_x; - m_subdivisions_y = other.m_subdivisions_y; - setDims( other.m_width, other.m_height ); - copy_ctrl( m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data() + ( m_width * m_height ) ); - SetShader( other.m_shader.c_str() ); - controlPointsChanged(); -} - -Patch( const Patch& other ) : - XMLImporter( other ), - XMLExporter( other ), - TransformNode( other ), - Bounded( other ), - Cullable( other ), - Snappable(), - Undoable( other ), - Filterable( other ), - Nameable( other ), - m_state( 0 ), - m_undoable_observer( 0 ), - m_map( 0 ), - m_render_solid( m_tess ), - m_render_wireframe( m_tess ), - m_render_wireframe_fixed( m_tess ), - m_render_ctrl( GL_POINTS, m_ctrl_vertices ), - m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), - m_transformChanged( false ), - m_evaluateTransform( other.m_evaluateTransform ), - m_boundsChanged( other.m_boundsChanged ){ - m_bOverlay = false; - - m_patchDef3 = other.m_patchDef3; - m_subdivisions_x = other.m_subdivisions_x; - m_subdivisions_y = other.m_subdivisions_y; - setDims( other.m_width, other.m_height ); - copy_ctrl( m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data() + ( m_width * m_height ) ); - SetShader( other.m_shader.c_str() ); - controlPointsChanged(); -} - -~Patch(){ - BezierCurveTreeArray_deleteAll( m_tess.m_curveTreeU ); - BezierCurveTreeArray_deleteAll( m_tess.m_curveTreeV ); - - releaseShader(); - - ASSERT_MESSAGE( m_observers.empty(), "Patch::~Patch: observers still attached" ); -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_state->incrementUsed(); - m_map = path_find_mapfile( path.begin(), path.end() ); - m_undoable_observer = GlobalUndoSystem().observer( this ); - GlobalFilterSystem().registerFilterable( *this ); + Patch( scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : + m_node( &node ), + m_shader( texdef_name_default() ), + m_state( 0 ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_solid( m_tess ), + m_render_wireframe( m_tess ), + m_render_wireframe_fixed( m_tess ), + m_render_ctrl( GL_POINTS, m_ctrl_vertices ), + m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), + m_transformChanged( false ), + m_evaluateTransform( evaluateTransform ), + m_boundsChanged( boundsChanged ){ + construct(); } - else - { - ASSERT_MESSAGE( path_find_mapfile( path.begin(), path.end() ) == m_map, "node is instanced across more than one file" ); - } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_map = 0; - m_undoable_observer = 0; - GlobalUndoSystem().release( this ); - GlobalFilterSystem().unregisterFilterable( *this ); - m_state->decrementUsed(); - } -} + Patch( const Patch& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged ) : + m_node( &node ), + m_shader( texdef_name_default() ), + m_state( 0 ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_solid( m_tess ), + m_render_wireframe( m_tess ), + m_render_wireframe_fixed( m_tess ), + m_render_ctrl( GL_POINTS, m_ctrl_vertices ), + m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), + m_transformChanged( false ), + m_evaluateTransform( evaluateTransform ), + m_boundsChanged( boundsChanged ){ + construct(); -const char* name() const { - return "patch"; -} -void attach( const NameCallback& callback ){ -} -void detach( const NameCallback& callback ){ -} - -void attach( Observer* observer ){ - observer->allocate( m_width * m_height ); - - m_observers.insert( observer ); -} -void detach( Observer* observer ){ - m_observers.erase( observer ); -} - -void updateFiltered(){ - if ( m_node != 0 ) { - if ( patch_filtered( *this ) ) { - m_node->enable( scene::Node::eFiltered ); - } - else - { - m_node->disable( scene::Node::eFiltered ); - } - } -} - -void onAllocate( std::size_t size ){ - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->allocate( size ); - } -} - -const Matrix4& localToParent() const { - return g_matrix4_identity; -} -const AABB& localAABB() const { - const_cast( this )->evaluateTransform(); //experimental! fixing extra sceneChangeNotify call during scene rendering - return m_aabb_local; -} -VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { - return test.TestAABB( m_aabb_local, localToWorld ); -} -void render_solid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( m_state, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_solid, localToWorld ); -} -void render_wireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( m_state, Renderer::eFullMaterials ); - if ( m_patchDef3 ) { - renderer.addRenderable( m_render_wireframe_fixed, localToWorld ); - } - else - { - renderer.addRenderable( m_render_wireframe, localToWorld ); - } -} - -void render_component( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.SetState( m_state_lattice, Renderer::eWireframeOnly ); - renderer.SetState( m_state_lattice, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_lattice, localToWorld ); - - renderer.SetState( m_state_ctrl, Renderer::eWireframeOnly ); - renderer.SetState( m_state_ctrl, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_ctrl, localToWorld ); -} -void testSelect( Selector& selector, SelectionTest& test ){ - SelectionIntersection best; - IndexPointer::index_type* pIndex = m_tess.m_indices.data(); - for ( std::size_t s = 0; s < m_tess.m_numStrips; s++ ) - { - test.TestQuadStrip( vertexpointer_arbitrarymeshvertex( m_tess.m_vertices.data() ), IndexPointer( pIndex, m_tess.m_lenStrips ), best ); - pIndex += m_tess.m_lenStrips; - } - if ( best.valid() ) { - selector.addIntersection( best ); - } -} -void transform( const Matrix4& matrix ){ - for ( PatchControlIter i = m_ctrlTransformed.data(); i != m_ctrlTransformed.data() + m_ctrlTransformed.size(); ++i ) - { - matrix4_transform_point( matrix, ( *i ).m_vertex ); - } - - if ( matrix4_handedness( matrix ) == MATRIX4_LEFTHANDED ) { - PatchControlArray_invert( m_ctrlTransformed, m_width, m_height ); - } - UpdateCachedData(); -} -void transformChanged(){ - m_transformChanged = true; - m_boundsChanged(); //experimental! fixing extra sceneChangeNotify call during scene rendering - m_lightsChanged(); - SceneChangeNotify(); -} -typedef MemberCaller TransformChangedCaller; - -void evaluateTransform(){ - if ( m_transformChanged ) { - //m_transformChanged = false; - revertTransform(); - m_evaluateTransform(); - m_transformChanged = false; //experimental! fixing extra sceneChangeNotify call during scene rendering - } -} - -void revertTransform(){ - m_ctrlTransformed = m_ctrl; -} -void freezeTransform(){ - undoSave(); - evaluateTransform(); - ASSERT_MESSAGE( m_ctrlTransformed.size() == m_ctrl.size(), "Patch::freeze: size mismatch" ); - std::copy( m_ctrlTransformed.begin(), m_ctrlTransformed.end(), m_ctrl.begin() ); -} - -void controlPointsChanged(){ - transformChanged(); - evaluateTransform(); - UpdateCachedData(); -} -bool isValid() const; - -void snapto( float snap ){ - undoSave(); - - for ( PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i ) - { - vector3_snap( ( *i ).m_vertex, snap ); - } - - controlPointsChanged(); -} - - - - -void RenderDebug( RenderStateFlags state ) const; -void RenderNormals( RenderStateFlags state ) const; - -void pushElement( const XMLElement& element ){ - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eDefault: - ASSERT_MESSAGE( string_equal( element.name(), "patch" ), "parse error" ); - m_xml_state.push_back( xml_state_t::ePatch ); - break; - case xml_state_t::ePatch: - if ( string_equal( element.name(), "matrix" ) ) { - setDims( atoi( element.attribute( "width" ) ), atoi( element.attribute( "height" ) ) ); - m_xml_state.push_back( xml_state_t::eMatrix ); - } - else if ( string_equal( element.name(), "shader" ) ) { - m_xml_state.push_back( xml_state_t::eShader ); - } - break; - default: - ERROR_MESSAGE( "parse error" ); - } - -} -void popElement( const char* name ){ - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eDefault: - ERROR_MESSAGE( "parse error" ); - break; - case xml_state_t::ePatch: - break; - case xml_state_t::eMatrix: - { - StringTokeniser content( m_xml_state.back().content() ); - - for ( PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i ) - { - ( *i ).m_vertex[0] = string_read_float( content.getToken() ); - ( *i ).m_vertex[1] = string_read_float( content.getToken() ); - ( *i ).m_vertex[2] = string_read_float( content.getToken() ); - ( *i ).m_texcoord[0] = string_read_float( content.getToken() ); - ( *i ).m_texcoord[1] = string_read_float( content.getToken() ); - } - controlPointsChanged(); - } - break; - case xml_state_t::eShader: - { - SetShader( m_xml_state.back().content() ); - } - break; - default: - ERROR_MESSAGE( "parse error" ); - } - - ASSERT_MESSAGE( !m_xml_state.empty(), "popping empty stack" ); - m_xml_state.pop_back(); -} -std::size_t write( const char* buffer, std::size_t length ){ - switch ( m_xml_state.back().state() ) - { - case xml_state_t::eDefault: - break; - case xml_state_t::ePatch: - break; - case xml_state_t::eMatrix: - case xml_state_t::eShader: - return m_xml_state.back().write( buffer, length ); - break; - default: - ERROR_MESSAGE( "parse error" ); - } - return length; -} - -void exportXML( XMLImporter& importer ){ - StaticElement patchElement( "patch" ); - importer.pushElement( patchElement ); - - { - const StaticElement element( "shader" ); - importer.pushElement( element ); - importer.write( m_shader.c_str(), strlen( m_shader.c_str() ) ); - importer.popElement( element.name() ); - } - - { - char width[16], height[16]; - sprintf( width, "%u", Unsigned( m_width ) ); - sprintf( height, "%u", Unsigned( m_height ) ); - StaticElement element( "matrix" ); - element.insertAttribute( "width", width ); - element.insertAttribute( "height", height ); - - importer.pushElement( element ); - { - for ( PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i ) - { - importer << ( *i ).m_vertex[0] - << ' ' << ( *i ).m_vertex[1] - << ' ' << ( *i ).m_vertex[2] - << ' ' << ( *i ).m_texcoord[0] - << ' ' << ( *i ).m_texcoord[1]; - } - } - importer.popElement( element.name() ); - } - - importer.popElement( patchElement.name() ); -} - -void UpdateCachedData(); - -const char *GetShader() const { - return m_shader.c_str(); -} -void SetShader( const char* name ){ - ASSERT_NOTNULL( name ); - - if ( shader_equal( m_shader.c_str(), name ) ) { - return; - } - - undoSave(); - - if ( m_instanceCounter.m_count != 0 ) { - m_state->decrementUsed(); - } - releaseShader(); - m_shader = name; - captureShader(); - if ( m_instanceCounter.m_count != 0 ) { - m_state->incrementUsed(); - } - - check_shader(); - Patch_textureChanged(); -} -int getShaderFlags() const { - if ( m_state != 0 ) { - return m_state->getFlags(); - } - return 0; -} -const Shader* getShader(){ - ASSERT_MESSAGE( m_state != 0, "patch shader is not realised" ); - return m_state; -} - -typedef PatchControl* iterator; -typedef const PatchControl* const_iterator; - -iterator begin(){ - return m_ctrl.data(); -} -const_iterator begin() const { - return m_ctrl.data(); -} -iterator end(){ - return m_ctrl.data() + m_ctrl.size(); -} -const_iterator end() const { - return m_ctrl.data() + m_ctrl.size(); -} - -PatchControlArray& getControlPoints(){ - return m_ctrl; -} - -// Same as above, just for const arguments -const PatchControlArray& getControlPoints() const { - return m_ctrl; -} - -PatchControlArray& getControlPointsTransformed(){ - return m_ctrlTransformed; -} - -void setDims( std::size_t w, std::size_t h ); -std::size_t getWidth() const { - return m_width; -} -std::size_t getHeight() const { - return m_height; -} -PatchControl& ctrlAt( std::size_t row, std::size_t col ){ - return m_ctrl[row * m_width + col]; -} -const PatchControl& ctrlAt( std::size_t row, std::size_t col ) const { - return m_ctrl[row * m_width + col]; -} - -void ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3 ); -void constructPlane( const AABB& aabb, int axis, std::size_t width, std::size_t height ); -void InvertMatrix(); -void TransposeMatrix(); -void Redisperse( EMatrixMajor mt ); -void Smooth( EMatrixMajor mt ); -void InsertRemove( bool bInsert, bool bColumn, bool bFirst ); -Patch* MakeCap( Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst ); -void ConstructSeam( EPatchCap eType, Vector3* p, std::size_t width ); - -void FlipTexture( int nAxis ); -void TranslateTexture( float s, float t ); -void ScaleTexture( float s, float t ); -void RotateTexture( float angle ); -void SetTextureRepeat( float s, float t ); // call with s=1 t=1 for FIT -void CapTexture(); -void NaturalTexture(); -Vector3 Calculate_AvgNormal() const; -void Calculate_AvgAxes( Vector3& wDir, Vector3& hDir ) const; -void ProjectTexture( TextureProjection projection, const Vector3& normal ); -void ProjectTexture( const texdef_t& texdef, const Vector3* direction ); -void createThickenedOpposite(const Patch& sourcePatch, const float thickness, const int axis, bool& no12, bool& no34 ); -void createThickenedWall(const Patch& sourcePatch, const Patch& targetPatch, const int wallIndex); - -void undoSave(){ - if ( m_map != 0 ) { - m_map->changed(); - } - if ( m_undoable_observer != 0 ) { - m_undoable_observer->save( this ); - } -} - -UndoMemento* exportState() const { - return new SavedState( m_width, m_height, m_ctrl, m_shader.c_str(), m_patchDef3, m_subdivisions_x, m_subdivisions_y ); -} -void importState( const UndoMemento* state ){ - undoSave(); - - const SavedState& other = *( static_cast( state ) ); - - // begin duplicate of SavedState copy constructor, needs refactoring - - // copy construct - { - m_width = other.m_width; - m_height = other.m_height; - SetShader( other.m_shader.c_str() ); - m_ctrl = other.m_ctrl; - onAllocate( m_ctrl.size() ); m_patchDef3 = other.m_patchDef3; m_subdivisions_x = other.m_subdivisions_x; m_subdivisions_y = other.m_subdivisions_y; + setDims( other.m_width, other.m_height ); + copy_ctrl( m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data() + ( m_width * m_height ) ); + SetShader( other.m_shader.c_str() ); + controlPointsChanged(); } - // end duplicate code + Patch( const Patch& other ) : + XMLImporter( other ), + XMLExporter( other ), + TransformNode( other ), + Bounded( other ), + Cullable( other ), + Snappable(), + Undoable( other ), + Filterable( other ), + Nameable( other ), + m_state( 0 ), + m_undoable_observer( 0 ), + m_map( 0 ), + m_render_solid( m_tess ), + m_render_wireframe( m_tess ), + m_render_wireframe_fixed( m_tess ), + m_render_ctrl( GL_POINTS, m_ctrl_vertices ), + m_render_lattice( GL_LINES, m_lattice_indices, m_ctrl_vertices ), + m_transformChanged( false ), + m_evaluateTransform( other.m_evaluateTransform ), + m_boundsChanged( other.m_boundsChanged ){ + m_bOverlay = false; - Patch_textureChanged(); + m_patchDef3 = other.m_patchDef3; + m_subdivisions_x = other.m_subdivisions_x; + m_subdivisions_y = other.m_subdivisions_y; + setDims( other.m_width, other.m_height ); + copy_ctrl( m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data() + ( m_width * m_height ) ); + SetShader( other.m_shader.c_str() ); + controlPointsChanged(); + } - controlPointsChanged(); -} + ~Patch(){ + BezierCurveTreeArray_deleteAll( m_tess.m_curveTreeU ); + BezierCurveTreeArray_deleteAll( m_tess.m_curveTreeV ); -static void constructStatic( EPatchType type ){ - Patch::m_type = type; - Patch::m_state_ctrl = GlobalShaderCache().capture( "$POINT" ); - Patch::m_state_lattice = GlobalShaderCache().capture( "$LATTICE" ); -} + releaseShader(); -static void destroyStatic(){ - GlobalShaderCache().release( "$LATTICE" ); - GlobalShaderCache().release( "$POINT" ); -} + ASSERT_MESSAGE( m_observers.empty(), "Patch::~Patch: observers still attached" ); + } + + InstanceCounter m_instanceCounter; + void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_state->incrementUsed(); + m_map = path_find_mapfile( path.begin(), path.end() ); + m_undoable_observer = GlobalUndoSystem().observer( this ); + GlobalFilterSystem().registerFilterable( *this ); + } + else + { + ASSERT_MESSAGE( path_find_mapfile( path.begin(), path.end() ) == m_map, "node is instanced across more than one file" ); + } + } + void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_map = 0; + m_undoable_observer = 0; + GlobalUndoSystem().release( this ); + GlobalFilterSystem().unregisterFilterable( *this ); + m_state->decrementUsed(); + } + } + + const char* name() const { + return "patch"; + } + void attach( const NameCallback& callback ){ + } + void detach( const NameCallback& callback ){ + } + + void attach( Observer* observer ){ + observer->allocate( m_width * m_height ); + + m_observers.insert( observer ); + } + void detach( Observer* observer ){ + m_observers.erase( observer ); + } + + void updateFiltered(){ + if ( m_node != 0 ) { + if ( patch_filtered( *this ) ) { + m_node->enable( scene::Node::eFiltered ); + } + else + { + m_node->disable( scene::Node::eFiltered ); + } + } + } + + void onAllocate( std::size_t size ){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->allocate( size ); + } + } + + const Matrix4& localToParent() const { + return g_matrix4_identity; + } + const AABB& localAABB() const { + const_cast( this )->evaluateTransform(); //experimental! fixing extra sceneChangeNotify call during scene rendering + return m_aabb_local; + } + VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const { + return test.TestAABB( m_aabb_local, localToWorld ); + } + void render_solid( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( m_state, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_solid, localToWorld ); + } + void render_wireframe( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( m_state, Renderer::eFullMaterials ); + if ( m_patchDef3 ) { + renderer.addRenderable( m_render_wireframe_fixed, localToWorld ); + } + else + { + renderer.addRenderable( m_render_wireframe, localToWorld ); + } + } + + void render_component( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { + renderer.SetState( m_state_lattice, Renderer::eWireframeOnly ); + renderer.SetState( m_state_lattice, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_lattice, localToWorld ); + + renderer.SetState( m_state_ctrl, Renderer::eWireframeOnly ); + renderer.SetState( m_state_ctrl, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_ctrl, localToWorld ); + } + void testSelect( Selector& selector, SelectionTest& test ){ + SelectionIntersection best; + IndexPointer::index_type* pIndex = m_tess.m_indices.data(); + for ( std::size_t s = 0; s < m_tess.m_numStrips; s++ ) + { + test.TestQuadStrip( vertexpointer_arbitrarymeshvertex( m_tess.m_vertices.data() ), IndexPointer( pIndex, m_tess.m_lenStrips ), best ); + pIndex += m_tess.m_lenStrips; + } + if ( best.valid() ) { + selector.addIntersection( best ); + } + } + void transform( const Matrix4& matrix ){ + for ( PatchControlIter i = m_ctrlTransformed.data(); i != m_ctrlTransformed.data() + m_ctrlTransformed.size(); ++i ) + { + matrix4_transform_point( matrix, ( *i ).m_vertex ); + } + + if ( matrix4_handedness( matrix ) == MATRIX4_LEFTHANDED ) { + PatchControlArray_invert( m_ctrlTransformed, m_width, m_height ); + } + UpdateCachedData(); + } + void transformChanged(){ + m_transformChanged = true; + m_boundsChanged(); //experimental! fixing extra sceneChangeNotify call during scene rendering + m_lightsChanged(); + SceneChangeNotify(); + } + typedef MemberCaller TransformChangedCaller; + + void evaluateTransform(){ + if ( m_transformChanged ) { + //m_transformChanged = false; + revertTransform(); + m_evaluateTransform(); + m_transformChanged = false; //experimental! fixing extra sceneChangeNotify call during scene rendering + } + } + + void revertTransform(){ + m_ctrlTransformed = m_ctrl; + } + void freezeTransform(){ + undoSave(); + evaluateTransform(); + ASSERT_MESSAGE( m_ctrlTransformed.size() == m_ctrl.size(), "Patch::freeze: size mismatch" ); + std::copy( m_ctrlTransformed.begin(), m_ctrlTransformed.end(), m_ctrl.begin() ); + } + + void controlPointsChanged(){ + transformChanged(); + evaluateTransform(); + UpdateCachedData(); + } + bool isValid() const; + + void snapto( float snap ){ + undoSave(); + + for ( PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i ) + { + vector3_snap( ( *i ).m_vertex, snap ); + } + + controlPointsChanged(); + } + + + + + void RenderDebug( RenderStateFlags state ) const; + void RenderNormals( RenderStateFlags state ) const; + + void pushElement( const XMLElement& element ){ + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eDefault: + ASSERT_MESSAGE( string_equal( element.name(), "patch" ), "parse error" ); + m_xml_state.push_back( xml_state_t::ePatch ); + break; + case xml_state_t::ePatch: + if ( string_equal( element.name(), "matrix" ) ) { + setDims( atoi( element.attribute( "width" ) ), atoi( element.attribute( "height" ) ) ); + m_xml_state.push_back( xml_state_t::eMatrix ); + } + else if ( string_equal( element.name(), "shader" ) ) { + m_xml_state.push_back( xml_state_t::eShader ); + } + break; + default: + ERROR_MESSAGE( "parse error" ); + } + + } + void popElement( const char* name ){ + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eDefault: + ERROR_MESSAGE( "parse error" ); + break; + case xml_state_t::ePatch: + break; + case xml_state_t::eMatrix: + { + StringTokeniser content( m_xml_state.back().content() ); + + for ( PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i ) + { + ( *i ).m_vertex[0] = string_read_float( content.getToken() ); + ( *i ).m_vertex[1] = string_read_float( content.getToken() ); + ( *i ).m_vertex[2] = string_read_float( content.getToken() ); + ( *i ).m_texcoord[0] = string_read_float( content.getToken() ); + ( *i ).m_texcoord[1] = string_read_float( content.getToken() ); + } + controlPointsChanged(); + } + break; + case xml_state_t::eShader: + { + SetShader( m_xml_state.back().content() ); + } + break; + default: + ERROR_MESSAGE( "parse error" ); + } + + ASSERT_MESSAGE( !m_xml_state.empty(), "popping empty stack" ); + m_xml_state.pop_back(); + } + std::size_t write( const char* buffer, std::size_t length ){ + switch ( m_xml_state.back().state() ) + { + case xml_state_t::eDefault: + break; + case xml_state_t::ePatch: + break; + case xml_state_t::eMatrix: + case xml_state_t::eShader: + return m_xml_state.back().write( buffer, length ); + break; + default: + ERROR_MESSAGE( "parse error" ); + } + return length; + } + + void exportXML( XMLImporter& importer ){ + StaticElement patchElement( "patch" ); + importer.pushElement( patchElement ); + + { + const StaticElement element( "shader" ); + importer.pushElement( element ); + importer.write( m_shader.c_str(), strlen( m_shader.c_str() ) ); + importer.popElement( element.name() ); + } + + { + char width[16], height[16]; + sprintf( width, "%u", Unsigned( m_width ) ); + sprintf( height, "%u", Unsigned( m_height ) ); + StaticElement element( "matrix" ); + element.insertAttribute( "width", width ); + element.insertAttribute( "height", height ); + + importer.pushElement( element ); + { + for ( PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i ) + { + importer << ( *i ).m_vertex[0] + << ' ' << ( *i ).m_vertex[1] + << ' ' << ( *i ).m_vertex[2] + << ' ' << ( *i ).m_texcoord[0] + << ' ' << ( *i ).m_texcoord[1]; + } + } + importer.popElement( element.name() ); + } + + importer.popElement( patchElement.name() ); + } + + void UpdateCachedData(); + + const char *GetShader() const { + return m_shader.c_str(); + } + void SetShader( const char* name ){ + ASSERT_NOTNULL( name ); + + if ( shader_equal( m_shader.c_str(), name ) ) { + return; + } + + undoSave(); + + if ( m_instanceCounter.m_count != 0 ) { + m_state->decrementUsed(); + } + releaseShader(); + m_shader = name; + captureShader(); + if ( m_instanceCounter.m_count != 0 ) { + m_state->incrementUsed(); + } + + check_shader(); + Patch_textureChanged(); + } + int getShaderFlags() const { + if ( m_state != 0 ) { + return m_state->getFlags(); + } + return 0; + } + const Shader* getShader(){ + ASSERT_MESSAGE( m_state != 0, "patch shader is not realised" ); + return m_state; + } + + typedef PatchControl* iterator; + typedef const PatchControl* const_iterator; + + iterator begin(){ + return m_ctrl.data(); + } + const_iterator begin() const { + return m_ctrl.data(); + } + iterator end(){ + return m_ctrl.data() + m_ctrl.size(); + } + const_iterator end() const { + return m_ctrl.data() + m_ctrl.size(); + } + + PatchControlArray& getControlPoints(){ + return m_ctrl; + } + +// Same as above, just for const arguments + const PatchControlArray& getControlPoints() const { + return m_ctrl; + } + + PatchControlArray& getControlPointsTransformed(){ + return m_ctrlTransformed; + } + + void setDims( std::size_t w, std::size_t h ); + std::size_t getWidth() const { + return m_width; + } + std::size_t getHeight() const { + return m_height; + } + PatchControl& ctrlAt( std::size_t row, std::size_t col ){ + return m_ctrl[row * m_width + col]; + } + const PatchControl& ctrlAt( std::size_t row, std::size_t col ) const { + return m_ctrl[row * m_width + col]; + } + + void ConstructPrefab( const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3 ); + void constructPlane( const AABB& aabb, int axis, std::size_t width, std::size_t height ); + void InvertMatrix(); + void TransposeMatrix(); + void Redisperse( EMatrixMajor mt ); + void Smooth( EMatrixMajor mt ); + void InsertRemove( bool bInsert, bool bColumn, bool bFirst ); + Patch* MakeCap( Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst ); + void ConstructSeam( EPatchCap eType, Vector3* p, std::size_t width ); + + void FlipTexture( int nAxis ); + void TranslateTexture( float s, float t ); + void ScaleTexture( float s, float t ); + void RotateTexture( float angle ); + void SetTextureRepeat( float s, float t ); // call with s=1 t=1 for FIT + void CapTexture(); + void NaturalTexture(); + Vector3 Calculate_AvgNormal() const; + void Calculate_AvgAxes( Vector3& wDir, Vector3& hDir ) const; + void ProjectTexture( TextureProjection projection, const Vector3& normal ); + void ProjectTexture( const texdef_t& texdef, const Vector3* direction ); + void createThickenedOpposite(const Patch& sourcePatch, const float thickness, const int axis, bool& no12, bool& no34 ); + void createThickenedWall(const Patch& sourcePatch, const Patch& targetPatch, const int wallIndex); + + void undoSave(){ + if ( m_map != 0 ) { + m_map->changed(); + } + if ( m_undoable_observer != 0 ) { + m_undoable_observer->save( this ); + } + } + + UndoMemento* exportState() const { + return new SavedState( m_width, m_height, m_ctrl, m_shader.c_str(), m_patchDef3, m_subdivisions_x, m_subdivisions_y ); + } + void importState( const UndoMemento* state ){ + undoSave(); + + const SavedState& other = *( static_cast( state ) ); + + // begin duplicate of SavedState copy constructor, needs refactoring + + // copy construct + { + m_width = other.m_width; + m_height = other.m_height; + SetShader( other.m_shader.c_str() ); + m_ctrl = other.m_ctrl; + onAllocate( m_ctrl.size() ); + m_patchDef3 = other.m_patchDef3; + m_subdivisions_x = other.m_subdivisions_x; + m_subdivisions_y = other.m_subdivisions_y; + } + + // end duplicate code + + Patch_textureChanged(); + + controlPointsChanged(); + } + + static void constructStatic( EPatchType type ){ + Patch::m_type = type; + Patch::m_state_ctrl = GlobalShaderCache().capture( "$POINT" ); + Patch::m_state_lattice = GlobalShaderCache().capture( "$LATTICE" ); + } + + static void destroyStatic(){ + GlobalShaderCache().release( "$LATTICE" ); + GlobalShaderCache().release( "$POINT" ); + } private: -void captureShader(){ - m_state = GlobalShaderCache().capture( m_shader.c_str() ); -} - -void releaseShader(){ - GlobalShaderCache().release( m_shader.c_str() ); -} - -void check_shader(){ - if ( !texdef_name_valid( GetShader() ) ) { - globalErrorStream() << "patch has invalid texture name: '" << GetShader() << "'\n"; + void captureShader(){ + m_state = GlobalShaderCache().capture( m_shader.c_str() ); } -} -void InsertPoints( EMatrixMajor mt, bool bFirst ); -void RemovePoints( EMatrixMajor mt, bool bFirst ); + void releaseShader(){ + GlobalShaderCache().release( m_shader.c_str() ); + } -void AccumulateBBox(); + void check_shader(){ + if ( !texdef_name_valid( GetShader() ) ) { + globalErrorStream() << "patch has invalid texture name: '" << GetShader() << "'\n"; + } + } -void TesselateSubMatrixFixed( ArbitraryMeshVertex * vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl * subMatrix[3][3] ); + void InsertPoints( EMatrixMajor mt, bool bFirst ); + void RemovePoints( EMatrixMajor mt, bool bFirst ); + + void AccumulateBBox(); + + void TesselateSubMatrixFixed( ArbitraryMeshVertex * vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl * subMatrix[3][3] ); // uses binary trees representing bezier curves to recursively tesselate a bezier sub-patch -void TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, - std::size_t offStartX, std::size_t offStartY, - std::size_t offEndX, std::size_t offEndY, - std::size_t nFlagsX, std::size_t nFlagsY, - Vector3& left, Vector3& mid, Vector3& right, - Vector2& texLeft, Vector2& texMid, Vector2& texRight, - bool bTranspose ); + void TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, + std::size_t offStartX, std::size_t offStartY, + std::size_t offEndX, std::size_t offEndY, + std::size_t nFlagsX, std::size_t nFlagsY, + Vector3& left, Vector3& mid, Vector3& right, + Vector2& texLeft, Vector2& texMid, Vector2& texRight, + bool bTranspose ); // tesselates the entire surface -void BuildTesselationCurves( EMatrixMajor major ); -void accumulateVertexTangentSpace( std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1 ); -void BuildVertexArray(); + void BuildTesselationCurves( EMatrixMajor major ); + void accumulateVertexTangentSpace( std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1 ); + void BuildVertexArray(); }; inline bool Patch_importHeader( Patch& patch, Tokeniser& tokeniser ){ @@ -1133,36 +1133,36 @@ inline bool Patch_importFooter( Patch& patch, Tokeniser& tokeniser ){ class PatchTokenImporter : public MapImporter { -Patch& m_patch; + Patch& m_patch; public: -PatchTokenImporter( Patch& patch ) : m_patch( patch ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( Patch_importHeader( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importShader( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importParams( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importMatrix( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importFooter( m_patch, tokeniser ) ); + PatchTokenImporter( Patch& patch ) : m_patch( patch ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( Patch_importHeader( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importShader( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importParams( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importMatrix( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importFooter( m_patch, tokeniser ) ); - return true; -} + return true; + } }; class PatchDoom3TokenImporter : public MapImporter { -Patch& m_patch; + Patch& m_patch; public: -PatchDoom3TokenImporter( Patch& patch ) : m_patch( patch ){ -} -bool importTokens( Tokeniser& tokeniser ){ - RETURN_FALSE_IF_FAIL( Patch_importHeader( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( PatchDoom3_importShader( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importParams( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importMatrix( m_patch, tokeniser ) ); - RETURN_FALSE_IF_FAIL( Patch_importFooter( m_patch, tokeniser ) ); + PatchDoom3TokenImporter( Patch& patch ) : m_patch( patch ){ + } + bool importTokens( Tokeniser& tokeniser ){ + RETURN_FALSE_IF_FAIL( Patch_importHeader( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( PatchDoom3_importShader( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importParams( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importMatrix( m_patch, tokeniser ) ); + RETURN_FALSE_IF_FAIL( Patch_importFooter( m_patch, tokeniser ) ); - return true; -} + return true; + } }; inline void Patch_exportHeader( const Patch& patch, TokenWriter& writer ){ @@ -1249,54 +1249,54 @@ inline void Patch_exportFooter( const Patch& patch, TokenWriter& writer ){ class PatchTokenExporter : public MapExporter { -const Patch& m_patch; + const Patch& m_patch; public: -PatchTokenExporter( Patch& patch ) : m_patch( patch ){ -} -void exportTokens( TokenWriter& writer ) const { - Patch_exportHeader( m_patch, writer ); - Patch_exportShader( m_patch, writer ); - Patch_exportParams( m_patch, writer ); - Patch_exportMatrix( m_patch, writer ); - Patch_exportFooter( m_patch, writer ); -} + PatchTokenExporter( Patch& patch ) : m_patch( patch ){ + } + void exportTokens( TokenWriter& writer ) const { + Patch_exportHeader( m_patch, writer ); + Patch_exportShader( m_patch, writer ); + Patch_exportParams( m_patch, writer ); + Patch_exportMatrix( m_patch, writer ); + Patch_exportFooter( m_patch, writer ); + } }; class PatchDoom3TokenExporter : public MapExporter { -const Patch& m_patch; + const Patch& m_patch; public: -PatchDoom3TokenExporter( Patch& patch ) : m_patch( patch ){ -} -void exportTokens( TokenWriter& writer ) const { - Patch_exportHeader( m_patch, writer ); - PatchDoom3_exportShader( m_patch, writer ); - Patch_exportParams( m_patch, writer ); - Patch_exportMatrix( m_patch, writer ); - Patch_exportFooter( m_patch, writer ); -} + PatchDoom3TokenExporter( Patch& patch ) : m_patch( patch ){ + } + void exportTokens( TokenWriter& writer ) const { + Patch_exportHeader( m_patch, writer ); + PatchDoom3_exportShader( m_patch, writer ); + Patch_exportParams( m_patch, writer ); + Patch_exportMatrix( m_patch, writer ); + Patch_exportFooter( m_patch, writer ); + } }; class PatchControlInstance { public: -PatchControl* m_ctrl; -ObservedSelectable m_selectable; + PatchControl* m_ctrl; + ObservedSelectable m_selectable; -PatchControlInstance( PatchControl* ctrl, const SelectionChangeCallback& observer ) - : m_ctrl( ctrl ), m_selectable( observer ){ -} - -void testSelect( Selector& selector, SelectionTest& test ){ - SelectionIntersection best; - test.TestPoint( m_ctrl->m_vertex, best ); - if ( best.valid() ) { - Selector_add( selector, m_selectable, best ); + PatchControlInstance( PatchControl* ctrl, const SelectionChangeCallback& observer ) + : m_ctrl( ctrl ), m_selectable( observer ){ + } + + void testSelect( Selector& selector, SelectionTest& test ){ + SelectionIntersection best; + test.TestPoint( m_ctrl->m_vertex, best ); + if ( best.valid() ) { + Selector_add( selector, m_selectable, best ); + } + } + void snapto( float snap ){ + vector3_snap( m_ctrl->m_vertex, snap ); } -} -void snapto( float snap ){ - vector3_snap( m_ctrl->m_vertex, snap ); -} }; @@ -1312,394 +1312,394 @@ class PatchInstance : public PlaneSelectable, public LightCullable { -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceStaticCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceStaticCast::install( m_casts ); - InstanceIdentityCast::install( m_casts ); - InstanceContainedCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - - -Patch& m_patch; -typedef std::vector PatchControlInstances; -PatchControlInstances m_ctrl_instances; - -ObservedSelectable m_selectable; - -DragPlanes m_dragPlanes; - -mutable RenderablePointVector m_render_selected; -mutable AABB m_aabb_component; - -static Shader* m_state_selpoint; - -const LightList* m_lightList; - -TransformModifier m_transform; -public: -static Counter* m_counter; - -typedef LazyStatic StaticTypeCasts; - -void lightsChanged(){ - m_lightList->lightsChanged(); -} -typedef MemberCaller LightsChangedCaller; - -STRING_CONSTANT( Name, "PatchInstance" ); - -PatchInstance( const scene::Path& path, scene::Instance* parent, Patch& patch ) : - Instance( path, parent, this, StaticTypeCasts::instance().get() ), - m_patch( patch ), - m_selectable( SelectedChangedCaller( *this ) ), - m_dragPlanes( SelectedChangedComponentCaller( *this ) ), - m_render_selected( GL_POINTS ), - m_transform( Patch::TransformChangedCaller( m_patch ), ApplyTransformCaller( *this ) ){ - m_patch.instanceAttach( Instance::path() ); - m_patch.attach( this ); - m_counter->increment(); - - m_lightList = &GlobalShaderCache().attach( *this ); - m_patch.m_lightsChanged = LightsChangedCaller( *this ); - - Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); -} -~PatchInstance(){ - Instance::setTransformChangedCallback( Callback() ); - - m_patch.m_lightsChanged = Callback(); - GlobalShaderCache().detach( *this ); - - m_counter->decrement(); - m_patch.detach( this ); - m_patch.instanceDetach( Instance::path() ); -} - -void selectedChanged( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); - GlobalSelectionSystem().onSelectedChanged( *this, selectable ); - - Instance::selectedChanged(); -} -typedef MemberCaller1 SelectedChangedCaller; - -void selectedChangedComponent( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); - GlobalSelectionSystem().onComponentSelection( *this, selectable ); -} -typedef MemberCaller1 SelectedChangedComponentCaller; - -Patch& getPatch(){ - return m_patch; -} -Bounded& get( NullType){ - return m_patch; -} -Cullable& get( NullType){ - return m_patch; -} -Transformable& get( NullType){ - return m_transform; -} - -static void constructStatic(){ - m_state_selpoint = GlobalShaderCache().capture( "$SELPOINT" ); -} - -static void destroyStatic(){ - GlobalShaderCache().release( "$SELPOINT" ); -} - - -void allocate( std::size_t size ){ - m_ctrl_instances.clear(); - m_ctrl_instances.reserve( size ); - for ( Patch::iterator i = m_patch.begin(); i != m_patch.end(); ++i ) + class TypeCasts { - m_ctrl_instances.push_back( PatchControlInstance( &( *i ), SelectedChangedComponentCaller( *this ) ) ); + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + InstanceStaticCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceStaticCast::install( m_casts ); + InstanceIdentityCast::install( m_casts ); + InstanceContainedCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; + + + Patch& m_patch; + typedef std::vector PatchControlInstances; + PatchControlInstances m_ctrl_instances; + + ObservedSelectable m_selectable; + + DragPlanes m_dragPlanes; + + mutable RenderablePointVector m_render_selected; + mutable AABB m_aabb_component; + + static Shader* m_state_selpoint; + + const LightList* m_lightList; + + TransformModifier m_transform; +public: + static Counter* m_counter; + + typedef LazyStatic StaticTypeCasts; + + void lightsChanged(){ + m_lightList->lightsChanged(); } -} + typedef MemberCaller LightsChangedCaller; -void setSelected( bool select ){ - m_selectable.setSelected( select ); - if ( !select && parent() ){ - Selectable* sel_parent = Instance_getSelectable( *parent() ); - if ( sel_parent && sel_parent->isSelected() ) - sel_parent->setSelected( false ); + STRING_CONSTANT( Name, "PatchInstance" ); + + PatchInstance( const scene::Path& path, scene::Instance* parent, Patch& patch ) : + Instance( path, parent, this, StaticTypeCasts::instance().get() ), + m_patch( patch ), + m_selectable( SelectedChangedCaller( *this ) ), + m_dragPlanes( SelectedChangedComponentCaller( *this ) ), + m_render_selected( GL_POINTS ), + m_transform( Patch::TransformChangedCaller( m_patch ), ApplyTransformCaller( *this ) ){ + m_patch.instanceAttach( Instance::path() ); + m_patch.attach( this ); + m_counter->increment(); + + m_lightList = &GlobalShaderCache().attach( *this ); + m_patch.m_lightsChanged = LightsChangedCaller( *this ); + + Instance::setTransformChangedCallback( LightsChangedCaller( *this ) ); + } + ~PatchInstance(){ + Instance::setTransformChangedCallback( Callback() ); + + m_patch.m_lightsChanged = Callback(); + GlobalShaderCache().detach( *this ); + + m_counter->decrement(); + m_patch.detach( this ); + m_patch.instanceDetach( Instance::path() ); + } + + void selectedChanged( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); + GlobalSelectionSystem().onSelectedChanged( *this, selectable ); + + Instance::selectedChanged(); + } + typedef MemberCaller1 SelectedChangedCaller; + + void selectedChangedComponent( const Selectable& selectable ){ + GlobalSelectionSystem().getObserver ( SelectionSystem::eComponent )( selectable ); + GlobalSelectionSystem().onComponentSelection( *this, selectable ); + } + typedef MemberCaller1 SelectedChangedComponentCaller; + + Patch& getPatch(){ + return m_patch; + } + Bounded& get( NullType){ + return m_patch; + } + Cullable& get( NullType){ + return m_patch; + } + Transformable& get( NullType){ + return m_transform; + } + + static void constructStatic(){ + m_state_selpoint = GlobalShaderCache().capture( "$SELPOINT" ); + } + + static void destroyStatic(){ + GlobalShaderCache().release( "$SELPOINT" ); } -} -bool isSelected() const { - return m_selectable.isSelected(); -} -void update_selected() const { - m_render_selected.clear(); - Patch::iterator ctrl = m_patch.getControlPointsTransformed().begin(); - for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl ) - { - if ( ( *i ).m_selectable.isSelected() ) { - const Colour4b colour_selected( 0, 0, 255, 255 ); - m_render_selected.push_back( PointVertex( reinterpret_cast( ( *ctrl ).m_vertex ), colour_selected ) ); + void allocate( std::size_t size ){ + m_ctrl_instances.clear(); + m_ctrl_instances.reserve( size ); + for ( Patch::iterator i = m_patch.begin(); i != m_patch.end(); ++i ) + { + m_ctrl_instances.push_back( PatchControlInstance( &( *i ), SelectedChangedComponentCaller( *this ) ) ); + } + } + + void setSelected( bool select ){ + m_selectable.setSelected( select ); + if ( !select && parent() ){ + Selectable* sel_parent = Instance_getSelectable( *parent() ); + if ( sel_parent && sel_parent->isSelected() ) + sel_parent->setSelected( false ); + } + } + bool isSelected() const { + return m_selectable.isSelected(); + } + + + void update_selected() const { + m_render_selected.clear(); + Patch::iterator ctrl = m_patch.getControlPointsTransformed().begin(); + for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl ) + { + if ( ( *i ).m_selectable.isSelected() ) { + const Colour4b colour_selected( 0, 0, 255, 255 ); + m_render_selected.push_back( PointVertex( reinterpret_cast( ( *ctrl ).m_vertex ), colour_selected ) ); + } } } -} #if 0 -void render( Renderer& renderer, const VolumeTest& volume ) const { - if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && m_selectable.isSelected() ) { - renderer.Highlight( Renderer::eFace, false ); + void render( Renderer& renderer, const VolumeTest& volume ) const { + if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && m_selectable.isSelected() ) { + renderer.Highlight( Renderer::eFace, false ); - m_patch.render( renderer, volume, localToWorld() ); + m_patch.render( renderer, volume, localToWorld() ); - if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { - renderer.Highlight( Renderer::ePrimitive, false ); + if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { + renderer.Highlight( Renderer::ePrimitive, false ); - m_patch.render_component( renderer, volume, localToWorld() ); + m_patch.render_component( renderer, volume, localToWorld() ); - renderComponentsSelected( renderer, volume ); + renderComponentsSelected( renderer, volume ); + } + } + else{ + m_patch.render( renderer, volume, localToWorld() ); } } - else{ - m_patch.render( renderer, volume, localToWorld() ); - } -} #endif -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - m_patch.evaluateTransform(); - renderer.setLights( *m_lightList ); - renderer.Highlight( Renderer::ePrimitiveWire ); - m_patch.render_solid( renderer, volume, localToWorld() ); + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + m_patch.evaluateTransform(); + renderer.setLights( *m_lightList ); + renderer.Highlight( Renderer::ePrimitiveWire ); + m_patch.render_solid( renderer, volume, localToWorld() ); - renderComponentsSelected( renderer, volume ); -} - -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - m_patch.evaluateTransform(); - m_patch.render_wireframe( renderer, volume, localToWorld() ); - - renderComponentsSelected( renderer, volume ); -} - -void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume ) const { - m_patch.evaluateTransform(); - update_selected(); - if ( !m_render_selected.empty() ) { - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.SetState( m_state_selpoint, Renderer::eWireframeOnly ); - renderer.SetState( m_state_selpoint, Renderer::eFullMaterials ); - renderer.addRenderable( m_render_selected, localToWorld() ); + renderComponentsSelected( renderer, volume ); } -} -void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { - m_patch.evaluateTransform(); - if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { - m_patch.render_component( renderer, volume, localToWorld() ); - } -} -void testSelect( Selector& selector, SelectionTest& test ){ - test.BeginMesh( localToWorld(), true ); - m_patch.testSelect( selector, test ); -} + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + m_patch.evaluateTransform(); + m_patch.render_wireframe( renderer, volume, localToWorld() ); -void selectCtrl( bool select ){ - for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - ( *i ).m_selectable.setSelected( select ); + renderComponentsSelected( renderer, volume ); } -} -bool isSelectedComponents() const { - for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - if ( ( *i ).m_selectable.isSelected() ) { - return true; + + void renderComponentsSelected( Renderer& renderer, const VolumeTest& volume ) const { + m_patch.evaluateTransform(); + update_selected(); + if ( !m_render_selected.empty() ) { + renderer.Highlight( Renderer::ePrimitive, false ); + renderer.SetState( m_state_selpoint, Renderer::eWireframeOnly ); + renderer.SetState( m_state_selpoint, Renderer::eFullMaterials ); + renderer.addRenderable( m_render_selected, localToWorld() ); } } - return false; -} -void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ - if ( mode == SelectionSystem::eVertex ) { - selectCtrl( select ); + void renderComponents( Renderer& renderer, const VolumeTest& volume ) const { + m_patch.evaluateTransform(); + if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ) { + m_patch.render_component( renderer, volume, localToWorld() ); + } } - else if ( mode == SelectionSystem::eFace ) { - m_dragPlanes.setSelected( select ); - } -} -void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ - test.BeginMesh( localToWorld() ); - switch ( mode ) - { - case SelectionSystem::eVertex: - { + void testSelect( Selector& selector, SelectionTest& test ){ + test.BeginMesh( localToWorld(), true ); + m_patch.testSelect( selector, test ); + } + + void selectCtrl( bool select ){ for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) { - ( *i ).testSelect( selector, test ); + ( *i ).m_selectable.setSelected( select ); } } - break; - default: - break; - } -} -void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { - test.BeginMesh( localToWorld() ); - - switch ( mode ) - { - case SelectionSystem::eVertex: - { - for ( const PatchControlInstance& pci : m_ctrl_instances ) - { - SelectionIntersection best; - test.TestPoint( pci.m_ctrl->m_vertex, best ); - if ( SelectionIntersection_closer( best, intersection ) ) { - intersection = best; - polygons.clear(); - polygons.emplace_back( std::initializer_list( { pci.m_ctrl->m_vertex } ) ); - } - } - } - break; - default: - break; - } -} - -const AABB& getSelectedComponentsBounds() const { - m_aabb_component = AABB(); - - for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - if ( ( *i ).m_selectable.isSelected() ) { - aabb_extend_by_point_safe( m_aabb_component, ( *i ).m_ctrl->m_vertex ); - } - } - - return m_aabb_component; -} -void gatherSelectedComponents( const Vector3Callback& callback ) const { - for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - if ( ( *i ).m_selectable.isSelected() ) { - callback( ( *i ).m_ctrl->m_vertex ); - } - } -} - -bool selectedVertices() const { - for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - if ( ( *i ).m_selectable.isSelected() ) { - return true; - } - } - return false; -} - -void transformComponents( const Matrix4& matrix ){ - if ( selectedVertices() ) { - PatchControlIter ctrl = m_patch.getControlPointsTransformed().begin(); - for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl ) + bool isSelectedComponents() const { + for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) { if ( ( *i ).m_selectable.isSelected() ) { - matrix4_transform_point( matrix, ( *ctrl ).m_vertex ); + return true; } } - m_patch.UpdateCachedData(); + return false; + } + void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ){ + if ( mode == SelectionSystem::eVertex ) { + selectCtrl( select ); + } + else if ( mode == SelectionSystem::eFace ) { + m_dragPlanes.setSelected( select ); + } + } + void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ){ + test.BeginMesh( localToWorld() ); + + switch ( mode ) + { + case SelectionSystem::eVertex: + { + for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) + { + ( *i ).testSelect( selector, test ); + } + } + break; + default: + break; + } + } + void gatherComponentsHighlight( std::vector>& polygons, SelectionIntersection& intersection, SelectionTest& test, SelectionSystem::EComponentMode mode ) const { + test.BeginMesh( localToWorld() ); + + switch ( mode ) + { + case SelectionSystem::eVertex: + { + for ( const PatchControlInstance& pci : m_ctrl_instances ) + { + SelectionIntersection best; + test.TestPoint( pci.m_ctrl->m_vertex, best ); + if ( SelectionIntersection_closer( best, intersection ) ) { + intersection = best; + polygons.clear(); + polygons.emplace_back( std::initializer_list( { pci.m_ctrl->m_vertex } ) ); + } + } + } + break; + default: + break; + } } - if ( m_dragPlanes.isSelected() ) { // this should only be true when the transform is a pure translation. - m_patch.transform( m_dragPlanes.evaluateTransform( vector4_to_vector3( matrix.t() ) ) ); + const AABB& getSelectedComponentsBounds() const { + m_aabb_component = AABB(); + + for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) + { + if ( ( *i ).m_selectable.isSelected() ) { + aabb_extend_by_point_safe( m_aabb_component, ( *i ).m_ctrl->m_vertex ); + } + } + + return m_aabb_component; } -} - -void invertComponentSelection(){ - for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) - { - ( *i ).m_selectable.setSelected( !( *i ).m_selectable.isSelected() ); + void gatherSelectedComponents( const Vector3Callback& callback ) const { + for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) + { + if ( ( *i ).m_selectable.isSelected() ) { + callback( ( *i ).m_ctrl->m_vertex ); + } + } } -} + bool selectedVertices() const { + for ( PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) + { + if ( ( *i ).m_selectable.isSelected() ) { + return true; + } + } + return false; + } -void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ - test.BeginMesh( localToWorld() ); + void transformComponents( const Matrix4& matrix ){ + if ( selectedVertices() ) { + PatchControlIter ctrl = m_patch.getControlPointsTransformed().begin(); + for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl ) + { + if ( ( *i ).m_selectable.isSelected() ) { + matrix4_transform_point( matrix, ( *ctrl ).m_vertex ); + } + } + m_patch.UpdateCachedData(); + } - m_dragPlanes.selectPlanes( m_patch.localAABB(), selector, test, selectedPlaneCallback ); -} -void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ - m_dragPlanes.selectReversedPlanes( m_patch.localAABB(), selector, selectedPlanes ); -} + if ( m_dragPlanes.isSelected() ) { // this should only be true when the transform is a pure translation. + m_patch.transform( m_dragPlanes.evaluateTransform( vector4_to_vector3( matrix.t() ) ) ); + } + } -void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { - test.BeginMesh( localToWorld() ); - m_dragPlanes.bestPlaneDirect( m_patch.localAABB(), test, plane, intersection ); -} -void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { - test.BeginMesh( localToWorld() ); - m_dragPlanes.bestPlaneIndirect( m_patch.localAABB(), test, plane, intersection, dist ); -} -void selectByPlane( const Plane3& plane ){ - m_dragPlanes.selectByPlane( m_patch.localAABB(), plane ); -} -void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { - m_dragPlanes.gatherPolygonsByPlane( m_patch.localAABB(), plane, polygons ); -} - - -void snapComponents( float snap ){ - if ( selectedVertices() ) { - m_patch.undoSave(); + void invertComponentSelection(){ for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) { - if ( ( *i ).m_selectable.isSelected() ) { - ( *i ).snapto( snap ); - } + ( *i ).m_selectable.setSelected( !( *i ).m_selectable.isSelected() ); } - m_patch.controlPointsChanged(); } -} -void evaluateTransform(){ - Matrix4 matrix( m_transform.calculateTransform() ); - if ( m_transform.getType() == TRANSFORM_PRIMITIVE ) { - m_patch.transform( matrix ); + void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ + test.BeginMesh( localToWorld() ); + + m_dragPlanes.selectPlanes( m_patch.localAABB(), selector, test, selectedPlaneCallback ); } - else - { - transformComponents( matrix ); + void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ){ + m_dragPlanes.selectReversedPlanes( m_patch.localAABB(), selector, selectedPlanes ); + } + + void bestPlaneDirect( SelectionTest& test, Plane3& plane, SelectionIntersection& intersection ) const { + test.BeginMesh( localToWorld() ); + m_dragPlanes.bestPlaneDirect( m_patch.localAABB(), test, plane, intersection ); + } + void bestPlaneIndirect( SelectionTest& test, Plane3& plane, Vector3& intersection, float& dist ) const { + test.BeginMesh( localToWorld() ); + m_dragPlanes.bestPlaneIndirect( m_patch.localAABB(), test, plane, intersection, dist ); + } + void selectByPlane( const Plane3& plane ){ + m_dragPlanes.selectByPlane( m_patch.localAABB(), plane ); + } + void gatherPolygonsByPlane( const Plane3& plane, std::vector>& polygons ) const { + m_dragPlanes.gatherPolygonsByPlane( m_patch.localAABB(), plane, polygons ); } -} -void applyTransform(){ - m_patch.revertTransform(); - evaluateTransform(); - m_patch.freezeTransform(); -} -typedef MemberCaller ApplyTransformCaller; -bool testLight( const RendererLight& light ) const { - return light.testAABB( worldAABB() ); -} + void snapComponents( float snap ){ + if ( selectedVertices() ) { + m_patch.undoSave(); + for ( PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i ) + { + if ( ( *i ).m_selectable.isSelected() ) { + ( *i ).snapto( snap ); + } + } + m_patch.controlPointsChanged(); + } + } + + void evaluateTransform(){ + Matrix4 matrix( m_transform.calculateTransform() ); + + if ( m_transform.getType() == TRANSFORM_PRIMITIVE ) { + m_patch.transform( matrix ); + } + else + { + transformComponents( matrix ); + } + } + void applyTransform(){ + m_patch.revertTransform(); + evaluateTransform(); + m_patch.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; + + + bool testLight( const RendererLight& light ) const { + return light.testAABB( worldAABB() ); + } }; @@ -1709,110 +1709,110 @@ class PatchNode : public scene::Instantiable, public scene::Cloneable { -typedef PatchNode Self; + typedef PatchNode Self; -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + } + InstanceTypeCastTable& get(){ + return m_casts; + } + }; -scene::Node m_node; -InstanceSet m_instances; -Patch m_patch; -TokenImporter m_importMap; -TokenExporter m_exportMap; + scene::Node m_node; + InstanceSet m_instances; + Patch m_patch; + TokenImporter m_importMap; + TokenExporter m_exportMap; public: -typedef LazyStatic StaticTypeCasts; + typedef LazyStatic StaticTypeCasts; -Snappable& get( NullType){ - return m_patch; -} -TransformNode& get( NullType){ - return m_patch; -} -Patch& get( NullType){ - return m_patch; -} -XMLImporter& get( NullType){ - return m_patch; -} -XMLExporter& get( NullType){ - return m_patch; -} -MapImporter& get( NullType){ - return m_importMap; -} -MapExporter& get( NullType){ - return m_exportMap; -} -Nameable& get( NullType){ - return m_patch; -} + Snappable& get( NullType){ + return m_patch; + } + TransformNode& get( NullType){ + return m_patch; + } + Patch& get( NullType){ + return m_patch; + } + XMLImporter& get( NullType){ + return m_patch; + } + XMLExporter& get( NullType){ + return m_patch; + } + MapImporter& get( NullType){ + return m_importMap; + } + MapExporter& get( NullType){ + return m_exportMap; + } + Nameable& get( NullType){ + return m_patch; + } -PatchNode( bool patchDef3 = false ) : - m_node( this, this, StaticTypeCasts::instance().get() ), - m_patch( m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), - m_importMap( m_patch ), - m_exportMap( m_patch ){ - m_patch.m_patchDef3 = patchDef3; -} -PatchNode( const PatchNode& other ) : - scene::Node::Symbiot( other ), - scene::Instantiable( other ), - scene::Cloneable( other ), - m_node( this, this, StaticTypeCasts::instance().get() ), - m_patch( other.m_patch, m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), - m_importMap( m_patch ), - m_exportMap( m_patch ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} -Patch& get(){ - return m_patch; -} -const Patch& get() const { - return m_patch; -} + PatchNode( bool patchDef3 = false ) : + m_node( this, this, StaticTypeCasts::instance().get() ), + m_patch( m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), + m_importMap( m_patch ), + m_exportMap( m_patch ){ + m_patch.m_patchDef3 = patchDef3; + } + PatchNode( const PatchNode& other ) : + scene::Node::Symbiot( other ), + scene::Instantiable( other ), + scene::Cloneable( other ), + m_node( this, this, StaticTypeCasts::instance().get() ), + m_patch( other.m_patch, m_node, InstanceSetEvaluateTransform::Caller( m_instances ), InstanceSet::BoundsChangedCaller( m_instances ) ), + m_importMap( m_patch ), + m_exportMap( m_patch ){ + } + void release(){ + delete this; + } + scene::Node& node(){ + return m_node; + } + Patch& get(){ + return m_patch; + } + const Patch& get() const { + return m_patch; + } -scene::Node& clone() const { - return ( new PatchNode( *this ) )->node(); -} + scene::Node& clone() const { + return ( new PatchNode( *this ) )->node(); + } -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new PatchInstance( path, parent, m_patch ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - return m_instances.erase( observer, path ); -} + scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new PatchInstance( path, parent, m_patch ); + } + void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); + } + void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + } + scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + return m_instances.erase( observer, path ); + } }; @@ -1831,16 +1831,16 @@ inline PatchInstance* Instance_getPatch( scene::Instance& instance ){ template class PatchSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -PatchSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - PatchInstance* patch = Instance_getPatch( instance ); - if ( patch != 0 ) { - m_functor( *patch ); + PatchSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + PatchInstance* patch = Instance_getPatch( instance ); + if ( patch != 0 ) { + m_functor( *patch ); + } } -} }; template @@ -1852,17 +1852,17 @@ inline void Scene_forEachSelectedPatch( const Functor& functor ){ template class PatchVisibleSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -PatchVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - PatchInstance* patch = Instance_getPatch( instance ); - if ( patch != 0 - && instance.path().top().get().visible() ) { - m_functor( *patch ); + PatchVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + PatchInstance* patch = Instance_getPatch( instance ); + if ( patch != 0 + && instance.path().top().get().visible() ) { + m_functor( *patch ); + } } -} }; template @@ -1873,22 +1873,22 @@ inline void Scene_forEachVisibleSelectedPatchInstance( const Functor& functor ){ template class PatchForEachWalker : public scene::Graph::Walker { -const Functor& m_functor; + const Functor& m_functor; public: -PatchForEachWalker( const Functor& functor ) : m_functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Patch* patch = Node_getPatch( path.top() ); - if ( patch != 0 ) { - m_functor( *patch ); + PatchForEachWalker( const Functor& functor ) : m_functor( functor ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Patch* patch = Node_getPatch( path.top() ); + if ( patch != 0 ) { + m_functor( *patch ); + } } + else{ + return false; + } + return true; } - else{ - return false; - } - return true; -} }; template @@ -1899,23 +1899,23 @@ inline void Scene_forEachVisiblePatch( const Functor& functor ){ template class PatchForEachSelectedWalker : public scene::Graph::Walker { -const Functor& m_functor; + const Functor& m_functor; public: -PatchForEachSelectedWalker( const Functor& functor ) : m_functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - Patch* patch = Node_getPatch( path.top() ); - if ( patch != 0 - && Instance_isSelected( instance ) ) { - m_functor( *patch ); + PatchForEachSelectedWalker( const Functor& functor ) : m_functor( functor ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + Patch* patch = Node_getPatch( path.top() ); + if ( patch != 0 + && Instance_isSelected( instance ) ) { + m_functor( *patch ); + } } + else{ + return false; + } + return true; } - else{ - return false; - } - return true; -} }; template @@ -1926,22 +1926,22 @@ inline void Scene_forEachVisibleSelectedPatch( const Functor& functor ){ template class PatchForEachInstanceWalker : public scene::Graph::Walker { -const Functor& m_functor; + const Functor& m_functor; public: -PatchForEachInstanceWalker( const Functor& functor ) : m_functor( functor ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() ) { - PatchInstance* patch = Instance_getPatch( instance ); - if ( patch != 0 ) { - m_functor( *patch ); + PatchForEachInstanceWalker( const Functor& functor ) : m_functor( functor ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() ) { + PatchInstance* patch = Instance_getPatch( instance ); + if ( patch != 0 ) { + m_functor( *patch ); + } } + else{ + return false; + } + return true; } - else{ - return false; - } - return true; -} }; template diff --git a/radiant/patchdialog.cpp b/radiant/patchdialog.cpp index 3a4702fc..ce23b080 100644 --- a/radiant/patchdialog.cpp +++ b/radiant/patchdialog.cpp @@ -70,13 +70,13 @@ pi_globals_t g_pi_globals; class PatchFixedSubdivisions { public: -PatchFixedSubdivisions() : m_enabled( false ), m_x( 0 ), m_y( 0 ){ -} -PatchFixedSubdivisions( bool enabled, std::size_t x, std::size_t y ) : m_enabled( enabled ), m_x( x ), m_y( y ){ -} -bool m_enabled; -std::size_t m_x; -std::size_t m_y; + PatchFixedSubdivisions() : m_enabled( false ), m_x( 0 ), m_y( 0 ){ + } + PatchFixedSubdivisions( bool enabled, std::size_t x, std::size_t y ) : m_enabled( enabled ), m_x( x ), m_y( y ){ + } + bool m_enabled; + std::size_t m_x; + std::size_t m_y; }; void Patch_getFixedSubdivisions( const Patch& patch, PatchFixedSubdivisions& subdivisions ){ @@ -114,14 +114,14 @@ void Patch_setFixedSubdivisions( Patch& patch, const PatchFixedSubdivisions& sub class PatchGetFixedSubdivisions { -PatchFixedSubdivisions& m_subdivisions; + PatchFixedSubdivisions& m_subdivisions; public: -PatchGetFixedSubdivisions( PatchFixedSubdivisions& subdivisions ) : m_subdivisions( subdivisions ){ -} -void operator()( Patch& patch ){ - Patch_getFixedSubdivisions( patch, m_subdivisions ); - SceneChangeNotify(); -} + PatchGetFixedSubdivisions( PatchFixedSubdivisions& subdivisions ) : m_subdivisions( subdivisions ){ + } + void operator()( Patch& patch ){ + Patch_getFixedSubdivisions( patch, m_subdivisions ); + SceneChangeNotify(); + } }; void Scene_PatchGetFixedSubdivisions( PatchFixedSubdivisions& subdivisions ){ @@ -139,13 +139,13 @@ void Scene_PatchGetFixedSubdivisions( PatchFixedSubdivisions& subdivisions ){ class PatchSetFixedSubdivisions { -const PatchFixedSubdivisions& m_subdivisions; + const PatchFixedSubdivisions& m_subdivisions; public: -PatchSetFixedSubdivisions( const PatchFixedSubdivisions& subdivisions ) : m_subdivisions( subdivisions ){ -} -void operator()( Patch& patch ) const { - Patch_setFixedSubdivisions( patch, m_subdivisions ); -} + PatchSetFixedSubdivisions( const PatchFixedSubdivisions& subdivisions ) : m_subdivisions( subdivisions ){ + } + void operator()( Patch& patch ) const { + Patch_setFixedSubdivisions( patch, m_subdivisions ); + } }; void Scene_PatchSetFixedSubdivisions( const PatchFixedSubdivisions& subdivisions ){ @@ -158,120 +158,120 @@ typedef struct _GtkCheckButton GtkCheckButton; class Subdivisions { public: -GtkCheckButton* m_enabled; -GtkEntry* m_horizontal; -GtkEntry* m_vertical; -Subdivisions() : m_enabled( 0 ), m_horizontal( 0 ), m_vertical( 0 ){ -} -void update(){ - PatchFixedSubdivisions subdivisions; - Scene_PatchGetFixedSubdivisions( subdivisions ); - - toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_enabled ), subdivisions.m_enabled ); - - if ( subdivisions.m_enabled ) { - entry_set_int( m_horizontal, static_cast( subdivisions.m_x ) ); - entry_set_int( m_vertical, static_cast( subdivisions.m_y ) ); - gtk_widget_set_sensitive( GTK_WIDGET( m_horizontal ), TRUE ); - gtk_widget_set_sensitive( GTK_WIDGET( m_vertical ), TRUE ); + GtkCheckButton* m_enabled; + GtkEntry* m_horizontal; + GtkEntry* m_vertical; + Subdivisions() : m_enabled( 0 ), m_horizontal( 0 ), m_vertical( 0 ){ } - else - { - gtk_entry_set_text( m_horizontal, "" ); - gtk_entry_set_text( m_vertical, "" ); - gtk_widget_set_sensitive( GTK_WIDGET( m_horizontal ), FALSE ); - gtk_widget_set_sensitive( GTK_WIDGET( m_vertical ), FALSE ); + void update(){ + PatchFixedSubdivisions subdivisions; + Scene_PatchGetFixedSubdivisions( subdivisions ); + + toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( m_enabled ), subdivisions.m_enabled ); + + if ( subdivisions.m_enabled ) { + entry_set_int( m_horizontal, static_cast( subdivisions.m_x ) ); + entry_set_int( m_vertical, static_cast( subdivisions.m_y ) ); + gtk_widget_set_sensitive( GTK_WIDGET( m_horizontal ), TRUE ); + gtk_widget_set_sensitive( GTK_WIDGET( m_vertical ), TRUE ); + } + else + { + gtk_entry_set_text( m_horizontal, "" ); + gtk_entry_set_text( m_vertical, "" ); + gtk_widget_set_sensitive( GTK_WIDGET( m_horizontal ), FALSE ); + gtk_widget_set_sensitive( GTK_WIDGET( m_vertical ), FALSE ); + } } -} -void cancel(){ - update(); -} -typedef MemberCaller CancelCaller; -void apply(){ - Scene_PatchSetFixedSubdivisions( - PatchFixedSubdivisions( - gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( m_enabled ) ), - static_cast( entry_get_int( m_horizontal ) ), - static_cast( entry_get_int( m_vertical ) ) - ) + void cancel(){ + update(); + } + typedef MemberCaller CancelCaller; + void apply(){ + Scene_PatchSetFixedSubdivisions( + PatchFixedSubdivisions( + gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( m_enabled ) ), + static_cast( entry_get_int( m_horizontal ) ), + static_cast( entry_get_int( m_vertical ) ) + ) ); -} -typedef MemberCaller ApplyCaller; -static void applyGtk( GtkToggleButton* toggle, Subdivisions* self ){ - self->apply(); -} + } + typedef MemberCaller ApplyCaller; + static void applyGtk( GtkToggleButton* toggle, Subdivisions* self ){ + self->apply(); + } }; class PatchInspector : public Dialog { -GtkWindow* BuildDialog(); -Subdivisions m_subdivisions; -NonModalEntry m_horizontalSubdivisionsEntry; -NonModalEntry m_verticalSubdivisionsEntry; + GtkWindow* BuildDialog(); + Subdivisions m_subdivisions; + NonModalEntry m_horizontalSubdivisionsEntry; + NonModalEntry m_verticalSubdivisionsEntry; public: -IdleDraw m_idleDraw; -WindowPositionTracker m_position_tracker; + IdleDraw m_idleDraw; + WindowPositionTracker m_position_tracker; -Patch *m_Patch; + Patch *m_Patch; -CopiedString m_strName; -float m_fS; -float m_fT; -float m_fX; -float m_fY; -float m_fZ; -/* float m_fHScale; - float m_fHShift; - float m_fRotate; - float m_fVScale; - float m_fVShift; */ -int m_nCol; -int m_nRow; -GtkComboBoxText *m_pRowCombo; -GtkComboBoxText *m_pColCombo; -std::size_t m_countRows; -std::size_t m_countCols; + CopiedString m_strName; + float m_fS; + float m_fT; + float m_fX; + float m_fY; + float m_fZ; + /* float m_fHScale; + float m_fHShift; + float m_fRotate; + float m_fVScale; + float m_fVShift; */ + int m_nCol; + int m_nRow; + GtkComboBoxText *m_pRowCombo; + GtkComboBoxText *m_pColCombo; + std::size_t m_countRows; + std::size_t m_countCols; // turn on/off processing of the "changed" "value_changed" messages // (need to turn off when we are feeding data in) // NOTE: much more simple than blocking signals -bool m_bListenChanged; + bool m_bListenChanged; -PatchInspector() : - m_horizontalSubdivisionsEntry( Subdivisions::ApplyCaller( m_subdivisions ), Subdivisions::CancelCaller( m_subdivisions ) ), - m_verticalSubdivisionsEntry( Subdivisions::ApplyCaller( m_subdivisions ), Subdivisions::CancelCaller( m_subdivisions ) ), - m_idleDraw( MemberCaller( *this ) ){ - m_fS = 0.0f; - m_fT = 0.0f; - m_fX = 0.0f; - m_fY = 0.0f; - m_fZ = 0.0f; - m_nCol = 0; - m_nRow = 0; - m_countRows = 0; - m_countCols = 0; - m_Patch = 0; - m_bListenChanged = true; + PatchInspector() : + m_horizontalSubdivisionsEntry( Subdivisions::ApplyCaller( m_subdivisions ), Subdivisions::CancelCaller( m_subdivisions ) ), + m_verticalSubdivisionsEntry( Subdivisions::ApplyCaller( m_subdivisions ), Subdivisions::CancelCaller( m_subdivisions ) ), + m_idleDraw( MemberCaller( *this ) ){ + m_fS = 0.0f; + m_fT = 0.0f; + m_fX = 0.0f; + m_fY = 0.0f; + m_fZ = 0.0f; + m_nCol = 0; + m_nRow = 0; + m_countRows = 0; + m_countCols = 0; + m_Patch = 0; + m_bListenChanged = true; - m_position_tracker.setPosition( c_default_window_pos ); -} + m_position_tracker.setPosition( c_default_window_pos ); + } -bool visible(){ - return gtk_widget_get_visible( GTK_WIDGET( GetWidget() ) ); -} + bool visible(){ + return gtk_widget_get_visible( GTK_WIDGET( GetWidget() ) ); + } -// void UpdateInfo(); -// void SetPatchInfo(); -void GetPatchInfo(); -void UpdateSpinners( bool bUp, int nID ); +// void UpdateInfo(); +// void SetPatchInfo(); + void GetPatchInfo(); + void UpdateSpinners( bool bUp, int nID ); // read the current patch on map and initialize m_fX m_fY accordingly -void UpdateRowColInfo(); + void UpdateRowColInfo(); // sync the dialog our internal data structures // depending on the flag it will read or write // we use m_nCol m_nRow m_fX m_fY m_fZ m_fS m_fT m_strName // (NOTE: this doesn't actually commit stuff to the map or read from it) -void importData(); -void exportData(); + void importData(); + void exportData(); }; PatchInspector g_PatchInspector; @@ -327,7 +327,7 @@ static void OnApply( GtkWidget *widget, gpointer data ){ std::size_t r = g_PatchInspector.m_nRow; std::size_t c = g_PatchInspector.m_nCol; if ( r < g_PatchInspector.m_Patch->getHeight() - && c < g_PatchInspector.m_Patch->getWidth() ) { + && c < g_PatchInspector.m_Patch->getWidth() ) { PatchControl& p = g_PatchInspector.m_Patch->ctrlAt( r,c ); p.m_vertex[0] = g_PatchInspector.m_fX; p.m_vertex[1] = g_PatchInspector.m_fY; @@ -353,13 +353,13 @@ static void OnSelchangeComboColRow( GtkWidget *widget, gpointer data ){ class PatchSetTextureRepeat { -float m_s, m_t; + float m_s, m_t; public: -PatchSetTextureRepeat( float s, float t ) : m_s( s ), m_t( t ){ -} -void operator()( Patch& patch ) const { - patch.SetTextureRepeat( m_s, m_t ); -} + PatchSetTextureRepeat( float s, float t ) : m_s( s ), m_t( t ){ + } + void operator()( Patch& patch ) const { + patch.SetTextureRepeat( m_s, m_t ); + } }; void Scene_PatchTileTexture_Selected( scene::Graph& graph, float s, float t ){ @@ -408,13 +408,13 @@ void Scene_PatchRotateTexture_Selected( scene::Graph& graph, float angle ){ class PatchScaleTexture { -float m_s, m_t; + float m_s, m_t; public: -PatchScaleTexture( float s, float t ) : m_s( s ), m_t( t ){ -} -void operator()( Patch& patch ) const { - patch.ScaleTexture( m_s, m_t ); -} + PatchScaleTexture( float s, float t ) : m_s( s ), m_t( t ){ + } + void operator()( Patch& patch ) const { + patch.ScaleTexture( m_s, m_t ); + } }; float Patch_convertScale( float scale ){ @@ -433,14 +433,14 @@ void Scene_PatchScaleTexture_Selected( scene::Graph& graph, float s, float t ){ class PatchTranslateTexture { -float m_s, m_t; + float m_s, m_t; public: -PatchTranslateTexture( float s, float t ) - : m_s( s ), m_t( t ){ -} -void operator()( Patch& patch ) const { - patch.TranslateTexture( m_s, m_t ); -} + PatchTranslateTexture( float s, float t ) + : m_s( s ), m_t( t ){ + } + void operator()( Patch& patch ) const { + patch.TranslateTexture( m_s, m_t ); + } }; void Scene_PatchTranslateTexture_Selected( scene::Graph& graph, float s, float t ){ @@ -593,15 +593,15 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Row:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Column:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 1, 2, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkComboBoxText* combo = m_pRowCombo = GTK_COMBO_BOX_TEXT( gtk_combo_box_text_new() ); @@ -610,8 +610,8 @@ GtkWindow* PatchInspector::BuildDialog(){ gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table, GTK_WIDGET( combo ), 0, 1, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( combo ), 60, -1 ); } @@ -622,8 +622,8 @@ GtkWindow* PatchInspector::BuildDialog(){ gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table, GTK_WIDGET( combo ), 1, 2, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( combo ), 60, -1 ); } } @@ -636,43 +636,43 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "X:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Y:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Z:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 2, 3, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "S:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 3, 4, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "T:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 4, 5, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); AddDialogData( *entry, m_fX ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( OnDialogKey ), 0 ); @@ -681,8 +681,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); AddDialogData( *entry, m_fY ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( OnDialogKey ), 0 ); @@ -691,8 +691,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 2, 3, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); AddDialogData( *entry, m_fZ ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( OnDialogKey ), 0 ); @@ -701,8 +701,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 3, 4, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); AddDialogData( *entry, m_fS ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( OnDialogKey ), 0 ); @@ -711,8 +711,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 4, 5, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); AddDialogData( *entry, m_fT ); g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( OnDialogKey ), 0 ); @@ -738,15 +738,15 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Fixed" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new() ); gtk_widget_show( GTK_WIDGET( check ) ); gtk_table_attach( table, GTK_WIDGET( check ), 1, 2, 0, 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); m_subdivisions.m_enabled = check; guint handler_id = g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( &Subdivisions::applyGtk ), &m_subdivisions ); g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler_id ) ); @@ -755,15 +755,15 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Horizontal" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); m_subdivisions.m_horizontal = entry; m_horizontalSubdivisionsEntry.connect( entry ); } @@ -771,15 +771,15 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Vertical" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 2, 3, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 2, 3, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); m_subdivisions.m_vertical = entry; m_verticalSubdivisionsEntry.connect( entry ); } @@ -822,32 +822,32 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Horizontal Shift Step" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 2, 4, 0, 1, - (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Vertical Shift Step" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 2, 4, 1, 2, - (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Horizontal Stretch Step" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 2, 3, 2, 3, - (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkButton* button = GTK_BUTTON( gtk_button_new_with_label( "FlipX" ) ); gtk_widget_show( GTK_WIDGET( button ) ); gtk_table_attach( table, GTK_WIDGET( button ), 3, 4, 2, 3, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchFlipX ), 0 ); gtk_widget_set_size_request( GTK_WIDGET( button ), 60, -1 ); } @@ -855,16 +855,16 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Vertical Stretch Step" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 2, 3, 3, 4, - (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkButton* button = GTK_BUTTON( gtk_button_new_with_label( "FlipY" ) ); gtk_widget_show( GTK_WIDGET( button ) ); gtk_table_attach( table, GTK_WIDGET( button ), 3, 4, 3, 4, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchFlipY ), 0 ); gtk_widget_set_size_request( GTK_WIDGET( button ), 60, -1 ); } @@ -872,16 +872,16 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Rotate Step" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 2, 4, 4, 5, - (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL|GTK_EXPAND ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 0, 1, 0, 1, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); g_object_set_data( G_OBJECT( window ), "hshift_entry", entry ); // we fill in this data, if no patch is selected the widgets are unmodified when the inspector is raised @@ -895,8 +895,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 0 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 0, 1, - (GtkAttachOptions)( 0 ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( 0 ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 16, -1 ); gtk_widget_set_can_focus( GTK_WIDGET( spin ), FALSE ); } @@ -904,8 +904,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 0, 1, 1, 2, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); entry_set_float( entry, g_pi_globals.shift[1] ); @@ -916,8 +916,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 0 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 1, 2, - (GtkAttachOptions)( 0 ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( 0 ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 16, -1 ); gtk_widget_set_can_focus( GTK_WIDGET( spin ), FALSE ); } @@ -925,8 +925,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 0, 1, 2, 3, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); entry_set_float( entry, g_pi_globals.scale[0] ); @@ -937,8 +937,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 0 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 2, 3, - (GtkAttachOptions)( 0 ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( 0 ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 16, -1 ); gtk_widget_set_can_focus( GTK_WIDGET( spin ), FALSE ); } @@ -946,8 +946,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 0, 1, 3, 4, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); entry_set_float( entry, g_pi_globals.scale[1] ); @@ -958,8 +958,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 0 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 3, 4, - (GtkAttachOptions)( 0 ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( 0 ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 16, -1 ); gtk_widget_set_can_focus( GTK_WIDGET( spin ), FALSE ); } @@ -967,8 +967,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( table, GTK_WIDGET( entry ), 0, 1, 4, 5, - (GtkAttachOptions)( GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); entry_set_float( entry, g_pi_globals.rotate ); @@ -979,8 +979,8 @@ GtkWindow* PatchInspector::BuildDialog(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 0 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 4, 5, - (GtkAttachOptions)( 0 ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( 0 ), + (GtkAttachOptions)( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 16, -1 ); gtk_widget_set_can_focus( GTK_WIDGET( spin ), FALSE ); } @@ -1102,7 +1102,8 @@ void PatchInspector::GetPatchInfo(){ //globalWarningStream() << "WARNING: no patch\n"; } // fill in our internal structs - m_nRow = 0; m_nCol = 0; + m_nRow = 0; + m_nCol = 0; UpdateRowColInfo(); // now update the dialog box importData(); @@ -1118,7 +1119,7 @@ void PatchInspector::UpdateRowColInfo(){ std::size_t r = m_nRow; std::size_t c = m_nCol; if ( r < m_Patch->getHeight() - && c < m_Patch->getWidth() ) { + && c < m_Patch->getWidth() ) { const PatchControl& p = m_Patch->ctrlAt( r,c ); m_fX = p.m_vertex[0]; m_fY = p.m_vertex[1]; diff --git a/radiant/patchmanip.cpp b/radiant/patchmanip.cpp index 45cdeef5..0f08d715 100644 --- a/radiant/patchmanip.cpp +++ b/radiant/patchmanip.cpp @@ -74,17 +74,17 @@ void Scene_PatchConstructPrefab( scene::Graph& graph, const AABB aabb, const cha void Patch_makeCaps( Patch& patch, scene::Instance& instance, EPatchCap type, const char* shader ){ if ( ( type == eCapEndCap || type == eCapIEndCap ) - && patch.getWidth() != 5 ) { + && patch.getWidth() != 5 ) { globalErrorStream() << "cannot create end-cap - patch width != 5\n"; return; } if ( ( type == eCapBevel || type == eCapIBevel ) - && patch.getWidth() != 3 && patch.getWidth() != 5 ) { + && patch.getWidth() != 3 && patch.getWidth() != 5 ) { globalErrorStream() << "cannot create bevel-cap - patch width != 3\n"; return; } if ( type == eCapCylinder - && patch.getWidth() != 9 ) { + && patch.getWidth() != 9 ) { globalErrorStream() << "cannot create cylinder-cap - patch width != 9\n"; return; } @@ -121,13 +121,13 @@ typedef std::vector InstanceVector; class PatchStoreInstance { -InstanceVector& m_instances; + InstanceVector& m_instances; public: -PatchStoreInstance( InstanceVector& instances ) : m_instances( instances ){ -} -void operator()( PatchInstance& patch ) const { - m_instances.push_back( &patch ); -} + PatchStoreInstance( InstanceVector& instances ) : m_instances( instances ){ + } + void operator()( PatchInstance& patch ) const { + m_instances.push_back( &patch ); + } }; enum ECapDialog { @@ -201,68 +201,68 @@ void Scene_PatchDeform( scene::Graph& graph, const int deform, const int axis ) void Patch_thicken( Patch& patch, scene::Instance& instance, const float thickness, bool seams, const int axis ){ - // Create a new patch node - NodeSmartReference node( g_patchCreator->createPatch() ); - // Insert the node into worldspawn - Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node ); + // Create a new patch node + NodeSmartReference node( g_patchCreator->createPatch() ); + // Insert the node into worldspawn + Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node ); - // Retrieve the contained patch from the node - Patch* targetPatch = Node_getPatch( node ); + // Retrieve the contained patch from the node + Patch* targetPatch = Node_getPatch( node ); - // Create the opposite patch with the given thickness = distance - bool no12 = true; - bool no34 = true; - targetPatch->createThickenedOpposite( patch, thickness, axis, no12, no34 ); + // Create the opposite patch with the given thickness = distance + bool no12 = true; + bool no34 = true; + targetPatch->createThickenedOpposite( patch, thickness, axis, no12, no34 ); - // Now select the newly created patches - { - scene::Path patchpath( makeReference( GlobalSceneGraph().root() ) ); - patchpath.push( makeReference( *Map_GetWorldspawn( g_map ) ) ); - patchpath.push( makeReference( node.get() ) ); - Instance_getSelectable( *GlobalSceneGraph().find( patchpath ) )->setSelected( true ); + // Now select the newly created patches + { + scene::Path patchpath( makeReference( GlobalSceneGraph().root() ) ); + patchpath.push( makeReference( *Map_GetWorldspawn( g_map ) ) ); + patchpath.push( makeReference( node.get() ) ); + Instance_getSelectable( *GlobalSceneGraph().find( patchpath ) )->setSelected( true ); + } + + if( seams && thickness != 0.0f){ + int i = 0; + if ( no12 ){ + i = 2; } + int iend = 4; + if ( no34 ){ + iend = 2; + } + // Now create the four walls + for ( ; i < iend; i++ ){ + // Allocate new patch + NodeSmartReference node = NodeSmartReference( g_patchCreator->createPatch() ); + // Insert each node into worldspawn + Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node ); - if( seams && thickness != 0.0f){ - int i = 0; - if ( no12 ){ - i = 2; + // Retrieve the contained patch from the node + Patch* wallPatch = Node_getPatch( node ); + + // Create the wall patch by passing i as wallIndex + wallPatch->createThickenedWall( patch, *targetPatch, i ); + + if( ( wallPatch->localAABB().extents[0] <= 0.00005 && wallPatch->localAABB().extents[1] <= 0.00005 ) || + ( wallPatch->localAABB().extents[1] <= 0.00005 && wallPatch->localAABB().extents[2] <= 0.00005 ) || + ( wallPatch->localAABB().extents[0] <= 0.00005 && wallPatch->localAABB().extents[2] <= 0.00005 ) ){ + //globalOutputStream() << "Thicken: Discarding degenerate patch.\n"; + Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->erase( node ); } - int iend = 4; - if ( no34 ){ - iend = 2; - } - // Now create the four walls - for ( ; i < iend; i++ ){ - // Allocate new patch - NodeSmartReference node = NodeSmartReference( g_patchCreator->createPatch() ); - // Insert each node into worldspawn - Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node ); - - // Retrieve the contained patch from the node - Patch* wallPatch = Node_getPatch( node ); - - // Create the wall patch by passing i as wallIndex - wallPatch->createThickenedWall( patch, *targetPatch, i ); - - if( ( wallPatch->localAABB().extents[0] <= 0.00005 && wallPatch->localAABB().extents[1] <= 0.00005 ) || - ( wallPatch->localAABB().extents[1] <= 0.00005 && wallPatch->localAABB().extents[2] <= 0.00005 ) || - ( wallPatch->localAABB().extents[0] <= 0.00005 && wallPatch->localAABB().extents[2] <= 0.00005 ) ){ - //globalOutputStream() << "Thicken: Discarding degenerate patch.\n"; - Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->erase( node ); - } - else + else // Now select the newly created patches - { - scene::Path patchpath( makeReference( GlobalSceneGraph().root() ) ); - patchpath.push( makeReference( *Map_GetWorldspawn(g_map) ) ); - patchpath.push( makeReference( node.get() ) ); - Instance_getSelectable( *GlobalSceneGraph().find( patchpath ) )->setSelected( true ); - } + { + scene::Path patchpath( makeReference( GlobalSceneGraph().root() ) ); + patchpath.push( makeReference( *Map_GetWorldspawn(g_map) ) ); + patchpath.push( makeReference( node.get() ) ); + Instance_getSelectable( *GlobalSceneGraph().find( patchpath ) )->setSelected( true ); } } + } - // Invert the target patch so that it faces the opposite direction - targetPatch->InvertMatrix(); + // Invert the target patch so that it faces the opposite direction + targetPatch->InvertMatrix(); } void Scene_PatchThicken( scene::Graph& graph, const int thickness, bool seams, const int axis ) @@ -290,10 +290,10 @@ Patch* Scene_GetUltimateSelectedVisiblePatch(){ class PatchCapTexture { public: -void operator()( Patch& patch ) const { - //patch.ProjectTexture( Patch::m_CycleCapIndex ); - patch.CapTexture(); -} + void operator()( Patch& patch ) const { + //patch.ProjectTexture( Patch::m_CycleCapIndex ); + patch.CapTexture(); + } }; void Scene_PatchCapTexture_Selected( scene::Graph& graph ){ @@ -338,13 +338,13 @@ void Scene_PatchProjectTexture_Selected( scene::Graph& graph, const TextureProje class PatchFlipTexture { -int m_axis; + int m_axis; public: -PatchFlipTexture( int axis ) : m_axis( axis ){ -} -void operator()( Patch& patch ) const { - patch.FlipTexture( m_axis ); -} + PatchFlipTexture( int axis ) : m_axis( axis ){ + } + void operator()( Patch& patch ) const { + patch.FlipTexture( m_axis ); + } }; void Scene_PatchFlipTexture_Selected( scene::Graph& graph, int axis ){ @@ -354,9 +354,9 @@ void Scene_PatchFlipTexture_Selected( scene::Graph& graph, int axis ){ class PatchNaturalTexture { public: -void operator()( Patch& patch ) const { - patch.NaturalTexture(); -} + void operator()( Patch& patch ) const { + patch.NaturalTexture(); + } }; void Scene_PatchNaturalTexture_Selected( scene::Graph& graph ){ @@ -367,13 +367,13 @@ void Scene_PatchNaturalTexture_Selected( scene::Graph& graph ){ class PatchInsertRemove { -bool m_insert, m_column, m_first; + bool m_insert, m_column, m_first; public: -PatchInsertRemove( bool insert, bool column, bool first ) : m_insert( insert ), m_column( column ), m_first( first ){ -} -void operator()( Patch& patch ) const { - patch.InsertRemove( m_insert, m_column, m_first ); -} + PatchInsertRemove( bool insert, bool column, bool first ) : m_insert( insert ), m_column( column ), m_first( first ){ + } + void operator()( Patch& patch ) const { + patch.InsertRemove( m_insert, m_column, m_first ); + } }; void Scene_PatchInsertRemove_Selected( scene::Graph& graph, bool bInsert, bool bColumn, bool bFirst ){ @@ -383,9 +383,9 @@ void Scene_PatchInsertRemove_Selected( scene::Graph& graph, bool bInsert, bool b class PatchInvertMatrix { public: -void operator()( Patch& patch ) const { - patch.InvertMatrix(); -} + void operator()( Patch& patch ) const { + patch.InvertMatrix(); + } }; void Scene_PatchInvert_Selected( scene::Graph& graph ){ @@ -394,13 +394,13 @@ void Scene_PatchInvert_Selected( scene::Graph& graph ){ class PatchRedisperse { -EMatrixMajor m_major; + EMatrixMajor m_major; public: -PatchRedisperse( EMatrixMajor major ) : m_major( major ){ -} -void operator()( Patch& patch ) const { - patch.Redisperse( m_major ); -} + PatchRedisperse( EMatrixMajor major ) : m_major( major ){ + } + void operator()( Patch& patch ) const { + patch.Redisperse( m_major ); + } }; void Scene_PatchRedisperse_Selected( scene::Graph& graph, EMatrixMajor major ){ @@ -409,13 +409,13 @@ void Scene_PatchRedisperse_Selected( scene::Graph& graph, EMatrixMajor major ){ class PatchSmooth { -EMatrixMajor m_major; + EMatrixMajor m_major; public: -PatchSmooth( EMatrixMajor major ) : m_major( major ){ -} -void operator()( Patch& patch ) const { - patch.Smooth( m_major ); -} + PatchSmooth( EMatrixMajor major ) : m_major( major ){ + } + void operator()( Patch& patch ) const { + patch.Smooth( m_major ); + } }; void Scene_PatchSmooth_Selected( scene::Graph& graph, EMatrixMajor major ){ @@ -425,9 +425,9 @@ void Scene_PatchSmooth_Selected( scene::Graph& graph, EMatrixMajor major ){ class PatchTransposeMatrix { public: -void operator()( Patch& patch ) const { - patch.TransposeMatrix(); -} + void operator()( Patch& patch ) const { + patch.TransposeMatrix(); + } }; void Scene_PatchTranspose_Selected( scene::Graph& graph ){ @@ -436,14 +436,14 @@ void Scene_PatchTranspose_Selected( scene::Graph& graph ){ class PatchSetShader { -const char* m_name; + const char* m_name; public: -PatchSetShader( const char* name ) - : m_name( name ){ -} -void operator()( Patch& patch ) const { - patch.SetShader( m_name ); -} + PatchSetShader( const char* name ) + : m_name( name ){ + } + void operator()( Patch& patch ) const { + patch.SetShader( m_name ); + } }; void Scene_PatchSetShader_Selected( scene::Graph& graph, const char* name ){ @@ -460,16 +460,16 @@ void Scene_PatchGetShader_Selected( scene::Graph& graph, CopiedString& name ){ class PatchSelectByShader { -const char* m_name; + const char* m_name; public: -inline PatchSelectByShader( const char* name ) - : m_name( name ){ -} -void operator()( PatchInstance& patch ) const { - if ( shader_equal( patch.getPatch().GetShader(), m_name ) ) { - patch.setSelected( true ); + inline PatchSelectByShader( const char* name ) + : m_name( name ){ + } + void operator()( PatchInstance& patch ) const { + if ( shader_equal( patch.getPatch().GetShader(), m_name ) ) { + patch.setSelected( true ); + } } -} }; void Scene_PatchSelectByShader( scene::Graph& graph, const char* name ){ @@ -479,16 +479,16 @@ void Scene_PatchSelectByShader( scene::Graph& graph, const char* name ){ class PatchFindReplaceShader { -const char* m_find; -const char* m_replace; + const char* m_find; + const char* m_replace; public: -PatchFindReplaceShader( const char* find, const char* replace ) : m_find( find ), m_replace( replace ){ -} -void operator()( Patch& patch ) const { - if ( shader_equal( patch.GetShader(), m_find ) ) { - patch.SetShader( m_replace ); + PatchFindReplaceShader( const char* find, const char* replace ) : m_find( find ), m_replace( replace ){ + } + void operator()( Patch& patch ) const { + if ( shader_equal( patch.GetShader(), m_find ) ) { + patch.SetShader( m_replace ); + } } -} }; void Scene_PatchFindReplaceShader( scene::Graph& graph, const char* find, const char* replace ){ @@ -772,31 +772,31 @@ void Patch_Thicken(){ class filter_patch_all : public PatchFilter { public: -bool filter( const Patch& patch ) const { - return true; -} + bool filter( const Patch& patch ) const { + return true; + } }; class filter_patch_shader : public PatchFilter { -const char* m_shader; + const char* m_shader; public: -filter_patch_shader( const char* shader ) : m_shader( shader ){ -} -bool filter( const Patch& patch ) const { - return shader_equal( patch.GetShader(), m_shader ); -} + filter_patch_shader( const char* shader ) : m_shader( shader ){ + } + bool filter( const Patch& patch ) const { + return shader_equal( patch.GetShader(), m_shader ); + } }; class filter_patch_flags : public PatchFilter { -int m_flags; + int m_flags; public: -filter_patch_flags( int flags ) : m_flags( flags ){ -} -bool filter( const Patch& patch ) const { - return ( patch.getShaderFlags() & m_flags ) != 0; -} + filter_patch_flags( int flags ) : m_flags( flags ){ + } + bool filter( const Patch& patch ) const { + return ( patch.getShaderFlags() & m_flags ) != 0; + } }; @@ -997,16 +997,16 @@ void DoNewPatchDlg( EPatchPrefab prefab, int minrows, int mincols, int defrows, GtkLabel* label = GTK_LABEL( gtk_label_new( "Width:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } { GtkLabel* label = GTK_LABEL( gtk_label_new( "Height:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } @@ -1031,8 +1031,8 @@ void DoNewPatchDlg( EPatchPrefab prefab, int minrows, int mincols, int defrows, #undef D_ITEM gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table, GTK_WIDGET( combo ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); width = GTK_COMBO_BOX( combo ); } @@ -1057,8 +1057,8 @@ void DoNewPatchDlg( EPatchPrefab prefab, int minrows, int mincols, int defrows, #undef D_ITEM gtk_widget_show( GTK_WIDGET( combo ) ); gtk_table_attach( table, GTK_WIDGET( combo ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); height = GTK_COMBO_BOX( combo ); } @@ -1069,8 +1069,8 @@ void DoNewPatchDlg( EPatchPrefab prefab, int minrows, int mincols, int defrows, gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _redisperseCheckBox ), FALSE ); gtk_widget_show( _redisperseCheckBox ); gtk_table_attach( table, _redisperseCheckBox, 0, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); redisperseCheckBox = _redisperseCheckBox; } @@ -1116,7 +1116,7 @@ void DoPatchDeformDlg(){ ModalDialog dialog; GtkWidget* deformW; - GtkWidget* rndY; + GtkWidget* rndY; GtkWidget* rndX; GtkWindow* window = create_dialog_window( MainFrame_getWindow(), "Patch deform", G_CALLBACK( dialog_delete_callback ), &dialog ); @@ -1134,8 +1134,8 @@ void DoPatchDeformDlg(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Max deform:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } // { @@ -1153,8 +1153,8 @@ void DoPatchDeformDlg(){ GtkWidget* spin = gtk_spin_button_new( adj, 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( table, spin, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( spin, 64, -1 ); gtk_spin_button_set_numeric( GTK_SPIN_BUTTON( spin ), TRUE ); @@ -1172,8 +1172,8 @@ void DoPatchDeformDlg(){ GtkHBox* _hbox = create_dialog_hbox( 4, 4 ); gtk_table_attach( table, GTK_WIDGET( _hbox ), 0, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_box_pack_start( GTK_BOX( _hbox ), GTK_WIDGET( _rndX ), TRUE, TRUE, 0 ); gtk_box_pack_start( GTK_BOX( _hbox ), GTK_WIDGET( _rndY ), TRUE, TRUE, 0 ); gtk_box_pack_start( GTK_BOX( _hbox ), GTK_WIDGET( _rndZ ), TRUE, TRUE, 0 ); @@ -1253,36 +1253,36 @@ EMessageBoxReturn DoCapDlg( ECapDialog* type ){ GtkImage* image = new_local_image( "cap_bevel.png" ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( table, GTK_WIDGET( image ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkImage* image = new_local_image( "cap_endcap.png" ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( table, GTK_WIDGET( image ), 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkImage* image = new_local_image( "cap_ibevel.png" ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( table, GTK_WIDGET( image ), 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkImage* image = new_local_image( "cap_iendcap.png" ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( table, GTK_WIDGET( image ), 0, 1, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkImage* image = new_local_image( "cap_cylinder.png" ); gtk_widget_show( GTK_WIDGET( image ) ); gtk_table_attach( table, GTK_WIDGET( image ), 0, 1, 4, 5, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } GtkRadioButton* group = 0; @@ -1290,8 +1290,8 @@ EMessageBoxReturn DoCapDlg( ECapDialog* type ){ GtkWidget* button = gtk_radio_button_new_with_label_from_widget( group, "Bevel" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); group = GTK_RADIO_BUTTON( button ); bevel = button; } @@ -1299,32 +1299,32 @@ EMessageBoxReturn DoCapDlg( ECapDialog* type ){ GtkWidget* button = gtk_radio_button_new_with_label_from_widget( group, "Endcap" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); endcap = button; } { GtkWidget* button = gtk_radio_button_new_with_label_from_widget( group, "Inverted Bevel" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); ibevel = button; } { GtkWidget* button = gtk_radio_button_new_with_label_from_widget( group, "Inverted Endcap" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 3, 4, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); iendcap = button; } { GtkWidget* button = gtk_radio_button_new_with_label_from_widget( group, "Cylinder" ); gtk_widget_show( button ); gtk_table_attach( table, button, 1, 2, 4, 5, - (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( 0 ), 0, 0 ); cylinder = button; } } @@ -1398,8 +1398,8 @@ void DoPatchThickenDlg(){ GtkLabel* label = GTK_LABEL( gtk_label_new( "Thickness:" ) ); gtk_widget_show( GTK_WIDGET( label ) ); gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); } // { @@ -1418,8 +1418,8 @@ void DoPatchThickenDlg(){ GtkWidget* spin = gtk_spin_button_new( adj, 1, 0 ); gtk_widget_show( spin ); gtk_table_attach( table, spin, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( spin, 48, -1 ); gtk_spin_button_set_numeric( GTK_SPIN_BUTTON( spin ), TRUE ); @@ -1431,8 +1431,8 @@ void DoPatchThickenDlg(){ gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _seamsCheckBox ), TRUE ); gtk_widget_show( _seamsCheckBox ); gtk_table_attach( table, _seamsCheckBox, 2, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); seamsW = _seamsCheckBox; } @@ -1450,17 +1450,17 @@ void DoPatchThickenDlg(){ // Pack the buttons into the table gtk_table_attach( table, _radNormals, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, _radX, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, _radY, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_table_attach( table, _radZ, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); radX = _radX; radY = _radY; radZ = _radZ; diff --git a/radiant/patchmodule.cpp b/radiant/patchmodule.cpp index b4785599..371ec8e7 100644 --- a/radiant/patchmodule.cpp +++ b/radiant/patchmodule.cpp @@ -73,33 +73,33 @@ void Patch_Destroy(){ class CommonPatchCreator : public PatchCreator { public: -void Patch_undoSave( scene::Node& patch ) const { - Node_getPatch( patch )->undoSave(); -} -void Patch_resize( scene::Node& patch, std::size_t width, std::size_t height ) const { - Node_getPatch( patch )->setDims( width, height ); -} -PatchControlMatrix Patch_getControlPoints( scene::Node& node ) const { - Patch& patch = *Node_getPatch( node ); - return PatchControlMatrix( patch.getHeight(), patch.getWidth(), patch.getControlPoints().data() ); -} -void Patch_controlPointsChanged( scene::Node& patch ) const { - return Node_getPatch( patch )->controlPointsChanged(); -} -const char* Patch_getShader( scene::Node& patch ) const { - return Node_getPatch( patch )->GetShader(); -} -void Patch_setShader( scene::Node& patch, const char* shader ) const { - Node_getPatch( patch )->SetShader( shader ); -} + void Patch_undoSave( scene::Node& patch ) const { + Node_getPatch( patch )->undoSave(); + } + void Patch_resize( scene::Node& patch, std::size_t width, std::size_t height ) const { + Node_getPatch( patch )->setDims( width, height ); + } + PatchControlMatrix Patch_getControlPoints( scene::Node& node ) const { + Patch& patch = *Node_getPatch( node ); + return PatchControlMatrix( patch.getHeight(), patch.getWidth(), patch.getControlPoints().data() ); + } + void Patch_controlPointsChanged( scene::Node& patch ) const { + return Node_getPatch( patch )->controlPointsChanged(); + } + const char* Patch_getShader( scene::Node& patch ) const { + return Node_getPatch( patch )->GetShader(); + } + void Patch_setShader( scene::Node& patch, const char* shader ) const { + Node_getPatch( patch )->SetShader( shader ); + } }; class Quake3PatchCreator : public CommonPatchCreator { public: -scene::Node& createPatch(){ - return ( new PatchNodeQuake3() )->node(); -} + scene::Node& createPatch(){ + return ( new PatchNodeQuake3() )->node(); + } }; Quake3PatchCreator g_Quake3PatchCreator; @@ -111,9 +111,9 @@ PatchCreator& GetQuake3PatchCreator(){ class Doom3PatchCreator : public CommonPatchCreator { public: -scene::Node& createPatch(){ - return ( new PatchNodeDoom3( true ) )->node(); -} + scene::Node& createPatch(){ + return ( new PatchNodeDoom3( true ) )->node(); + } }; Doom3PatchCreator g_Doom3PatchCreator; @@ -125,9 +125,9 @@ PatchCreator& GetDoom3PatchCreator(){ class Doom3PatchDef2Creator : public CommonPatchCreator { public: -scene::Node& createPatch(){ - return ( new PatchNodeDoom3() )->node(); -} + scene::Node& createPatch(){ + return ( new PatchNodeDoom3() )->node(); + } }; Doom3PatchDef2Creator g_Doom3PatchDef2Creator; @@ -152,23 +152,23 @@ class PatchDependencies : class PatchQuake3API : public TypeSystemRef { -PatchCreator* m_patchquake3; + PatchCreator* m_patchquake3; public: -typedef PatchCreator Type; -STRING_CONSTANT( Name, "quake3" ); + typedef PatchCreator Type; + STRING_CONSTANT( Name, "quake3" ); -PatchQuake3API(){ - Patch_Construct( ePatchTypeQuake3 ); + PatchQuake3API(){ + Patch_Construct( ePatchTypeQuake3 ); - m_patchquake3 = &GetQuake3PatchCreator(); - g_patchCreator = m_patchquake3; -} -~PatchQuake3API(){ - Patch_Destroy(); -} -PatchCreator* getTable(){ - return m_patchquake3; -} + m_patchquake3 = &GetQuake3PatchCreator(); + g_patchCreator = m_patchquake3; + } + ~PatchQuake3API(){ + Patch_Destroy(); + } + PatchCreator* getTable(){ + return m_patchquake3; + } }; typedef SingletonModule PatchQuake3Module; @@ -179,22 +179,22 @@ StaticRegisterModule staticRegisterPatchQuake3( StaticPatchQuake3Module::instanc class PatchDoom3API : public TypeSystemRef { -PatchCreator* m_patchdoom3; + PatchCreator* m_patchdoom3; public: -typedef PatchCreator Type; -STRING_CONSTANT( Name, "doom3" ); + typedef PatchCreator Type; + STRING_CONSTANT( Name, "doom3" ); -PatchDoom3API(){ - Patch_Construct( ePatchTypeDoom3 ); + PatchDoom3API(){ + Patch_Construct( ePatchTypeDoom3 ); - m_patchdoom3 = &GetDoom3PatchCreator(); -} -~PatchDoom3API(){ - Patch_Destroy(); -} -PatchCreator* getTable(){ - return m_patchdoom3; -} + m_patchdoom3 = &GetDoom3PatchCreator(); + } + ~PatchDoom3API(){ + Patch_Destroy(); + } + PatchCreator* getTable(){ + return m_patchdoom3; + } }; typedef SingletonModule PatchDoom3Module; @@ -204,23 +204,23 @@ StaticRegisterModule staticRegisterPatchDoom3( StaticPatchDoom3Module::instance( class PatchDef2Doom3API : public TypeSystemRef { -PatchCreator* m_patchdef2doom3; + PatchCreator* m_patchdef2doom3; public: -typedef PatchCreator Type; -STRING_CONSTANT( Name, "def2doom3" ); + typedef PatchCreator Type; + STRING_CONSTANT( Name, "def2doom3" ); -PatchDef2Doom3API(){ - Patch_Construct( ePatchTypeDoom3 ); + PatchDef2Doom3API(){ + Patch_Construct( ePatchTypeDoom3 ); - m_patchdef2doom3 = &GetDoom3PatchDef2Creator(); - g_patchCreator = m_patchdef2doom3; -} -~PatchDef2Doom3API(){ - Patch_Destroy(); -} -PatchCreator* getTable(){ - return m_patchdef2doom3; -} + m_patchdef2doom3 = &GetDoom3PatchDef2Creator(); + g_patchCreator = m_patchdef2doom3; + } + ~PatchDef2Doom3API(){ + Patch_Destroy(); + } + PatchCreator* getTable(){ + return m_patchdef2doom3; + } }; typedef SingletonModule PatchDef2Doom3Module; diff --git a/radiant/plugin.cpp b/radiant/plugin.cpp index 8b2d48d1..987fdbc0 100644 --- a/radiant/plugin.cpp +++ b/radiant/plugin.cpp @@ -114,58 +114,58 @@ Vector3 Camera_getOrigin(){ class RadiantCoreAPI { -_QERFuncTable_1 m_radiantcore; + _QERFuncTable_1 m_radiantcore; public: -typedef _QERFuncTable_1 Type; -STRING_CONSTANT( Name, "*" ); + typedef _QERFuncTable_1 Type; + STRING_CONSTANT( Name, "*" ); -RadiantCoreAPI(){ - m_radiantcore.getEnginePath = &EnginePath_get; - m_radiantcore.getLocalRcPath = &LocalRcPath_get; - m_radiantcore.getAppPath = &AppPath_get; - m_radiantcore.getGameToolsPath = &GameToolsPath_get; - m_radiantcore.getSettingsPath = &SettingsPath_get; - m_radiantcore.getMapsPath = &getMapsPath; + RadiantCoreAPI(){ + m_radiantcore.getEnginePath = &EnginePath_get; + m_radiantcore.getLocalRcPath = &LocalRcPath_get; + m_radiantcore.getAppPath = &AppPath_get; + m_radiantcore.getGameToolsPath = &GameToolsPath_get; + m_radiantcore.getSettingsPath = &SettingsPath_get; + m_radiantcore.getMapsPath = &getMapsPath; - m_radiantcore.getGameName = &gamename_get; - m_radiantcore.getGameMode = &gamemode_get; + m_radiantcore.getGameName = &gamename_get; + m_radiantcore.getGameMode = &gamemode_get; - m_radiantcore.getMapName = &getMapName; - m_radiantcore.getMapWorldEntity = getMapWorldEntity; - m_radiantcore.getGridSize = GetGridSize; + m_radiantcore.getMapName = &getMapName; + m_radiantcore.getMapWorldEntity = getMapWorldEntity; + m_radiantcore.getGridSize = GetGridSize; - m_radiantcore.getGameDescriptionKeyValue = &GameDescription_getKeyValue; - m_radiantcore.getRequiredGameDescriptionKeyValue = &GameDescription_getRequiredKeyValue; + m_radiantcore.getGameDescriptionKeyValue = &GameDescription_getKeyValue; + m_radiantcore.getRequiredGameDescriptionKeyValue = &GameDescription_getRequiredKeyValue; - m_radiantcore.attachGameToolsPathObserver = Radiant_attachGameToolsPathObserver; - m_radiantcore.detachGameToolsPathObserver = Radiant_detachGameToolsPathObserver; - m_radiantcore.attachEnginePathObserver = Radiant_attachEnginePathObserver; - m_radiantcore.detachEnginePathObserver = Radiant_detachEnginePathObserver; - m_radiantcore.attachGameNameObserver = Radiant_attachGameNameObserver; - m_radiantcore.detachGameNameObserver = Radiant_detachGameNameObserver; - m_radiantcore.attachGameModeObserver = Radiant_attachGameModeObserver; - m_radiantcore.detachGameModeObserver = Radiant_detachGameModeObserver; + m_radiantcore.attachGameToolsPathObserver = Radiant_attachGameToolsPathObserver; + m_radiantcore.detachGameToolsPathObserver = Radiant_detachGameToolsPathObserver; + m_radiantcore.attachEnginePathObserver = Radiant_attachEnginePathObserver; + m_radiantcore.detachEnginePathObserver = Radiant_detachEnginePathObserver; + m_radiantcore.attachGameNameObserver = Radiant_attachGameNameObserver; + m_radiantcore.detachGameNameObserver = Radiant_detachGameNameObserver; + m_radiantcore.attachGameModeObserver = Radiant_attachGameModeObserver; + m_radiantcore.detachGameModeObserver = Radiant_detachGameModeObserver; - m_radiantcore.XYWindowDestroyed_connect = XYWindowDestroyed_connect; - m_radiantcore.XYWindowDestroyed_disconnect = XYWindowDestroyed_disconnect; - m_radiantcore.XYWindowMouseDown_connect = XYWindowMouseDown_connect; - m_radiantcore.XYWindowMouseDown_disconnect = XYWindowMouseDown_disconnect; - m_radiantcore.XYWindow_getViewType = XYWindow_getViewType; - m_radiantcore.XYWindow_windowToWorld = XYWindow_windowToWorld; + m_radiantcore.XYWindowDestroyed_connect = XYWindowDestroyed_connect; + m_radiantcore.XYWindowDestroyed_disconnect = XYWindowDestroyed_disconnect; + m_radiantcore.XYWindowMouseDown_connect = XYWindowMouseDown_connect; + m_radiantcore.XYWindowMouseDown_disconnect = XYWindowMouseDown_disconnect; + m_radiantcore.XYWindow_getViewType = XYWindow_getViewType; + m_radiantcore.XYWindow_windowToWorld = XYWindow_windowToWorld; - m_radiantcore.Camera_getOrigin = Camera_getOrigin; + m_radiantcore.Camera_getOrigin = Camera_getOrigin; - m_radiantcore.TextureBrowser_getSelectedShader = TextureBrowser_GetSelectedShader; + m_radiantcore.TextureBrowser_getSelectedShader = TextureBrowser_GetSelectedShader; - m_radiantcore.m_pfnMessageBox = >k_MessageBox; - m_radiantcore.m_pfnFileDialog = &file_dialog; - m_radiantcore.m_pfnColorDialog = &color_dialog; - m_radiantcore.m_pfnDirDialog = &dir_dialog; - m_radiantcore.m_pfnNewImage = &new_plugin_image; -} -_QERFuncTable_1* getTable(){ - return &m_radiantcore; -} + m_radiantcore.m_pfnMessageBox = >k_MessageBox; + m_radiantcore.m_pfnFileDialog = &file_dialog; + m_radiantcore.m_pfnColorDialog = &color_dialog; + m_radiantcore.m_pfnDirDialog = &dir_dialog; + m_radiantcore.m_pfnNewImage = &new_plugin_image; + } + _QERFuncTable_1* getTable(){ + return &m_radiantcore; + } }; typedef SingletonModule RadiantCoreModule; @@ -190,103 +190,103 @@ class RadiantDependencies : public GlobalScripLibModuleRef, public GlobalNamespaceModuleRef { -ImageModulesRef m_image_modules; -MapModulesRef m_map_modules; -ToolbarModulesRef m_toolbar_modules; -PluginModulesRef m_plugin_modules; + ImageModulesRef m_image_modules; + MapModulesRef m_map_modules; + ToolbarModulesRef m_toolbar_modules; + PluginModulesRef m_plugin_modules; public: -RadiantDependencies() : - GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), - GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ), - GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), - GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), - m_image_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "texturetypes" ) ), - m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) ), - m_toolbar_modules( "*" ), - m_plugin_modules( "*" ){ -} + RadiantDependencies() : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ), + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ), + m_image_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "texturetypes" ) ), + m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) ), + m_toolbar_modules( "*" ), + m_plugin_modules( "*" ){ + } -ImageModules& getImageModules(){ - return m_image_modules.get(); -} -MapModules& getMapModules(){ - return m_map_modules.get(); -} -ToolbarModules& getToolbarModules(){ - return m_toolbar_modules.get(); -} -PluginModules& getPluginModules(){ - return m_plugin_modules.get(); -} + ImageModules& getImageModules(){ + return m_image_modules.get(); + } + MapModules& getMapModules(){ + return m_map_modules.get(); + } + ToolbarModules& getToolbarModules(){ + return m_toolbar_modules.get(); + } + PluginModules& getPluginModules(){ + return m_plugin_modules.get(); + } }; class Radiant : public TypeSystemRef { public: -Radiant(){ - Preferences_Init(); + Radiant(){ + Preferences_Init(); - GlobalFiletypes().addType( "sound", "wav", filetype_t( "PCM sound files", "*.wav" ) ); + GlobalFiletypes().addType( "sound", "wav", filetype_t( "PCM sound files", "*.wav" ) ); - Selection_construct(); - HomePaths_Construct(); - VFS_Construct(); - Grid_construct(); - MultiMon_Construct(); - MRU_Construct(); - Pointfile_Construct(); - BuildMenu_Construct(); - Map_Construct(); - EntityList_Construct(); - MainFrame_Construct(); - GroupDialog_Construct(); - SurfaceInspector_Construct(); - PatchInspector_Construct(); - CamWnd_Construct(); - XYWindow_Construct(); - BuildMonitor_Construct(); - TextureBrowser_Construct(); - ModelBrowser_Construct(); - Entity_Construct(); - Autosave_Construct(); - EntityInspector_construct(); - FindTextureDialog_Construct(); - NullModel_construct(); - MapRoot_construct(); + Selection_construct(); + HomePaths_Construct(); + VFS_Construct(); + Grid_construct(); + MultiMon_Construct(); + MRU_Construct(); + Pointfile_Construct(); + BuildMenu_Construct(); + Map_Construct(); + EntityList_Construct(); + MainFrame_Construct(); + GroupDialog_Construct(); + SurfaceInspector_Construct(); + PatchInspector_Construct(); + CamWnd_Construct(); + XYWindow_Construct(); + BuildMonitor_Construct(); + TextureBrowser_Construct(); + ModelBrowser_Construct(); + Entity_Construct(); + Autosave_Construct(); + EntityInspector_construct(); + FindTextureDialog_Construct(); + NullModel_construct(); + MapRoot_construct(); - EnginePath_verify(); - EnginePath_Realise(); -} -~Radiant(){ - EnginePath_Unrealise(); + EnginePath_verify(); + EnginePath_Realise(); + } + ~Radiant(){ + EnginePath_Unrealise(); - MapRoot_destroy(); - NullModel_destroy(); - FindTextureDialog_Destroy(); - EntityInspector_destroy(); - Autosave_Destroy(); - Entity_Destroy(); - ModelBrowser_Destroy(); - TextureBrowser_Destroy(); - BuildMonitor_Destroy(); - XYWindow_Destroy(); - CamWnd_Destroy(); - PatchInspector_Destroy(); - SurfaceInspector_Destroy(); - GroupDialog_Destroy(); - MainFrame_Destroy(); - EntityList_Destroy(); - Map_Destroy(); - BuildMenu_Destroy(); - Pointfile_Destroy(); - MRU_Destroy(); - MultiMon_Destroy(); - Grid_destroy(); - VFS_Destroy(); - HomePaths_Destroy(); - Selection_destroy(); -} + MapRoot_destroy(); + NullModel_destroy(); + FindTextureDialog_Destroy(); + EntityInspector_destroy(); + Autosave_Destroy(); + Entity_Destroy(); + ModelBrowser_Destroy(); + TextureBrowser_Destroy(); + BuildMonitor_Destroy(); + XYWindow_Destroy(); + CamWnd_Destroy(); + PatchInspector_Destroy(); + SurfaceInspector_Destroy(); + GroupDialog_Destroy(); + MainFrame_Destroy(); + EntityList_Destroy(); + Map_Destroy(); + BuildMenu_Destroy(); + Pointfile_Destroy(); + MRU_Destroy(); + MultiMon_Destroy(); + Grid_destroy(); + VFS_Destroy(); + HomePaths_Destroy(); + Selection_destroy(); + } }; namespace diff --git a/radiant/pluginapi.cpp b/radiant/pluginapi.cpp index c44ab4e6..a5fb3248 100644 --- a/radiant/pluginapi.cpp +++ b/radiant/pluginapi.cpp @@ -60,19 +60,19 @@ void QERApp_GetCamWindowExtents( int *x, int *y, int *width, int *height ){ class CameraAPI { -_QERCameraTable m_camera; + _QERCameraTable m_camera; public: -typedef _QERCameraTable Type; -STRING_CONSTANT( Name, "*" ); + typedef _QERCameraTable Type; + STRING_CONSTANT( Name, "*" ); -CameraAPI(){ - m_camera.m_pfnGetCamera = &QERApp_GetCamera; - m_camera.m_pfnSetCamera = &QERApp_SetCamera; - m_camera.m_pfnGetCamWindowExtents = &QERApp_GetCamWindowExtents; -} -_QERCameraTable* getTable(){ - return &m_camera; -} + CameraAPI(){ + m_camera.m_pfnGetCamera = &QERApp_GetCamera; + m_camera.m_pfnSetCamera = &QERApp_SetCamera; + m_camera.m_pfnGetCamWindowExtents = &QERApp_GetCamWindowExtents; + } + _QERCameraTable* getTable(){ + return &m_camera; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/pluginmanager.cpp b/radiant/pluginmanager.cpp index 5e74eb02..5b9897cb 100644 --- a/radiant/pluginmanager.cpp +++ b/radiant/pluginmanager.cpp @@ -46,41 +46,41 @@ /* plugin manager --------------------------------------- */ class CPluginSlot : public IPlugIn { -CopiedString m_menu_name; -const _QERPluginTable *mpTable; -std::list m_CommandStrings; -std::list m_CommandTitleStrings; + CopiedString m_menu_name; + const _QERPluginTable *mpTable; + std::list m_CommandStrings; + std::list m_CommandTitleStrings; -std::list m_globalCommandNames; -class PluginCaller -{ - CPluginSlot* slot; - const char* name; -public: - PluginCaller( CPluginSlot* slot_, const char* name_ ) : slot( slot_ ), name( name_ ){ - } - void operator()(){ - slot->Dispatch( name ); - } -}; -std::list m_callbacks; + std::list m_globalCommandNames; + class PluginCaller + { + CPluginSlot* slot; + const char* name; + public: + PluginCaller( CPluginSlot* slot_, const char* name_ ) : slot( slot_ ), name( name_ ){ + } + void operator()(){ + slot->Dispatch( name ); + } + }; + std::list m_callbacks; public: -/*! - build directly from a SYN_PROVIDE interface - */ -CPluginSlot( GtkWidget* main_window, const char* name, const _QERPluginTable& table ); -/*! - dispatching a command by name to the plugin - */ -void Dispatch( const char *p ); + /*! + build directly from a SYN_PROVIDE interface + */ + CPluginSlot( GtkWidget* main_window, const char* name, const _QERPluginTable& table ); + /*! + dispatching a command by name to the plugin + */ + void Dispatch( const char *p ); // IPlugIn ------------------------------------------------------------ -const char* getMenuName(); -std::size_t getCommandCount(); -const char* getCommand( std::size_t n ); -const char* getCommandTitle( std::size_t n ); -const char* getGlobalCommand( std::size_t n ); + const char* getMenuName(); + std::size_t getCommandCount(); + const char* getCommand( std::size_t n ); + const char* getCommandTitle( std::size_t n ); + const char* getGlobalCommand( std::size_t n ); }; CPluginSlot::CPluginSlot( GtkWidget* main_window, const char* name, const _QERPluginTable& table ){ @@ -179,15 +179,15 @@ void CPluginSlot::Dispatch( const char *p ){ class CPluginSlots { -std::list mSlots; + std::list mSlots; public: -virtual ~CPluginSlots(); + virtual ~CPluginSlots(); -void AddPluginSlot( GtkWidget* main_window, const char* name, const _QERPluginTable& table ){ - mSlots.push_back( new CPluginSlot( main_window, name, table ) ); -} + void AddPluginSlot( GtkWidget* main_window, const char* name, const _QERPluginTable& table ){ + mSlots.push_back( new CPluginSlot( main_window, name, table ) ); + } -void PopulateMenu( PluginsVisitor& menu ); + void PopulateMenu( PluginsVisitor& menu ); }; CPluginSlots::~CPluginSlots(){ @@ -213,15 +213,15 @@ CPluginSlots g_plugin_slots; void FillPluginSlots( CPluginSlots& slots, GtkWidget* main_window ){ class AddPluginVisitor : public PluginModules::Visitor { - CPluginSlots& m_slots; - GtkWidget* m_main_window; -public: - AddPluginVisitor( CPluginSlots& slots, GtkWidget* main_window ) - : m_slots( slots ), m_main_window( main_window ){ - } - void visit( const char* name, const _QERPluginTable& table ) const { - m_slots.AddPluginSlot( m_main_window, name, table ); - } + CPluginSlots& m_slots; + GtkWidget* m_main_window; + public: + AddPluginVisitor( CPluginSlots& slots, GtkWidget* main_window ) + : m_slots( slots ), m_main_window( main_window ){ + } + void visit( const char* name, const _QERPluginTable& table ) const { + m_slots.AddPluginSlot( m_main_window, name, table ); + } } visitor( slots, main_window ); Radiant_getPluginModules().foreachModule( visitor ); diff --git a/radiant/pluginmanager.h b/radiant/pluginmanager.h index 03db4483..cae30094 100644 --- a/radiant/pluginmanager.h +++ b/radiant/pluginmanager.h @@ -34,28 +34,28 @@ typedef struct _GtkWidget GtkWidget; class IPlugIn { public: -IPlugIn() { } -virtual ~IPlugIn() { } + IPlugIn() { } + virtual ~IPlugIn() { } -virtual const char* getMenuName() = 0; -virtual std::size_t getCommandCount() = 0; -virtual const char* getCommand( std::size_t ) = 0; -virtual const char* getCommandTitle( std::size_t ) = 0; -virtual const char* getGlobalCommand( std::size_t ) = 0; + virtual const char* getMenuName() = 0; + virtual std::size_t getCommandCount() = 0; + virtual const char* getCommand( std::size_t ) = 0; + virtual const char* getCommandTitle( std::size_t ) = 0; + virtual const char* getGlobalCommand( std::size_t ) = 0; }; class PluginsVisitor { public: -virtual void visit( IPlugIn& plugin ) = 0; + virtual void visit( IPlugIn& plugin ) = 0; }; class CPlugInManager { public: -void Init( GtkWidget* main_window ); -void constructMenu( PluginsVisitor& menu ); -void Shutdown(); + void Init( GtkWidget* main_window ); + void constructMenu( PluginsVisitor& menu ); + void Shutdown(); }; CPlugInManager& GetPlugInMgr(); @@ -71,8 +71,8 @@ inline bool plugin_menu_separator( const char* text ){ } inline bool plugin_menu_special( const char* text ){ return plugin_menu_separator( text ) - || plugin_submenu_in( text ) - || plugin_submenu_out( text ); + || plugin_submenu_in( text ) + || plugin_submenu_out( text ); } #endif diff --git a/radiant/pluginmenu.cpp b/radiant/pluginmenu.cpp index a8aad292..68bf1a54 100644 --- a/radiant/pluginmenu.cpp +++ b/radiant/pluginmenu.cpp @@ -99,13 +99,13 @@ GtkMenuItem* g_plugins_menu_separator = 0; void PluginsMenu_populate(){ class PluginsMenuConstructor : public PluginsVisitor { - GtkMenu* m_menu; -public: - PluginsMenuConstructor( GtkMenu* menu ) : m_menu( menu ){ - } - void visit( IPlugIn& plugin ){ - PlugInMenu_Add( m_menu, &plugin ); - } + GtkMenu* m_menu; + public: + PluginsMenuConstructor( GtkMenu* menu ) : m_menu( menu ){ + } + void visit( IPlugIn& plugin ){ + PlugInMenu_Add( m_menu, &plugin ); + } }; PluginsMenuConstructor constructor( g_plugins_menu ); diff --git a/radiant/plugintoolbar.cpp b/radiant/plugintoolbar.cpp index ae31bda9..a98f4942 100644 --- a/radiant/plugintoolbar.cpp +++ b/radiant/plugintoolbar.cpp @@ -110,18 +110,18 @@ GtkToolbar* g_plugin_toolbar = 0; void PluginToolbar_populate(){ class AddToolbarItemVisitor : public ToolbarModules::Visitor { - GtkToolbar* m_toolbar; -public: - AddToolbarItemVisitor( GtkToolbar* toolbar ) - : m_toolbar( toolbar ){ - } - void visit( const char* name, const _QERPlugToolbarTable& table ) const { - const std::size_t count = table.m_pfnToolbarButtonCount(); - for ( std::size_t i = 0; i < count; ++i ) - { - PlugInToolbar_AddButton( m_toolbar, table.m_pfnGetToolbarButton( i ) ); + GtkToolbar* m_toolbar; + public: + AddToolbarItemVisitor( GtkToolbar* toolbar ) + : m_toolbar( toolbar ){ + } + void visit( const char* name, const _QERPlugToolbarTable& table ) const { + const std::size_t count = table.m_pfnToolbarButtonCount(); + for ( std::size_t i = 0; i < count; ++i ) + { + PlugInToolbar_AddButton( m_toolbar, table.m_pfnGetToolbarButton( i ) ); + } } - } } visitor( g_plugin_toolbar ); diff --git a/radiant/points.cpp b/radiant/points.cpp index bb47fbf3..d60c84a0 100644 --- a/radiant/points.cpp +++ b/radiant/points.cpp @@ -55,81 +55,81 @@ void Pointfile_Parse( CPointfile& pointfile ); class CPointfile : public ISAXHandler, public Renderable, public OpenGLRenderable { -enum -{ - MAX_POINTFILE = 8192, -}; -Vector3 s_pointvecs[MAX_POINTFILE]; -std::size_t s_num_points; -int m_displaylist; -static Shader* m_renderstate; -StringOutputStream m_characters; + enum + { + MAX_POINTFILE = 8192, + }; + Vector3 s_pointvecs[MAX_POINTFILE]; + std::size_t s_num_points; + int m_displaylist; + static Shader* m_renderstate; + StringOutputStream m_characters; public: -CPointfile(){ -} -~CPointfile(){ -} -void Init(); -void PushPoint( const Vector3& v ); -void GenerateDisplayList(); + CPointfile(){ + } + ~CPointfile(){ + } + void Init(); + void PushPoint( const Vector3& v ); + void GenerateDisplayList(); // SAX interface -void Release(){ - // blank because not heap-allocated -} -void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); -void saxEndElement( message_info_t *ctx, const xmlChar *name ); -void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); -const char* getName(); + void Release(){ + // blank because not heap-allocated + } + void saxStartElement( message_info_t *ctx, const xmlChar *name, const xmlChar **attrs ); + void saxEndElement( message_info_t *ctx, const xmlChar *name ); + void saxCharacters( message_info_t *ctx, const xmlChar *ch, int len ); + const char* getName(); -typedef const Vector3* const_iterator; + typedef const Vector3* const_iterator; -const_iterator begin() const { - return &s_pointvecs[0]; -} -const_iterator end() const { - return &s_pointvecs[s_num_points]; -} + const_iterator begin() const { + return &s_pointvecs[0]; + } + const_iterator end() const { + return &s_pointvecs[s_num_points]; + } -bool shown() const { - return m_displaylist != 0; -} -void show( bool show ){ - if ( show && !shown() ) { - Pointfile_Parse( *this ); - if( s_num_points > 0 ){ - GenerateDisplayList(); + bool shown() const { + return m_displaylist != 0; + } + void show( bool show ){ + if ( show && !shown() ) { + Pointfile_Parse( *this ); + if( s_num_points > 0 ){ + GenerateDisplayList(); + SceneChangeNotify(); + } + } + else if ( !show && shown() ) { + glDeleteLists( m_displaylist, 1 ); + m_displaylist = 0; SceneChangeNotify(); } } - else if ( !show && shown() ) { - glDeleteLists( m_displaylist, 1 ); - m_displaylist = 0; - SceneChangeNotify(); + + void render( RenderStateFlags state ) const { + glCallList( m_displaylist ); } -} -void render( RenderStateFlags state ) const { - glCallList( m_displaylist ); -} - -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { - if ( shown() ) { - renderer.SetState( m_renderstate, Renderer::eWireframeOnly ); - renderer.SetState( m_renderstate, Renderer::eFullMaterials ); - renderer.addRenderable( *this, g_matrix4_identity ); + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if ( shown() ) { + renderer.SetState( m_renderstate, Renderer::eWireframeOnly ); + renderer.SetState( m_renderstate, Renderer::eFullMaterials ); + renderer.addRenderable( *this, g_matrix4_identity ); + } + } + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); } -} -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} -static void constructStatic(){ - m_renderstate = GlobalShaderCache().capture( "$POINTFILE" ); -} + static void constructStatic(){ + m_renderstate = GlobalShaderCache().capture( "$POINTFILE" ); + } -static void destroyStatic(){ - GlobalShaderCache().release( "$POINTFILE" ); -} + static void destroyStatic(){ + GlobalShaderCache().release( "$POINTFILE" ); + } }; Shader* CPointfile::m_renderstate = 0; diff --git a/radiant/preferencedictionary.h b/radiant/preferencedictionary.h index ce3f7686..62d2c442 100644 --- a/radiant/preferencedictionary.h +++ b/radiant/preferencedictionary.h @@ -31,61 +31,61 @@ class PreferenceDictionary : public PreferenceSystem { -class PreferenceEntry -{ -StringImportCallback m_importer; -StringExportCallback m_exporter; -public: -PreferenceEntry( const StringImportCallback& importer, const StringExportCallback& exporter ) - : m_importer( importer ), m_exporter( exporter ){ -} -void importString( const char* string ){ - m_importer( string ); -} -void exportString( const StringImportCallback& importer ){ - m_exporter( importer ); -} -}; - -typedef std::map PreferenceEntries; -PreferenceEntries m_preferences; - -typedef std::map PreferenceCache; -PreferenceCache m_cache; - -public: -typedef PreferenceEntries::iterator iterator; - -iterator begin(){ - return m_preferences.begin(); -} -iterator end(){ - return m_preferences.end(); -} -iterator find( const char* name ){ - return m_preferences.find( name ); -} - -void registerPreference( const char* name, const StringImportCallback& importer, const StringExportCallback& exporter ){ - m_preferences.insert( PreferenceEntries::value_type( name, PreferenceEntry( importer, exporter ) ) ); - PreferenceCache::iterator i = m_cache.find( name ); - if ( i != m_cache.end() ) { - importer( ( *i ).second.c_str() ); - m_cache.erase( i ); - } -} - -void importPref( const char* name, const char* value ){ - PreferenceEntries::iterator i = m_preferences.find( name ); - if ( i != m_preferences.end() ) { - ( *i ).second.importString( value ); - } - else + class PreferenceEntry { - m_cache.erase( name ); - m_cache.insert( PreferenceCache::value_type( name, value ) ); + StringImportCallback m_importer; + StringExportCallback m_exporter; + public: + PreferenceEntry( const StringImportCallback& importer, const StringExportCallback& exporter ) + : m_importer( importer ), m_exporter( exporter ){ + } + void importString( const char* string ){ + m_importer( string ); + } + void exportString( const StringImportCallback& importer ){ + m_exporter( importer ); + } + }; + + typedef std::map PreferenceEntries; + PreferenceEntries m_preferences; + + typedef std::map PreferenceCache; + PreferenceCache m_cache; + +public: + typedef PreferenceEntries::iterator iterator; + + iterator begin(){ + return m_preferences.begin(); + } + iterator end(){ + return m_preferences.end(); + } + iterator find( const char* name ){ + return m_preferences.find( name ); + } + + void registerPreference( const char* name, const StringImportCallback& importer, const StringExportCallback& exporter ){ + m_preferences.insert( PreferenceEntries::value_type( name, PreferenceEntry( importer, exporter ) ) ); + PreferenceCache::iterator i = m_cache.find( name ); + if ( i != m_cache.end() ) { + importer( ( *i ).second.c_str() ); + m_cache.erase( i ); + } + } + + void importPref( const char* name, const char* value ){ + PreferenceEntries::iterator i = m_preferences.find( name ); + if ( i != m_preferences.end() ) { + ( *i ).second.importString( value ); + } + else + { + m_cache.erase( name ); + m_cache.insert( PreferenceCache::value_type( name, value ) ); + } } -} }; inline void XMLPreference_importString( XMLImporter& importer, const char* value ){ @@ -95,170 +95,170 @@ typedef ReferenceCaller1 X class XMLPreferenceDictionaryExporter : public XMLExporter { -class XMLQPrefElement : public XMLElement -{ -const char* m_version; -public: -XMLQPrefElement( const char* version ) : m_version( version ){ -} -const char* name() const { - return "qpref"; -} -const char* attribute( const char* name ) const { - if ( string_equal( name, "version" ) ) { - return m_version; - } - return ""; -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - visitor.visit( "version", m_version ); -} -}; - -class XMLPreferenceElement : public XMLElement -{ -const char* m_name; -public: -XMLPreferenceElement( const char* name ) - : m_name( name ){ -} -const char* name() const { - return "epair"; -} -const char* attribute( const char* name ) const { - if ( string_equal( name, "name" ) ) { - return m_name; - } - return ""; -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - visitor.visit( "name", m_name ); -} -}; - -typedef PreferenceDictionary PreferenceEntries; -PreferenceEntries& m_preferences; -const char* m_version; -public: -XMLPreferenceDictionaryExporter( PreferenceDictionary& preferences, const char* version ) - : m_preferences( preferences ), m_version( version ){ -} - -void exportXML( XMLImporter& importer ){ - importer.write( "\n", 1 ); - - XMLQPrefElement qpref_element( m_version ); - importer.pushElement( qpref_element ); - importer.write( "\n", 1 ); - - for ( PreferenceEntries::iterator i = m_preferences.begin(); i != m_preferences.end(); ++i ) + class XMLQPrefElement : public XMLElement { - XMLPreferenceElement epair_element( ( *i ).first.c_str() ); + const char* m_version; + public: + XMLQPrefElement( const char* version ) : m_version( version ){ + } + const char* name() const { + return "qpref"; + } + const char* attribute( const char* name ) const { + if ( string_equal( name, "version" ) ) { + return m_version; + } + return ""; + } + void forEachAttribute( XMLAttrVisitor& visitor ) const { + visitor.visit( "version", m_version ); + } + }; - importer.pushElement( epair_element ); + class XMLPreferenceElement : public XMLElement + { + const char* m_name; + public: + XMLPreferenceElement( const char* name ) + : m_name( name ){ + } + const char* name() const { + return "epair"; + } + const char* attribute( const char* name ) const { + if ( string_equal( name, "name" ) ) { + return m_name; + } + return ""; + } + void forEachAttribute( XMLAttrVisitor& visitor ) const { + visitor.visit( "name", m_name ); + } + }; - ( *i ).second.exportString( XMLPreferenceImportStringCaller( importer ) ); + typedef PreferenceDictionary PreferenceEntries; + PreferenceEntries& m_preferences; + const char* m_version; +public: + XMLPreferenceDictionaryExporter( PreferenceDictionary& preferences, const char* version ) + : m_preferences( preferences ), m_version( version ){ + } - importer.popElement( epair_element.name() ); + void exportXML( XMLImporter& importer ){ + importer.write( "\n", 1 ); + + XMLQPrefElement qpref_element( m_version ); + importer.pushElement( qpref_element ); + importer.write( "\n", 1 ); + + for ( PreferenceEntries::iterator i = m_preferences.begin(); i != m_preferences.end(); ++i ) + { + XMLPreferenceElement epair_element( ( *i ).first.c_str() ); + + importer.pushElement( epair_element ); + + ( *i ).second.exportString( XMLPreferenceImportStringCaller( importer ) ); + + importer.popElement( epair_element.name() ); + importer.write( "\n", 1 ); + } + + importer.popElement( qpref_element.name() ); importer.write( "\n", 1 ); } - - importer.popElement( qpref_element.name() ); - importer.write( "\n", 1 ); -} }; class XMLPreferenceDictionaryImporter : public XMLImporter { -struct xml_state_t -{ - enum ETag + struct xml_state_t { - tag_qpref, - tag_qpref_ignore, - tag_epair, - tag_epair_ignore + enum ETag + { + tag_qpref, + tag_qpref_ignore, + tag_epair, + tag_epair_ignore + }; + + xml_state_t( ETag tag ) + : m_tag( tag ){ + } + + ETag m_tag; + CopiedString m_name; + StringOutputStream m_ostream; }; - xml_state_t( ETag tag ) - : m_tag( tag ){ + typedef std::vector xml_stack_t; + xml_stack_t m_xml_stack; + + typedef PreferenceDictionary PreferenceEntries; + PreferenceEntries& m_preferences; + Version m_version; +public: + XMLPreferenceDictionaryImporter( PreferenceDictionary& preferences, const char* version ) + : m_preferences( preferences ), m_version( version_parse( version ) ){ } - ETag m_tag; - CopiedString m_name; - StringOutputStream m_ostream; -}; - -typedef std::vector xml_stack_t; -xml_stack_t m_xml_stack; - -typedef PreferenceDictionary PreferenceEntries; -PreferenceEntries& m_preferences; -Version m_version; -public: -XMLPreferenceDictionaryImporter( PreferenceDictionary& preferences, const char* version ) - : m_preferences( preferences ), m_version( version_parse( version ) ){ -} - -void pushElement( const XMLElement& element ){ - if ( m_xml_stack.empty() ) { - if ( string_equal( element.name(), "qpref" ) ) { - Version dataVersion( version_parse( element.attribute( "version" ) ) ); - if ( !version_compatible( m_version, dataVersion ) ) { - globalOutputStream() << "qpref import: data version " << dataVersion << " is not compatible with code version " << m_version << "\n"; - m_xml_stack.push_back( xml_state_t::tag_qpref_ignore ); + void pushElement( const XMLElement& element ){ + if ( m_xml_stack.empty() ) { + if ( string_equal( element.name(), "qpref" ) ) { + Version dataVersion( version_parse( element.attribute( "version" ) ) ); + if ( !version_compatible( m_version, dataVersion ) ) { + globalOutputStream() << "qpref import: data version " << dataVersion << " is not compatible with code version " << m_version << "\n"; + m_xml_stack.push_back( xml_state_t::tag_qpref_ignore ); + } + else + { + globalOutputStream() << "qpref import: data version " << dataVersion << " is compatible with code version " << m_version << "\n"; + m_xml_stack.push_back( xml_state_t::tag_qpref ); + } } else { - globalOutputStream() << "qpref import: data version " << dataVersion << " is compatible with code version " << m_version << "\n"; - m_xml_stack.push_back( xml_state_t::tag_qpref ); + // not valid } } else { - // not valid - } - } - else - { - switch ( m_xml_stack.back().m_tag ) - { - case xml_state_t::tag_qpref: - if ( string_equal( element.name(), "epair" ) ) { - m_xml_stack.push_back( xml_state_t::tag_epair ); - m_xml_stack.back().m_name = element.attribute( "name" ); - } - else + switch ( m_xml_stack.back().m_tag ) { + case xml_state_t::tag_qpref: + if ( string_equal( element.name(), "epair" ) ) { + m_xml_stack.push_back( xml_state_t::tag_epair ); + m_xml_stack.back().m_name = element.attribute( "name" ); + } + else + { + // not valid + } + break; + case xml_state_t::tag_qpref_ignore: + if ( string_equal( element.name(), "epair" ) ) { + m_xml_stack.push_back( xml_state_t::tag_epair_ignore ); + } + else + { + // not valid + } + break; + case xml_state_t::tag_epair: + case xml_state_t::tag_epair_ignore: // not valid + break; } - break; - case xml_state_t::tag_qpref_ignore: - if ( string_equal( element.name(), "epair" ) ) { - m_xml_stack.push_back( xml_state_t::tag_epair_ignore ); - } - else - { - // not valid - } - break; - case xml_state_t::tag_epair: - case xml_state_t::tag_epair_ignore: - // not valid - break; } - } -} -void popElement( const char* name ){ - if ( m_xml_stack.back().m_tag == xml_state_t::tag_epair ) { - m_preferences.importPref( m_xml_stack.back().m_name.c_str(), m_xml_stack.back().m_ostream.c_str() ); } - m_xml_stack.pop_back(); -} -std::size_t write( const char* buffer, std::size_t length ){ - return m_xml_stack.back().m_ostream.write( buffer, length ); -} + void popElement( const char* name ){ + if ( m_xml_stack.back().m_tag == xml_state_t::tag_epair ) { + m_preferences.importPref( m_xml_stack.back().m_name.c_str(), m_xml_stack.back().m_ostream.c_str() ); + } + m_xml_stack.pop_back(); + } + std::size_t write( const char* buffer, std::size_t length ){ + return m_xml_stack.back().m_ostream.write( buffer, length ); + } }; #endif diff --git a/radiant/preferences.cpp b/radiant/preferences.cpp index 55468acc..31bef256 100644 --- a/radiant/preferences.cpp +++ b/radiant/preferences.cpp @@ -183,8 +183,8 @@ bool Preferences_Save_Safe( PreferenceDictionary& preferences, const char* filen *( tmpName.end() - 1 ) = '\0'; return Preferences_Save( preferences, tmpName.data() ) - && ( !file_exists( filename ) || file_remove( filename ) ) - && file_move( tmpName.data(), filename ); + && ( !file_exists( filename ) || file_remove( filename ) ) + && file_move( tmpName.data(), filename ); } @@ -242,8 +242,8 @@ void CGameDialog::DoGameDialog(){ CGameDescription* CGameDialog::GameDescriptionForComboItem(){ return ( m_nComboSelect >= 0 && m_nComboSelect < static_cast( mGames.size() ) )? - *std::next( mGames.begin(), m_nComboSelect ) - : 0; // not found + *std::next( mGames.begin(), m_nComboSelect ) + : 0; // not found } void CGameDialog::GameFileAssign( int value ){ @@ -283,13 +283,13 @@ void CGameDialog::CreateGlobalFrame( PreferencesPage& page, bool global ){ games.push_back( ( *i )->getRequiredKeyValue( "name" ) ); } page.appendCombo( - "Select the game", - StringArrayRange( &( *games.begin() ), &( *games.end() ) ), - global? - IntImportCallback( MemberCaller1( *this ) ): - IntImportCallback( MemberCaller1( *this ) ), - ConstMemberCaller1( *this ) - ); + "Select the game", + StringArrayRange( &( *games.begin() ), &( *games.end() ) ), + global? + IntImportCallback( MemberCaller1( *this ) ): + IntImportCallback( MemberCaller1( *this ) ), + ConstMemberCaller1( *this ) + ); page.appendCheckBox( "Startup", "Show Global Preferences", m_bGamePrompt ); } @@ -310,29 +310,29 @@ GtkWindow* CGameDialog::BuildDialog(){ class LoadGameFile { -std::list& mGames; -const char* mPath; + std::list& mGames; + const char* mPath; public: -LoadGameFile( std::list& games, const char* path ) : mGames( games ), mPath( path ){ -} -void operator()( const char* name ) const { - if ( !extension_equal( path_get_extension( name ), "game" ) ) { - return; + LoadGameFile( std::list& games, const char* path ) : mGames( games ), mPath( path ){ } - StringOutputStream strPath( 256 ); - strPath << mPath << name; - globalOutputStream() << strPath.c_str() << '\n'; + void operator()( const char* name ) const { + if ( !extension_equal( path_get_extension( name ), "game" ) ) { + return; + } + StringOutputStream strPath( 256 ); + strPath << mPath << name; + globalOutputStream() << strPath.c_str() << '\n'; - xmlDocPtr pDoc = xmlParseFile( strPath.c_str() ); - if ( pDoc ) { - mGames.push_back( new CGameDescription( pDoc, name ) ); - xmlFreeDoc( pDoc ); + xmlDocPtr pDoc = xmlParseFile( strPath.c_str() ); + if ( pDoc ) { + mGames.push_back( new CGameDescription( pDoc, name ) ); + xmlFreeDoc( pDoc ); + } + else + { + globalErrorStream() << "XML parser failed on '" << strPath.c_str() << "'\n"; + } } - else - { - globalErrorStream() << "XML parser failed on '" << strPath.c_str() << "'\n"; - } -} }; void CGameDialog::ScanForGames(){ @@ -444,9 +444,10 @@ CGameDialog g_GamesDialog; static void OnButtonClean( GtkWidget *widget, gpointer data ){ // make sure this is what the user wants - if ( gtk_MessageBox( GTK_WIDGET( g_Preferences.GetWidget() ), "This will close Radiant and clean the corresponding registry entries.\n" - "Next time you start Radiant it will be good as new. Do you wish to continue?", - "Reset Registry", eMB_YESNO, eMB_ICONASTERISK ) == eIDYES ) { + if ( gtk_MessageBox( GTK_WIDGET( g_Preferences.GetWidget() ), + "This will close Radiant and clean the corresponding registry entries.\n" + "Next time you start Radiant it will be good as new. Do you wish to continue?", + "Reset Registry", eMB_YESNO, eMB_ICONASTERISK ) == eIDYES ) { PrefsDlg *dlg = (PrefsDlg*)data; dlg->EndModal( eIDCANCEL ); @@ -632,22 +633,22 @@ GtkWidget* PreferencePages_addPage( GtkWidget* notebook, const char* name ){ class PreferenceTreeGroup : public PreferenceGroup { -Dialog& m_dialog; -GtkWidget* m_notebook; -GtkTreeStore* m_store; -GtkTreeIter m_group; + Dialog& m_dialog; + GtkWidget* m_notebook; + GtkTreeStore* m_store; + GtkTreeIter m_group; public: -PreferenceTreeGroup( Dialog& dialog, GtkWidget* notebook, GtkTreeStore* store, GtkTreeIter group ) : - m_dialog( dialog ), - m_notebook( notebook ), - m_store( store ), - m_group( group ){ -} -PreferencesPage createPage( const char* treeName, const char* frameName ){ - GtkWidget* page = PreferencePages_addPage( m_notebook, frameName ); - PreferenceTree_appendPage( m_store, &m_group, treeName, page ); - return PreferencesPage( m_dialog, getVBox( page ) ); -} + PreferenceTreeGroup( Dialog& dialog, GtkWidget* notebook, GtkTreeStore* store, GtkTreeIter group ) : + m_dialog( dialog ), + m_notebook( notebook ), + m_store( store ), + m_group( group ){ + } + PreferencesPage createPage( const char* treeName, const char* frameName ){ + GtkWidget* page = PreferencePages_addPage( m_notebook, frameName ); + PreferenceTree_appendPage( m_store, &m_group, treeName, page ); + return PreferencesPage( m_dialog, getVBox( page ) ); + } }; #include @@ -839,17 +840,17 @@ PreferenceSystem& GetPreferenceSystem(){ class PreferenceSystemAPI { -PreferenceSystem* m_preferencesystem; + PreferenceSystem* m_preferencesystem; public: -typedef PreferenceSystem Type; -STRING_CONSTANT( Name, "*" ); + typedef PreferenceSystem Type; + STRING_CONSTANT( Name, "*" ); -PreferenceSystemAPI(){ - m_preferencesystem = &GetPreferenceSystem(); -} -PreferenceSystem* getTable(){ - return m_preferencesystem; -} + PreferenceSystemAPI(){ + m_preferencesystem = &GetPreferenceSystem(); + } + PreferenceSystem* getTable(){ + return m_preferencesystem; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/preferences.h b/radiant/preferences.h index 7d3aabb7..3242b787 100644 --- a/radiant/preferences.h +++ b/radiant/preferences.h @@ -38,80 +38,80 @@ void Widget_connectToggleDependency( GtkWidget* self, GtkWidget* toggleButton ); class PreferencesPage { -Dialog& m_dialog; -GtkWidget* m_vbox; + Dialog& m_dialog; + GtkWidget* m_vbox; public: -PreferencesPage( Dialog& dialog, GtkWidget* vbox ) : m_dialog( dialog ), m_vbox( vbox ){ -} -GtkWidget* appendCheckBox( const char* name, const char* flag, bool& data ){ - return m_dialog.addCheckBox( m_vbox, name, flag, data ); -} -GtkWidget* appendCheckBox( const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ){ - return m_dialog.addCheckBox( m_vbox, name, flag, importCallback, exportCallback ); -} -void appendCombo( const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ - m_dialog.addCombo( m_vbox, name, values, importCallback, exportCallback ); -} -void appendCombo( const char* name, int& data, StringArrayRange values ){ - m_dialog.addCombo( m_vbox, name, data, values ); -} -void appendSlider( const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ){ - m_dialog.addSlider( m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment ); -} -void appendSlider( const char* name, float& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ){ - m_dialog.addSlider( m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment ); -} -void appendRadio( const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ - m_dialog.addRadio( m_vbox, name, names, importCallback, exportCallback ); -} -void appendRadio( const char* name, int& data, StringArrayRange names ){ - m_dialog.addRadio( m_vbox, name, data, names ); -} -void appendRadioIcons( const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ - m_dialog.addRadioIcons( m_vbox, name, icons, importCallback, exportCallback ); -} -void appendRadioIcons( const char* name, int& data, StringArrayRange icons ){ - m_dialog.addRadioIcons( m_vbox, name, data, icons ); -} -GtkWidget* appendEntry( const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ - return m_dialog.addIntEntry( m_vbox, name, importCallback, exportCallback ); -} -GtkWidget* appendEntry( const char* name, int& data ){ - return m_dialog.addEntry( m_vbox, name, data ); -} -GtkWidget* appendEntry( const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ){ - return m_dialog.addSizeEntry( m_vbox, name, importCallback, exportCallback ); -} -GtkWidget* appendEntry( const char* name, std::size_t& data ){ - return m_dialog.addEntry( m_vbox, name, data ); -} -GtkWidget* appendEntry( const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ){ - return m_dialog.addFloatEntry( m_vbox, name, importCallback, exportCallback ); -} -GtkWidget* appendEntry( const char* name, float& data ){ - return m_dialog.addEntry( m_vbox, name, data ); -} -GtkWidget* appendEntry( const char* name, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ){ - return m_dialog.addTextEntry( m_vbox, name, importCallback, exportCallback ); -} -GtkWidget* appendEntry( const char* name, CopiedString& data ){ - return m_dialog.addEntry( m_vbox, name, data ); -} -GtkWidget* appendPathEntry( const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ){ - return m_dialog.addPathEntry( m_vbox, name, browse_directory, importCallback, exportCallback ); -} -GtkWidget* appendPathEntry( const char* name, CopiedString& data, bool directory ){ - return m_dialog.addPathEntry( m_vbox, name, data, directory ); -} -GtkWidget* appendSpinner( const char* name, int& data, double value, double lower, double upper ){ - return m_dialog.addSpinner( m_vbox, name, data, value, lower, upper ); -} -GtkWidget* appendSpinner( const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ - return m_dialog.addSpinner( m_vbox, name, value, lower, upper, importCallback, exportCallback ); -} -GtkWidget* appendSpinner( const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ){ - return m_dialog.addSpinner( m_vbox, name, value, lower, upper, importCallback, exportCallback ); -} + PreferencesPage( Dialog& dialog, GtkWidget* vbox ) : m_dialog( dialog ), m_vbox( vbox ){ + } + GtkWidget* appendCheckBox( const char* name, const char* flag, bool& data ){ + return m_dialog.addCheckBox( m_vbox, name, flag, data ); + } + GtkWidget* appendCheckBox( const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback ){ + return m_dialog.addCheckBox( m_vbox, name, flag, importCallback, exportCallback ); + } + void appendCombo( const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ + m_dialog.addCombo( m_vbox, name, values, importCallback, exportCallback ); + } + void appendCombo( const char* name, int& data, StringArrayRange values ){ + m_dialog.addCombo( m_vbox, name, data, values ); + } + void appendSlider( const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ){ + m_dialog.addSlider( m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment ); + } + void appendSlider( const char* name, float& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment ){ + m_dialog.addSlider( m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment ); + } + void appendRadio( const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ + m_dialog.addRadio( m_vbox, name, names, importCallback, exportCallback ); + } + void appendRadio( const char* name, int& data, StringArrayRange names ){ + m_dialog.addRadio( m_vbox, name, data, names ); + } + void appendRadioIcons( const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ + m_dialog.addRadioIcons( m_vbox, name, icons, importCallback, exportCallback ); + } + void appendRadioIcons( const char* name, int& data, StringArrayRange icons ){ + m_dialog.addRadioIcons( m_vbox, name, data, icons ); + } + GtkWidget* appendEntry( const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ + return m_dialog.addIntEntry( m_vbox, name, importCallback, exportCallback ); + } + GtkWidget* appendEntry( const char* name, int& data ){ + return m_dialog.addEntry( m_vbox, name, data ); + } + GtkWidget* appendEntry( const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback ){ + return m_dialog.addSizeEntry( m_vbox, name, importCallback, exportCallback ); + } + GtkWidget* appendEntry( const char* name, std::size_t& data ){ + return m_dialog.addEntry( m_vbox, name, data ); + } + GtkWidget* appendEntry( const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ){ + return m_dialog.addFloatEntry( m_vbox, name, importCallback, exportCallback ); + } + GtkWidget* appendEntry( const char* name, float& data ){ + return m_dialog.addEntry( m_vbox, name, data ); + } + GtkWidget* appendEntry( const char* name, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ){ + return m_dialog.addTextEntry( m_vbox, name, importCallback, exportCallback ); + } + GtkWidget* appendEntry( const char* name, CopiedString& data ){ + return m_dialog.addEntry( m_vbox, name, data ); + } + GtkWidget* appendPathEntry( const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback ){ + return m_dialog.addPathEntry( m_vbox, name, browse_directory, importCallback, exportCallback ); + } + GtkWidget* appendPathEntry( const char* name, CopiedString& data, bool directory ){ + return m_dialog.addPathEntry( m_vbox, name, data, directory ); + } + GtkWidget* appendSpinner( const char* name, int& data, double value, double lower, double upper ){ + return m_dialog.addSpinner( m_vbox, name, data, value, lower, upper ); + } + GtkWidget* appendSpinner( const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback ){ + return m_dialog.addSpinner( m_vbox, name, value, lower, upper, importCallback, exportCallback ); + } + GtkWidget* appendSpinner( const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback ){ + return m_dialog.addSpinner( m_vbox, name, value, lower, upper, importCallback, exportCallback ); + } }; typedef Callback1 PreferencesPageCallback; @@ -119,7 +119,7 @@ typedef Callback1 PreferencesPageCallback; class PreferenceGroup { public: -virtual PreferencesPage createPage( const char* treeName, const char* frameName ) = 0; + virtual PreferencesPage createPage( const char* treeName, const char* frameName ) = 0; }; typedef Callback1 PreferenceGroupCallback; @@ -139,21 +139,21 @@ template class LatchedValue { public: -Value m_value; -Value m_latched; -const char* m_description; + Value m_value; + Value m_latched; + const char* m_description; -LatchedValue( Value value, const char* description ) : m_value( value ), m_latched( value ), m_description( description ){ -} -void assign( Value value ){ // assign during initialization - m_value = m_latched = value; -} -void import( Value value ){ // import during runtime - m_latched = value; - if ( m_latched != m_value ) { - PreferencesDialog_restartRequired( m_description ); + LatchedValue( Value value, const char* description ) : m_value( value ), m_latched( value ), m_description( description ){ + } + void assign( Value value ){ // assign during initialization + m_value = m_latched = value; + } + void import( Value value ){ // import during runtime + m_latched = value; + if ( m_latched != m_value ) { + PreferencesDialog_restartRequired( m_description ); + } } -} }; typedef LatchedValue LatchedBool; @@ -183,34 +183,34 @@ inline R LatchedImportCaller( LatchedValue& latchedValue ){ */ class CGameDescription { -typedef std::map GameDescription; + typedef std::map GameDescription; public: -CopiedString mGameFile; ///< the .game file that describes this game -GameDescription m_gameDescription; + CopiedString mGameFile; ///< the .game file that describes this game + GameDescription m_gameDescription; -CopiedString mGameToolsPath; ///< the explicit path to the game-dependent modules -CopiedString mGameType; ///< the type of the engine + CopiedString mGameToolsPath; ///< the explicit path to the game-dependent modules + CopiedString mGameType; ///< the type of the engine -const char* getKeyValue( const char* key ) const { - GameDescription::const_iterator i = m_gameDescription.find( key ); - if ( i != m_gameDescription.end() ) { - return ( *i ).second.c_str(); + const char* getKeyValue( const char* key ) const { + GameDescription::const_iterator i = m_gameDescription.find( key ); + if ( i != m_gameDescription.end() ) { + return ( *i ).second.c_str(); + } + return ""; } - return ""; -} -const char* getRequiredKeyValue( const char* key ) const { - GameDescription::const_iterator i = m_gameDescription.find( key ); - if ( i != m_gameDescription.end() ) { - return ( *i ).second.c_str(); + const char* getRequiredKeyValue( const char* key ) const { + GameDescription::const_iterator i = m_gameDescription.find( key ); + if ( i != m_gameDescription.end() ) { + return ( *i ).second.c_str(); + } + ERROR_MESSAGE( "game attribute " << makeQuoted( key ) << " not found in " << makeQuoted( mGameFile.c_str() ) ); + return ""; } - ERROR_MESSAGE( "game attribute " << makeQuoted( key ) << " not found in " << makeQuoted( mGameFile.c_str() ) ); - return ""; -} -CGameDescription( xmlDocPtr pDoc, const CopiedString &GameFile ); + CGameDescription( xmlDocPtr pDoc, const CopiedString &GameFile ); -void Dump(); + void Dump(); }; extern CGameDescription *g_pGameDescription; @@ -226,110 +226,110 @@ class CGameDialog : public Dialog { protected: -mutable int m_nComboSelect; ///< intermediate int value for combo in dialog box + mutable int m_nComboSelect; ///< intermediate int value for combo in dialog box public: -/*! - those settings are saved in the global prefs file - I'm too lazy to wrap behind protected access, not sure this needs to be public - NOTE: those are preference settings. if you change them it is likely that you would - have to restart the editor for them to take effect - */ -/*@{*/ -/*! - what game has been selected - this is the name of the .game file - */ -LatchedValue m_sGameFile; -/*! - prompt which game to load on startup - */ -bool m_bGamePrompt; -/*! - log console to radiant.log - m_bForceLogConsole is an obscure forced latching situation - */ -bool m_bForceLogConsole; -/*@}*/ + /*! + those settings are saved in the global prefs file + I'm too lazy to wrap behind protected access, not sure this needs to be public + NOTE: those are preference settings. if you change them it is likely that you would + have to restart the editor for them to take effect + */ + /*@{*/ + /*! + what game has been selected + this is the name of the .game file + */ + LatchedValue m_sGameFile; + /*! + prompt which game to load on startup + */ + bool m_bGamePrompt; + /*! + log console to radiant.log + m_bForceLogConsole is an obscure forced latching situation + */ + bool m_bForceLogConsole; + /*@}*/ -/*! - the list of game descriptions we scanned from the game/ dir - */ -std::list mGames; + /*! + the list of game descriptions we scanned from the game/ dir + */ + std::list mGames; -CGameDialog() : - m_sGameFile( "", "Selected Game" ), - m_bGamePrompt( false ), - m_bForceLogConsole( false ){ -} -virtual ~CGameDialog(); + CGameDialog() : + m_sGameFile( "", "Selected Game" ), + m_bGamePrompt( false ), + m_bForceLogConsole( false ){ + } + virtual ~CGameDialog(); -void AddPacksURL( StringOutputStream &s ); + void AddPacksURL( StringOutputStream &s ); -/*! - intialize the game dialog, called at CPrefsDlg::Init - will scan for games, load prefs, and do game selection dialog if needed - */ -void Init(); + /*! + intialize the game dialog, called at CPrefsDlg::Init + will scan for games, load prefs, and do game selection dialog if needed + */ + void Init(); -/*! - reset the global settings by removing the file - */ -void Reset(); + /*! + reset the global settings by removing the file + */ + void Reset(); -/*! - run the dialog UI for the list of games - */ -void DoGameDialog(); + /*! + run the dialog UI for the list of games + */ + void DoGameDialog(); -/*! - Dialog API - this is only called when the dialog is built at startup for main engine select - */ -GtkWindow* BuildDialog(); + /*! + Dialog API + this is only called when the dialog is built at startup for main engine select + */ + GtkWindow* BuildDialog(); -void GameFileAssign( int value ); -void GameFileImport( int value ); -void GameFileExport( const IntImportCallback& importCallback ) const; + void GameFileAssign( int value ); + void GameFileImport( int value ); + void GameFileExport( const IntImportCallback& importCallback ) const; -/*! - construction of the dialog frame - this is the part to be re-used in prefs dialog - for the standalone dialog, we include this in a modal box - for prefs, we hook the frame in the main notebook - build the frame on-demand (only once) - */ + /*! + construction of the dialog frame + this is the part to be re-used in prefs dialog + for the standalone dialog, we include this in a modal box + for prefs, we hook the frame in the main notebook + build the frame on-demand (only once) + */ /// \brief \p global controls if to use LatchedValue assignment callback (global settings dialog) or import (preferences dialog). -void CreateGlobalFrame( PreferencesPage& page, bool global ); + void CreateGlobalFrame( PreferencesPage& page, bool global ); -/*! - global preferences subsystem - XML-based this time, hopefully this will generalize to other prefs - LoadPrefs has hardcoded defaults - NOTE: it may not be strictly 'CGameDialog' to put the global prefs here - could have named the class differently I guess - */ -/*@{*/ -void LoadPrefs(); ///< load from file into variables -void SavePrefs(); ///< save pref variables to file -/*@}*/ + /*! + global preferences subsystem + XML-based this time, hopefully this will generalize to other prefs + LoadPrefs has hardcoded defaults + NOTE: it may not be strictly 'CGameDialog' to put the global prefs here + could have named the class differently I guess + */ + /*@{*/ + void LoadPrefs(); ///< load from file into variables + void SavePrefs(); ///< save pref variables to file + /*@}*/ private: -/*! - scan for .game files, load them - */ -void ScanForGames(); + /*! + scan for .game files, load them + */ + void ScanForGames(); -/*! - inits g_Preferences.m_global_rc_path - */ -void InitGlobalPrefPath(); + /*! + inits g_Preferences.m_global_rc_path + */ + void InitGlobalPrefPath(); -/*! - uses m_nComboItem to find the right mGames - */ -CGameDescription *GameDescriptionForComboItem(); + /*! + uses m_nComboItem to find the right mGames + */ + CGameDescription *GameDescriptionForComboItem(); }; /*! @@ -342,47 +342,47 @@ class PrefsDlg : public Dialog { public: -GtkWidget *m_notebook; -GtkWidget *m_treeview; + GtkWidget *m_notebook; + GtkWidget *m_treeview; -virtual ~PrefsDlg(){ - g_string_free( m_rc_path, true ); - g_string_free( m_inipath, true ); -} + virtual ~PrefsDlg(){ + g_string_free( m_rc_path, true ); + g_string_free( m_inipath, true ); + } -/*! - path for global settings - win32: AppPath - linux: ~/.radiant/[version]/ - */ -GString *m_global_rc_path; + /*! + path for global settings + win32: AppPath + linux: ~/.radiant/[version]/ + */ + GString *m_global_rc_path; -/*! - path to per-game settings - used for various game dependant storage - win32: GameToolsPath - linux: ~/.radiant/[version]/[gamename]/ - */ -GString *m_rc_path; + /*! + path to per-game settings + used for various game dependant storage + win32: GameToolsPath + linux: ~/.radiant/[version]/[gamename]/ + */ + GString *m_rc_path; -/*! - holds per-game settings - m_rc_path+"local.pref" - \todo FIXME at some point this should become XML property bag code too - */ -GString *m_inipath; + /*! + holds per-game settings + m_rc_path+"local.pref" + \todo FIXME at some point this should become XML property bag code too + */ + GString *m_inipath; // initialize the above paths -void Init(); + void Init(); -/*! Utility function for swapping notebook pages for tree list selections */ -void showPrefPage( GtkWidget* prefpage ); + /*! Utility function for swapping notebook pages for tree list selections */ + void showPrefPage( GtkWidget* prefpage ); protected: -/*! Dialog API */ -GtkWindow* BuildDialog(); -void PostModal( EMessageBoxReturn code ); + /*! Dialog API */ + GtkWindow* BuildDialog(); + void PostModal( EMessageBoxReturn code ); }; extern PrefsDlg g_Preferences; diff --git a/radiant/qe3.cpp b/radiant/qe3.cpp index b88bdf58..d2c499c3 100644 --- a/radiant/qe3.cpp +++ b/radiant/qe3.cpp @@ -140,7 +140,9 @@ bool ConfirmModified( const char* title ){ return true; } - EMessageBoxReturn result = gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), "The current map has changed since it was last saved.\nDo you want to save the current map before continuing?", title, eMB_YESNOCANCEL, eMB_ICONQUESTION ); + EMessageBoxReturn result = gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), + "The current map has changed since it was last saved.\nDo you want to save the current map before continuing?", + title, eMB_YESNOCANCEL, eMB_ICONQUESTION ); if ( result == eIDCANCEL ) { return false; } @@ -188,42 +190,42 @@ void bsp_shutdown(){ class ArrayCommandListener : public CommandListener { -GPtrArray* m_array; + GPtrArray* m_array; public: -ArrayCommandListener(){ - m_array = g_ptr_array_new(); -} -~ArrayCommandListener(){ - g_ptr_array_free( m_array, TRUE ); -} + ArrayCommandListener(){ + m_array = g_ptr_array_new(); + } + ~ArrayCommandListener(){ + g_ptr_array_free( m_array, TRUE ); + } -void execute( const char* command ){ - g_ptr_array_add( m_array, g_strdup( command ) ); -} + void execute( const char* command ){ + g_ptr_array_add( m_array, g_strdup( command ) ); + } -GPtrArray* array() const { - return m_array; -} + GPtrArray* array() const { + return m_array; + } }; class BatchCommandListener : public CommandListener { -TextOutputStream& m_file; -std::size_t m_commandCount; -const char* m_outputRedirect; + TextOutputStream& m_file; + std::size_t m_commandCount; + const char* m_outputRedirect; public: -BatchCommandListener( TextOutputStream& file, const char* outputRedirect ) : m_file( file ), m_commandCount( 0 ), m_outputRedirect( outputRedirect ){ -} - -void execute( const char* command ){ - m_file << command; - if( m_outputRedirect ){ - m_file << ( m_commandCount == 0? " > " : " >> " ); - m_file << "\"" << m_outputRedirect << "\""; + BatchCommandListener( TextOutputStream& file, const char* outputRedirect ) : m_file( file ), m_commandCount( 0 ), m_outputRedirect( outputRedirect ){ + } + + void execute( const char* command ){ + m_file << command; + if( m_outputRedirect ){ + m_file << ( m_commandCount == 0? " > " : " >> " ); + m_file << "\"" << m_outputRedirect << "\""; + } + m_file << "\n"; + ++m_commandCount; } - m_file << "\n"; - ++m_commandCount; -} }; bool Region_cameraValid(){ diff --git a/radiant/qgl.cpp b/radiant/qgl.cpp index 7888b549..627a6429 100644 --- a/radiant/qgl.cpp +++ b/radiant/qgl.cpp @@ -928,40 +928,40 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_multitexture" ) ) { table.support_ARB_multitexture = - QGL_constructExtensionFunc( table.m_glActiveTextureARB, "glActiveTextureARB" ) - && QGL_constructExtensionFunc( table.m_glClientActiveTextureARB, "glClientActiveTextureARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dARB, "glMultiTexCoord1dARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dvARB, "glMultiTexCoord1dvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fARB, "glMultiTexCoord1fARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fvARB, "glMultiTexCoord1fvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1iARB, "glMultiTexCoord1iARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1ivARB, "glMultiTexCoord1ivARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1sARB, "glMultiTexCoord1sARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1svARB, "glMultiTexCoord1svARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dARB, "glMultiTexCoord2dARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dvARB, "glMultiTexCoord2dvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fARB, "glMultiTexCoord2fARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fvARB, "glMultiTexCoord2fvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2iARB, "glMultiTexCoord2iARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2ivARB, "glMultiTexCoord2ivARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2sARB, "glMultiTexCoord2sARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2svARB, "glMultiTexCoord2svARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dARB, "glMultiTexCoord3dARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dvARB, "glMultiTexCoord3dvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fARB, "glMultiTexCoord3fARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fvARB, "glMultiTexCoord3fvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3iARB, "glMultiTexCoord3iARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3ivARB, "glMultiTexCoord3ivARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3sARB, "glMultiTexCoord3sARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3svARB, "glMultiTexCoord3svARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dARB, "glMultiTexCoord4dARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dvARB, "glMultiTexCoord4dvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fARB, "glMultiTexCoord4fARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fvARB, "glMultiTexCoord4fvARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4iARB, "glMultiTexCoord4iARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4ivARB, "glMultiTexCoord4ivARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4sARB, "glMultiTexCoord4sARB" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4svARB, "glMultiTexCoord4svARB" ); + QGL_constructExtensionFunc( table.m_glActiveTextureARB, "glActiveTextureARB" ) + && QGL_constructExtensionFunc( table.m_glClientActiveTextureARB, "glClientActiveTextureARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dARB, "glMultiTexCoord1dARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dvARB, "glMultiTexCoord1dvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fARB, "glMultiTexCoord1fARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fvARB, "glMultiTexCoord1fvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1iARB, "glMultiTexCoord1iARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1ivARB, "glMultiTexCoord1ivARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1sARB, "glMultiTexCoord1sARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1svARB, "glMultiTexCoord1svARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dARB, "glMultiTexCoord2dARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dvARB, "glMultiTexCoord2dvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fARB, "glMultiTexCoord2fARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fvARB, "glMultiTexCoord2fvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2iARB, "glMultiTexCoord2iARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2ivARB, "glMultiTexCoord2ivARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2sARB, "glMultiTexCoord2sARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2svARB, "glMultiTexCoord2svARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dARB, "glMultiTexCoord3dARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dvARB, "glMultiTexCoord3dvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fARB, "glMultiTexCoord3fARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fvARB, "glMultiTexCoord3fvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3iARB, "glMultiTexCoord3iARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3ivARB, "glMultiTexCoord3ivARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3sARB, "glMultiTexCoord3sARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3svARB, "glMultiTexCoord3svARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dARB, "glMultiTexCoord4dARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dvARB, "glMultiTexCoord4dvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fARB, "glMultiTexCoord4fARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fvARB, "glMultiTexCoord4fvARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4iARB, "glMultiTexCoord4iARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4ivARB, "glMultiTexCoord4ivARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4sARB, "glMultiTexCoord4sARB" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4svARB, "glMultiTexCoord4svARB" ); if ( !table.support_ARB_multitexture ) { extension_not_implemented( "GL_ARB_multitexture" ); @@ -974,13 +974,13 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_texture_compression" ) ) { table.support_ARB_texture_compression = - QGL_constructExtensionFunc( table.m_glCompressedTexImage3DARB, "glCompressedTexImage3DARB" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexImage2DARB, "glCompressedTexImage2DARB" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexImage1DARB, "glCompressedTexImage1DARB" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage3DARB, "glCompressedTexSubImage3DARB" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage2DARB, "glCompressedTexSubImage2DARB" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage1DARB, "glCompressedTexSubImage1DARB" ) - && QGL_constructExtensionFunc( table.m_glGetCompressedTexImageARB, "glGetCompressedTexImageARB" ); + QGL_constructExtensionFunc( table.m_glCompressedTexImage3DARB, "glCompressedTexImage3DARB" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexImage2DARB, "glCompressedTexImage2DARB" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexImage1DARB, "glCompressedTexImage1DARB" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage3DARB, "glCompressedTexSubImage3DARB" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage2DARB, "glCompressedTexSubImage2DARB" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage1DARB, "glCompressedTexSubImage1DARB" ) + && QGL_constructExtensionFunc( table.m_glGetCompressedTexImageARB, "glGetCompressedTexImageARB" ); if ( !table.support_ARB_texture_compression ) { extension_not_implemented( "GL_ARB_texture_compression" ); @@ -996,10 +996,10 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ // GL 1.2 if ( table.major_version > 1 || table.minor_version >= 2 ) { table.support_GL_1_2 = - QGL_constructExtensionFunc( table.m_glCopyTexSubImage3D, "glCopyTexSubImage3D" ) - && QGL_constructExtensionFunc( table.m_glDrawRangeElements, "glDrawRangeElements" ) - && QGL_constructExtensionFunc( table.m_glTexImage3D, "glTexImage3D" ) - && QGL_constructExtensionFunc( table.m_glTexSubImage3D, "glTexSubImage3D" ); + QGL_constructExtensionFunc( table.m_glCopyTexSubImage3D, "glCopyTexSubImage3D" ) + && QGL_constructExtensionFunc( table.m_glDrawRangeElements, "glDrawRangeElements" ) + && QGL_constructExtensionFunc( table.m_glTexImage3D, "glTexImage3D" ) + && QGL_constructExtensionFunc( table.m_glTexSubImage3D, "glTexSubImage3D" ); if ( !table.support_GL_1_2 ) { extension_not_implemented( "GL_VERSION_1_2" ); @@ -1013,52 +1013,52 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ // GL 1.3 if ( table.major_version > 1 || table.minor_version >= 3 ) { table.support_GL_1_3 = - QGL_constructExtensionFunc( table.m_glActiveTexture, "glActiveTexture" ) - && QGL_constructExtensionFunc( table.m_glClientActiveTexture, "glClientActiveTexture" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexImage1D, "glCompressedTexImage1D" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexImage2D, "glCompressedTexImage2D" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexImage3D, "glCompressedTexImage3D" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage1D, "glCompressedTexSubImage1D" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage2D, "glCompressedTexSubImage2D" ) - && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage3D, "glCompressedTexSubImage3D" ) - && QGL_constructExtensionFunc( table.m_glGetCompressedTexImage, "glGetCompressedTexImage" ) - && QGL_constructExtensionFunc( table.m_glLoadTransposeMatrixd, "glLoadTransposeMatrixd" ) - && QGL_constructExtensionFunc( table.m_glLoadTransposeMatrixf, "glLoadTransposeMatrixf" ) - && QGL_constructExtensionFunc( table.m_glMultTransposeMatrixd, "glMultTransposeMatrixd" ) - && QGL_constructExtensionFunc( table.m_glMultTransposeMatrixf, "glMultTransposeMatrixf" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1d, "glMultiTexCoord1d" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dv, "glMultiTexCoord1dv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1f, "glMultiTexCoord1f" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fv, "glMultiTexCoord1fv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1i, "glMultiTexCoord1i" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1iv, "glMultiTexCoord1iv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1s, "glMultiTexCoord1s" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord1sv, "glMultiTexCoord1sv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2d, "glMultiTexCoord2d" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dv, "glMultiTexCoord2dv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2f, "glMultiTexCoord2f" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fv, "glMultiTexCoord2fv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2i, "glMultiTexCoord2i" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2iv, "glMultiTexCoord2iv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2s, "glMultiTexCoord2s" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord2sv, "glMultiTexCoord2sv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3d, "glMultiTexCoord3d" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dv, "glMultiTexCoord3dv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3f, "glMultiTexCoord3f" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fv, "glMultiTexCoord3fv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3i, "glMultiTexCoord3i" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3iv, "glMultiTexCoord3iv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3s, "glMultiTexCoord3s" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord3sv, "glMultiTexCoord3sv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4d, "glMultiTexCoord4d" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dv, "glMultiTexCoord4dv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4f, "glMultiTexCoord4f" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fv, "glMultiTexCoord4fv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4i, "glMultiTexCoord4i" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4iv, "glMultiTexCoord4iv" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4s, "glMultiTexCoord4s" ) - && QGL_constructExtensionFunc( table.m_glMultiTexCoord4sv, "glMultiTexCoord4sv" ) - && QGL_constructExtensionFunc( table.m_glSampleCoverage, "glSampleCoverage" ); + QGL_constructExtensionFunc( table.m_glActiveTexture, "glActiveTexture" ) + && QGL_constructExtensionFunc( table.m_glClientActiveTexture, "glClientActiveTexture" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexImage1D, "glCompressedTexImage1D" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexImage2D, "glCompressedTexImage2D" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexImage3D, "glCompressedTexImage3D" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage1D, "glCompressedTexSubImage1D" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage2D, "glCompressedTexSubImage2D" ) + && QGL_constructExtensionFunc( table.m_glCompressedTexSubImage3D, "glCompressedTexSubImage3D" ) + && QGL_constructExtensionFunc( table.m_glGetCompressedTexImage, "glGetCompressedTexImage" ) + && QGL_constructExtensionFunc( table.m_glLoadTransposeMatrixd, "glLoadTransposeMatrixd" ) + && QGL_constructExtensionFunc( table.m_glLoadTransposeMatrixf, "glLoadTransposeMatrixf" ) + && QGL_constructExtensionFunc( table.m_glMultTransposeMatrixd, "glMultTransposeMatrixd" ) + && QGL_constructExtensionFunc( table.m_glMultTransposeMatrixf, "glMultTransposeMatrixf" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1d, "glMultiTexCoord1d" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1dv, "glMultiTexCoord1dv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1f, "glMultiTexCoord1f" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1fv, "glMultiTexCoord1fv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1i, "glMultiTexCoord1i" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1iv, "glMultiTexCoord1iv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1s, "glMultiTexCoord1s" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord1sv, "glMultiTexCoord1sv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2d, "glMultiTexCoord2d" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2dv, "glMultiTexCoord2dv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2f, "glMultiTexCoord2f" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2fv, "glMultiTexCoord2fv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2i, "glMultiTexCoord2i" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2iv, "glMultiTexCoord2iv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2s, "glMultiTexCoord2s" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord2sv, "glMultiTexCoord2sv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3d, "glMultiTexCoord3d" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3dv, "glMultiTexCoord3dv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3f, "glMultiTexCoord3f" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3fv, "glMultiTexCoord3fv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3i, "glMultiTexCoord3i" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3iv, "glMultiTexCoord3iv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3s, "glMultiTexCoord3s" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord3sv, "glMultiTexCoord3sv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4d, "glMultiTexCoord4d" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4dv, "glMultiTexCoord4dv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4f, "glMultiTexCoord4f" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4fv, "glMultiTexCoord4fv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4i, "glMultiTexCoord4i" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4iv, "glMultiTexCoord4iv" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4s, "glMultiTexCoord4s" ) + && QGL_constructExtensionFunc( table.m_glMultiTexCoord4sv, "glMultiTexCoord4sv" ) + && QGL_constructExtensionFunc( table.m_glSampleCoverage, "glSampleCoverage" ); if ( !table.support_GL_1_3 ) { extension_not_implemented( "GL_VERSION_1_3" ); @@ -1072,51 +1072,51 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ // GL 1.4 if ( table.major_version > 1 || table.minor_version >= 4 ) { table.support_GL_1_4 = - QGL_constructExtensionFunc( table.m_glBlendColor, "glBlendColor" ) - && QGL_constructExtensionFunc( table.m_glBlendEquation, "glBlendEquation" ) - && QGL_constructExtensionFunc( table.m_glBlendFuncSeparate, "glBlendFuncSeparate" ) - && QGL_constructExtensionFunc( table.m_glFogCoordPointer, "glFogCoordPointer" ) - && QGL_constructExtensionFunc( table.m_glFogCoordd, "glFogCoordd" ) - && QGL_constructExtensionFunc( table.m_glFogCoorddv, "glFogCoorddv" ) - && QGL_constructExtensionFunc( table.m_glFogCoordf, "glFogCoordf" ) - && QGL_constructExtensionFunc( table.m_glFogCoordfv, "glFogCoordfv" ) - && QGL_constructExtensionFunc( table.m_glMultiDrawArrays, "glMultiDrawArrays" ) - && QGL_constructExtensionFunc( table.m_glMultiDrawElements, "glMultiDrawElements" ) - && QGL_constructExtensionFunc( table.m_glPointParameterf, "glPointParameterf" ) - && QGL_constructExtensionFunc( table.m_glPointParameterfv, "glPointParameterfv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3b, "glSecondaryColor3b" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3bv, "glSecondaryColor3bv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3d, "glSecondaryColor3d" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3dv, "glSecondaryColor3dv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3f, "glSecondaryColor3f" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3fv, "glSecondaryColor3fv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3i, "glSecondaryColor3i" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3iv, "glSecondaryColor3iv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3s, "glSecondaryColor3s" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3sv, "glSecondaryColor3sv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3ub, "glSecondaryColor3ub" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3ubv, "glSecondaryColor3ubv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3ui, "glSecondaryColor3ui" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3uiv, "glSecondaryColor3uiv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3us, "glSecondaryColor3us" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColor3usv, "glSecondaryColor3usv" ) - && QGL_constructExtensionFunc( table.m_glSecondaryColorPointer, "glSecondaryColorPointer" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2d, "glWindowPos2d" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2dv, "glWindowPos2dv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2f, "glWindowPos2f" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2fv, "glWindowPos2fv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2i, "glWindowPos2i" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2iv, "glWindowPos2iv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2s, "glWindowPos2s" ) - && QGL_constructExtensionFunc( table.m_glWindowPos2sv, "glWindowPos2sv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3d, "glWindowPos3d" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3dv, "glWindowPos3dv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3f, "glWindowPos3f" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3fv, "glWindowPos3fv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3i, "glWindowPos3i" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3iv, "glWindowPos3iv" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3s, "glWindowPos3s" ) - && QGL_constructExtensionFunc( table.m_glWindowPos3sv, "glWindowPos3sv" ); + QGL_constructExtensionFunc( table.m_glBlendColor, "glBlendColor" ) + && QGL_constructExtensionFunc( table.m_glBlendEquation, "glBlendEquation" ) + && QGL_constructExtensionFunc( table.m_glBlendFuncSeparate, "glBlendFuncSeparate" ) + && QGL_constructExtensionFunc( table.m_glFogCoordPointer, "glFogCoordPointer" ) + && QGL_constructExtensionFunc( table.m_glFogCoordd, "glFogCoordd" ) + && QGL_constructExtensionFunc( table.m_glFogCoorddv, "glFogCoorddv" ) + && QGL_constructExtensionFunc( table.m_glFogCoordf, "glFogCoordf" ) + && QGL_constructExtensionFunc( table.m_glFogCoordfv, "glFogCoordfv" ) + && QGL_constructExtensionFunc( table.m_glMultiDrawArrays, "glMultiDrawArrays" ) + && QGL_constructExtensionFunc( table.m_glMultiDrawElements, "glMultiDrawElements" ) + && QGL_constructExtensionFunc( table.m_glPointParameterf, "glPointParameterf" ) + && QGL_constructExtensionFunc( table.m_glPointParameterfv, "glPointParameterfv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3b, "glSecondaryColor3b" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3bv, "glSecondaryColor3bv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3d, "glSecondaryColor3d" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3dv, "glSecondaryColor3dv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3f, "glSecondaryColor3f" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3fv, "glSecondaryColor3fv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3i, "glSecondaryColor3i" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3iv, "glSecondaryColor3iv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3s, "glSecondaryColor3s" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3sv, "glSecondaryColor3sv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3ub, "glSecondaryColor3ub" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3ubv, "glSecondaryColor3ubv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3ui, "glSecondaryColor3ui" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3uiv, "glSecondaryColor3uiv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3us, "glSecondaryColor3us" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColor3usv, "glSecondaryColor3usv" ) + && QGL_constructExtensionFunc( table.m_glSecondaryColorPointer, "glSecondaryColorPointer" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2d, "glWindowPos2d" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2dv, "glWindowPos2dv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2f, "glWindowPos2f" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2fv, "glWindowPos2fv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2i, "glWindowPos2i" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2iv, "glWindowPos2iv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2s, "glWindowPos2s" ) + && QGL_constructExtensionFunc( table.m_glWindowPos2sv, "glWindowPos2sv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3d, "glWindowPos3d" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3dv, "glWindowPos3dv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3f, "glWindowPos3f" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3fv, "glWindowPos3fv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3i, "glWindowPos3i" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3iv, "glWindowPos3iv" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3s, "glWindowPos3s" ) + && QGL_constructExtensionFunc( table.m_glWindowPos3sv, "glWindowPos3sv" ); if ( !table.support_GL_1_4 ) { extension_not_implemented( "GL_VERSION_1_4" ); @@ -1130,25 +1130,25 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ // GL 1.5 if ( table.major_version > 1 || table.minor_version >= 5 ) { table.support_GL_1_5 = - QGL_constructExtensionFunc( table.m_glBeginQuery, "glBeginQuery" ) - && QGL_constructExtensionFunc( table.m_glBindBuffer, "glBindBuffer" ) - && QGL_constructExtensionFunc( table.m_glBufferData, "glBufferData" ) - && QGL_constructExtensionFunc( table.m_glBufferSubData, "glBufferSubData" ) - && QGL_constructExtensionFunc( table.m_glDeleteBuffers, "glDeleteBuffers" ) - && QGL_constructExtensionFunc( table.m_glDeleteQueries, "glDeleteQueries" ) - && QGL_constructExtensionFunc( table.m_glEndQuery, "glEndQuery" ) - && QGL_constructExtensionFunc( table.m_glGenBuffers, "glGenBuffers" ) - && QGL_constructExtensionFunc( table.m_glGenQueries, "glGenQueries" ) - && QGL_constructExtensionFunc( table.m_glGetBufferParameteriv, "glGetBufferParameteriv" ) - && QGL_constructExtensionFunc( table.m_glGetBufferPointerv, "glGetBufferPointerv" ) - && QGL_constructExtensionFunc( table.m_glGetBufferSubData, "glGetBufferSubData" ) - && QGL_constructExtensionFunc( table.m_glGetQueryObjectiv, "glGetQueryObjectiv" ) - && QGL_constructExtensionFunc( table.m_glGetQueryObjectuiv, "glGetQueryObjectuiv" ) - && QGL_constructExtensionFunc( table.m_glGetQueryiv, "glGetQueryiv" ) - && QGL_constructExtensionFunc( table.m_glIsBuffer, "glIsBuffer" ) - && QGL_constructExtensionFunc( table.m_glIsQuery, "glIsQuery" ) - && QGL_constructExtensionFunc( table.m_glMapBuffer, "glMapBuffer" ) - && QGL_constructExtensionFunc( table.m_glUnmapBuffer, "glUnmapBuffer" ); + QGL_constructExtensionFunc( table.m_glBeginQuery, "glBeginQuery" ) + && QGL_constructExtensionFunc( table.m_glBindBuffer, "glBindBuffer" ) + && QGL_constructExtensionFunc( table.m_glBufferData, "glBufferData" ) + && QGL_constructExtensionFunc( table.m_glBufferSubData, "glBufferSubData" ) + && QGL_constructExtensionFunc( table.m_glDeleteBuffers, "glDeleteBuffers" ) + && QGL_constructExtensionFunc( table.m_glDeleteQueries, "glDeleteQueries" ) + && QGL_constructExtensionFunc( table.m_glEndQuery, "glEndQuery" ) + && QGL_constructExtensionFunc( table.m_glGenBuffers, "glGenBuffers" ) + && QGL_constructExtensionFunc( table.m_glGenQueries, "glGenQueries" ) + && QGL_constructExtensionFunc( table.m_glGetBufferParameteriv, "glGetBufferParameteriv" ) + && QGL_constructExtensionFunc( table.m_glGetBufferPointerv, "glGetBufferPointerv" ) + && QGL_constructExtensionFunc( table.m_glGetBufferSubData, "glGetBufferSubData" ) + && QGL_constructExtensionFunc( table.m_glGetQueryObjectiv, "glGetQueryObjectiv" ) + && QGL_constructExtensionFunc( table.m_glGetQueryObjectuiv, "glGetQueryObjectuiv" ) + && QGL_constructExtensionFunc( table.m_glGetQueryiv, "glGetQueryiv" ) + && QGL_constructExtensionFunc( table.m_glIsBuffer, "glIsBuffer" ) + && QGL_constructExtensionFunc( table.m_glIsQuery, "glIsQuery" ) + && QGL_constructExtensionFunc( table.m_glMapBuffer, "glMapBuffer" ) + && QGL_constructExtensionFunc( table.m_glUnmapBuffer, "glUnmapBuffer" ); if ( !table.support_GL_1_5 ) { extension_not_implemented( "GL_VERSION_1_5" ); @@ -1162,68 +1162,68 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_vertex_program" ) ) { table.support_ARB_vertex_program = - QGL_constructExtensionFunc( table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB" ) - && QGL_constructExtensionFunc( table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB" ) - && QGL_constructExtensionFunc( table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB" ) - && QGL_constructExtensionFunc( table.m_glProgramStringARB, "glProgramStringARB" ) - && QGL_constructExtensionFunc( table.m_glBindProgramARB, "glBindProgramARB" ) - && QGL_constructExtensionFunc( table.m_glDeleteProgramsARB, "glDeleteProgramsARB" ) - && QGL_constructExtensionFunc( table.m_glGenProgramsARB, "glGenProgramsARB" ) - && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4dARB, "glProgramEnvParameter4dARB" ) - && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4dvARB, "glProgramEnvParameter4dvARB" ) - && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4fARB, "glProgramEnvParameter4fARB" ) - && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4fvARB, "glProgramEnvParameter4fvARB" ) - && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4dARB, "glProgramLocalParameter4dARB" ) - && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4dvARB, "glProgramLocalParameter4dvARB" ) - && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4fARB, "glProgramLocalParameter4fARB" ) - && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4fvARB, "glProgramLocalParameter4fvARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramEnvParameterdvARB, "glGetProgramEnvParameterdvARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramEnvParameterfvARB, "glGetProgramEnvParameterfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramLocalParameterdvARB, "glGetProgramLocalParameterdvARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramLocalParameterfvARB, "glGetProgramLocalParameterfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramivARB, "glGetProgramivARB" ) - && QGL_constructExtensionFunc( table.m_glGetProgramStringARB, "glGetProgramStringARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB" ) - && QGL_constructExtensionFunc( table.m_glIsProgramARB, "glIsProgramARB" ); + QGL_constructExtensionFunc( table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB" ) + && QGL_constructExtensionFunc( table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB" ) + && QGL_constructExtensionFunc( table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB" ) + && QGL_constructExtensionFunc( table.m_glProgramStringARB, "glProgramStringARB" ) + && QGL_constructExtensionFunc( table.m_glBindProgramARB, "glBindProgramARB" ) + && QGL_constructExtensionFunc( table.m_glDeleteProgramsARB, "glDeleteProgramsARB" ) + && QGL_constructExtensionFunc( table.m_glGenProgramsARB, "glGenProgramsARB" ) + && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4dARB, "glProgramEnvParameter4dARB" ) + && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4dvARB, "glProgramEnvParameter4dvARB" ) + && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4fARB, "glProgramEnvParameter4fARB" ) + && QGL_constructExtensionFunc( table.m_glProgramEnvParameter4fvARB, "glProgramEnvParameter4fvARB" ) + && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4dARB, "glProgramLocalParameter4dARB" ) + && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4dvARB, "glProgramLocalParameter4dvARB" ) + && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4fARB, "glProgramLocalParameter4fARB" ) + && QGL_constructExtensionFunc( table.m_glProgramLocalParameter4fvARB, "glProgramLocalParameter4fvARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramEnvParameterdvARB, "glGetProgramEnvParameterdvARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramEnvParameterfvARB, "glGetProgramEnvParameterfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramLocalParameterdvARB, "glGetProgramLocalParameterdvARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramLocalParameterfvARB, "glGetProgramLocalParameterfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramivARB, "glGetProgramivARB" ) + && QGL_constructExtensionFunc( table.m_glGetProgramStringARB, "glGetProgramStringARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB" ) + && QGL_constructExtensionFunc( table.m_glIsProgramARB, "glIsProgramARB" ); if ( !table.support_ARB_vertex_program ) { extension_not_implemented( "GL_ARB_vertex_program" ); @@ -1239,45 +1239,45 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_shader_objects" ) ) { table.support_ARB_shader_objects = - QGL_constructExtensionFunc( table.m_glDeleteObjectARB, "glDeleteObjectARB" ) - && QGL_constructExtensionFunc( table.m_glGetHandleARB, "glGetHandleARB" ) - && QGL_constructExtensionFunc( table.m_glDetachObjectARB, "glDetachObjectARB" ) - && QGL_constructExtensionFunc( table.m_glCreateShaderObjectARB, "glCreateShaderObjectARB" ) - && QGL_constructExtensionFunc( table.m_glShaderSourceARB, "glShaderSourceARB" ) - && QGL_constructExtensionFunc( table.m_glCompileShaderARB, "glCompileShaderARB" ) - && QGL_constructExtensionFunc( table.m_glCreateProgramObjectARB, "glCreateProgramObjectARB" ) - && QGL_constructExtensionFunc( table.m_glAttachObjectARB, "glAttachObjectARB" ) - && QGL_constructExtensionFunc( table.m_glLinkProgramARB, "glLinkProgramARB" ) - && QGL_constructExtensionFunc( table.m_glUseProgramObjectARB, "glUseProgramObjectARB" ) - && QGL_constructExtensionFunc( table.m_glValidateProgramARB, "glValidateProgramARB" ) - && QGL_constructExtensionFunc( table.m_glUniform1fARB, "glUniform1fARB" ) - && QGL_constructExtensionFunc( table.m_glUniform2fARB, "glUniform2fARB" ) - && QGL_constructExtensionFunc( table.m_glUniform3fARB, "glUniform3fARB" ) - && QGL_constructExtensionFunc( table.m_glUniform4fARB, "glUniform4fARB" ) - && QGL_constructExtensionFunc( table.m_glUniform1iARB, "glUniform1iARB" ) - && QGL_constructExtensionFunc( table.m_glUniform2iARB, "glUniform2iARB" ) - && QGL_constructExtensionFunc( table.m_glUniform3iARB, "glUniform3iARB" ) - && QGL_constructExtensionFunc( table.m_glUniform4iARB, "glUniform4iARB" ) - && QGL_constructExtensionFunc( table.m_glUniform1fvARB, "glUniform1fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniform2fvARB, "glUniform2fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniform3fvARB, "glUniform3fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniform4fvARB, "glUniform4fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniform1ivARB, "glUniform1ivARB" ) - && QGL_constructExtensionFunc( table.m_glUniform2ivARB, "glUniform2ivARB" ) - && QGL_constructExtensionFunc( table.m_glUniform3ivARB, "glUniform3ivARB" ) - && QGL_constructExtensionFunc( table.m_glUniform4ivARB, "glUniform4ivARB" ) - && QGL_constructExtensionFunc( table.m_glUniformMatrix2fvARB, "glUniformMatrix2fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniformMatrix3fvARB, "glUniformMatrix3fvARB" ) - && QGL_constructExtensionFunc( table.m_glUniformMatrix4fvARB, "glUniformMatrix4fvARB" ) - && QGL_constructExtensionFunc( table.m_glGetObjectParameterfvARB, "glGetObjectParameterfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetObjectParameterivARB, "glGetObjectParameterivARB" ) - && QGL_constructExtensionFunc( table.m_glGetInfoLogARB, "glGetInfoLogARB" ) - && QGL_constructExtensionFunc( table.m_glGetAttachedObjectsARB, "glGetAttachedObjectsARB" ) - && QGL_constructExtensionFunc( table.m_glGetUniformLocationARB, "glGetUniformLocationARB" ) - && QGL_constructExtensionFunc( table.m_glGetActiveUniformARB, "glGetActiveUniformARB" ) - && QGL_constructExtensionFunc( table.m_glGetUniformfvARB, "glGetUniformfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetUniformivARB, "glGetUniformivARB" ) - && QGL_constructExtensionFunc( table.m_glGetShaderSourceARB, "glGetShaderSourceARB" ); + QGL_constructExtensionFunc( table.m_glDeleteObjectARB, "glDeleteObjectARB" ) + && QGL_constructExtensionFunc( table.m_glGetHandleARB, "glGetHandleARB" ) + && QGL_constructExtensionFunc( table.m_glDetachObjectARB, "glDetachObjectARB" ) + && QGL_constructExtensionFunc( table.m_glCreateShaderObjectARB, "glCreateShaderObjectARB" ) + && QGL_constructExtensionFunc( table.m_glShaderSourceARB, "glShaderSourceARB" ) + && QGL_constructExtensionFunc( table.m_glCompileShaderARB, "glCompileShaderARB" ) + && QGL_constructExtensionFunc( table.m_glCreateProgramObjectARB, "glCreateProgramObjectARB" ) + && QGL_constructExtensionFunc( table.m_glAttachObjectARB, "glAttachObjectARB" ) + && QGL_constructExtensionFunc( table.m_glLinkProgramARB, "glLinkProgramARB" ) + && QGL_constructExtensionFunc( table.m_glUseProgramObjectARB, "glUseProgramObjectARB" ) + && QGL_constructExtensionFunc( table.m_glValidateProgramARB, "glValidateProgramARB" ) + && QGL_constructExtensionFunc( table.m_glUniform1fARB, "glUniform1fARB" ) + && QGL_constructExtensionFunc( table.m_glUniform2fARB, "glUniform2fARB" ) + && QGL_constructExtensionFunc( table.m_glUniform3fARB, "glUniform3fARB" ) + && QGL_constructExtensionFunc( table.m_glUniform4fARB, "glUniform4fARB" ) + && QGL_constructExtensionFunc( table.m_glUniform1iARB, "glUniform1iARB" ) + && QGL_constructExtensionFunc( table.m_glUniform2iARB, "glUniform2iARB" ) + && QGL_constructExtensionFunc( table.m_glUniform3iARB, "glUniform3iARB" ) + && QGL_constructExtensionFunc( table.m_glUniform4iARB, "glUniform4iARB" ) + && QGL_constructExtensionFunc( table.m_glUniform1fvARB, "glUniform1fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniform2fvARB, "glUniform2fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniform3fvARB, "glUniform3fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniform4fvARB, "glUniform4fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniform1ivARB, "glUniform1ivARB" ) + && QGL_constructExtensionFunc( table.m_glUniform2ivARB, "glUniform2ivARB" ) + && QGL_constructExtensionFunc( table.m_glUniform3ivARB, "glUniform3ivARB" ) + && QGL_constructExtensionFunc( table.m_glUniform4ivARB, "glUniform4ivARB" ) + && QGL_constructExtensionFunc( table.m_glUniformMatrix2fvARB, "glUniformMatrix2fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniformMatrix3fvARB, "glUniformMatrix3fvARB" ) + && QGL_constructExtensionFunc( table.m_glUniformMatrix4fvARB, "glUniformMatrix4fvARB" ) + && QGL_constructExtensionFunc( table.m_glGetObjectParameterfvARB, "glGetObjectParameterfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetObjectParameterivARB, "glGetObjectParameterivARB" ) + && QGL_constructExtensionFunc( table.m_glGetInfoLogARB, "glGetInfoLogARB" ) + && QGL_constructExtensionFunc( table.m_glGetAttachedObjectsARB, "glGetAttachedObjectsARB" ) + && QGL_constructExtensionFunc( table.m_glGetUniformLocationARB, "glGetUniformLocationARB" ) + && QGL_constructExtensionFunc( table.m_glGetActiveUniformARB, "glGetActiveUniformARB" ) + && QGL_constructExtensionFunc( table.m_glGetUniformfvARB, "glGetUniformfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetUniformivARB, "glGetUniformivARB" ) + && QGL_constructExtensionFunc( table.m_glGetShaderSourceARB, "glGetShaderSourceARB" ); if ( !table.support_ARB_shader_objects ) { extension_not_implemented( "GL_ARB_shader_objects" ); @@ -1290,52 +1290,52 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_vertex_shader" ) ) { table.support_ARB_vertex_shader = - QGL_constructExtensionFunc( table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB" ) - && QGL_constructExtensionFunc( table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB" ) - && QGL_constructExtensionFunc( table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB" ) - && QGL_constructExtensionFunc( table.m_glBindAttribLocationARB, "glBindAttribLocationARB" ) - && QGL_constructExtensionFunc( table.m_glGetActiveAttribARB, "glGetActiveAttribARB" ) - && QGL_constructExtensionFunc( table.m_glGetAttribLocationARB, "glGetAttribLocationARB" ); + QGL_constructExtensionFunc( table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB" ) + && QGL_constructExtensionFunc( table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB" ) + && QGL_constructExtensionFunc( table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB" ) + && QGL_constructExtensionFunc( table.m_glBindAttribLocationARB, "glBindAttribLocationARB" ) + && QGL_constructExtensionFunc( table.m_glGetActiveAttribARB, "glGetActiveAttribARB" ) + && QGL_constructExtensionFunc( table.m_glGetAttribLocationARB, "glGetAttribLocationARB" ); if ( !table.support_ARB_vertex_shader ) { extension_not_implemented( "GL_ARB_vertex_shader" ); @@ -1348,40 +1348,40 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_NV_vertex_program2" ) ) { table.support_NV_vertex_program2 = - QGL_constructExtensionFunc( table.m_glAreProgramsResidentNV, "glAreProgramsResidentNV" ) - && QGL_constructExtensionFunc( table.m_glBindProgramNV, "glBindProgramNV" ) - && QGL_constructExtensionFunc( table.m_glDeleteProgramsNV, "glDeleteProgramsNV" ) - && QGL_constructExtensionFunc( table.m_glExecuteProgramNV, "glExecuteProgramNV" ) - && QGL_constructExtensionFunc( table.m_glGenProgramsNV, "glGenProgramsNV" ) - && QGL_constructExtensionFunc( table.m_glGetProgramParameterdvNV, "glGetProgramParameterdvNV" ) - && QGL_constructExtensionFunc( table.m_glGetProgramParameterfvNV, "glGetProgramParameterfvNV" ) - && QGL_constructExtensionFunc( table.m_glGetProgramivNV, "glGetProgramivNV" ) - && QGL_constructExtensionFunc( table.m_glGetProgramStringNV, "glGetProgramStringNV" ) - && QGL_constructExtensionFunc( table.m_glGetTrackMatrixivNV, "glGetTrackMatrixivNV" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvNV, "glGetVertexAttribdvNV" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvNV, "glGetVertexAttribfvNV" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribivNV, "glGetVertexAttribivNV" ) - && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervNV, "glGetVertexAttribPointervNV" ) - && QGL_constructExtensionFunc( table.m_glIsProgramNV, "glIsProgramNV" ) - && QGL_constructExtensionFunc( table.m_glLoadProgramNV, "glLoadProgramNV" ) - && QGL_constructExtensionFunc( table.m_glProgramParameter4fNV, "glProgramParameter4fNV" ) - && QGL_constructExtensionFunc( table.m_glProgramParameter4fvNV, "glProgramParameter4fvNV" ) - && QGL_constructExtensionFunc( table.m_glProgramParameters4fvNV, "glProgramParameters4fvNV" ) - && QGL_constructExtensionFunc( table.m_glRequestResidentProgramsNV, "glRequestResidentProgramsNV" ) - && QGL_constructExtensionFunc( table.m_glTrackMatrixNV, "glTrackMatrixNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribPointerNV, "glVertexAttribPointerNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1fNV, "glVertexAttrib1fNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvNV, "glVertexAttrib1fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fNV, "glVertexAttrib2fNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvNV, "glVertexAttrib2fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fNV, "glVertexAttrib3fNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvNV, "glVertexAttrib3fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fNV, "glVertexAttrib4fNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvNV, "glVertexAttrib4fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribs1fvNV, "glVertexAttribs1fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribs2fvNV, "glVertexAttribs2fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribs3fvNV, "glVertexAttribs3fvNV" ) - && QGL_constructExtensionFunc( table.m_glVertexAttribs4fvNV, "glVertexAttribs4fvNV" ); + QGL_constructExtensionFunc( table.m_glAreProgramsResidentNV, "glAreProgramsResidentNV" ) + && QGL_constructExtensionFunc( table.m_glBindProgramNV, "glBindProgramNV" ) + && QGL_constructExtensionFunc( table.m_glDeleteProgramsNV, "glDeleteProgramsNV" ) + && QGL_constructExtensionFunc( table.m_glExecuteProgramNV, "glExecuteProgramNV" ) + && QGL_constructExtensionFunc( table.m_glGenProgramsNV, "glGenProgramsNV" ) + && QGL_constructExtensionFunc( table.m_glGetProgramParameterdvNV, "glGetProgramParameterdvNV" ) + && QGL_constructExtensionFunc( table.m_glGetProgramParameterfvNV, "glGetProgramParameterfvNV" ) + && QGL_constructExtensionFunc( table.m_glGetProgramivNV, "glGetProgramivNV" ) + && QGL_constructExtensionFunc( table.m_glGetProgramStringNV, "glGetProgramStringNV" ) + && QGL_constructExtensionFunc( table.m_glGetTrackMatrixivNV, "glGetTrackMatrixivNV" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribdvNV, "glGetVertexAttribdvNV" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribfvNV, "glGetVertexAttribfvNV" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribivNV, "glGetVertexAttribivNV" ) + && QGL_constructExtensionFunc( table.m_glGetVertexAttribPointervNV, "glGetVertexAttribPointervNV" ) + && QGL_constructExtensionFunc( table.m_glIsProgramNV, "glIsProgramNV" ) + && QGL_constructExtensionFunc( table.m_glLoadProgramNV, "glLoadProgramNV" ) + && QGL_constructExtensionFunc( table.m_glProgramParameter4fNV, "glProgramParameter4fNV" ) + && QGL_constructExtensionFunc( table.m_glProgramParameter4fvNV, "glProgramParameter4fvNV" ) + && QGL_constructExtensionFunc( table.m_glProgramParameters4fvNV, "glProgramParameters4fvNV" ) + && QGL_constructExtensionFunc( table.m_glRequestResidentProgramsNV, "glRequestResidentProgramsNV" ) + && QGL_constructExtensionFunc( table.m_glTrackMatrixNV, "glTrackMatrixNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribPointerNV, "glVertexAttribPointerNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1fNV, "glVertexAttrib1fNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib1fvNV, "glVertexAttrib1fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fNV, "glVertexAttrib2fNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib2fvNV, "glVertexAttrib2fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fNV, "glVertexAttrib3fNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib3fvNV, "glVertexAttrib3fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fNV, "glVertexAttrib4fNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttrib4fvNV, "glVertexAttrib4fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribs1fvNV, "glVertexAttribs1fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribs2fvNV, "glVertexAttribs2fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribs3fvNV, "glVertexAttribs3fvNV" ) + && QGL_constructExtensionFunc( table.m_glVertexAttribs4fvNV, "glVertexAttribs4fvNV" ); if ( !table.support_NV_vertex_program2 ) { extension_not_implemented( "GL_NV_vertex_program2" ); @@ -1428,9 +1428,9 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_NV_fragment_program" ) ) { table.support_NV_fragment_program = - QGL_constructExtensionFunc( table.m_glProgramNamedParameter4fNV, "glProgramNamedParameter4fNV" ) - && QGL_constructExtensionFunc( table.m_glProgramNamedParameter4fvNV, "glProgramNamedParameter4fvNV" ) - && QGL_constructExtensionFunc( table.m_glGetProgramNamedParameterfvNV, "glGetProgramNamedParameterfvNV" ); + QGL_constructExtensionFunc( table.m_glProgramNamedParameter4fNV, "glProgramNamedParameter4fNV" ) + && QGL_constructExtensionFunc( table.m_glProgramNamedParameter4fvNV, "glProgramNamedParameter4fvNV" ) + && QGL_constructExtensionFunc( table.m_glGetProgramNamedParameterfvNV, "glGetProgramNamedParameterfvNV" ); if ( !table.support_NV_fragment_program ) { extension_not_implemented( "GL_NV_fragment_program" ); @@ -1457,26 +1457,26 @@ void QGL_sharedContextCreated( OpenGLBinding& table ){ if ( QGL_ExtensionSupported( "GL_ARB_framebuffer_object" ) ) { table.support_ARB_framebuffer_object = - QGL_constructExtensionFunc( table.m_glBindFramebuffer, "glBindFramebuffer" ) - && QGL_constructExtensionFunc( table.m_glBindRenderbuffer, "glBindRenderbuffer" ) - && QGL_constructExtensionFunc( table.m_glBlitFramebuffer, "glBlitFramebuffer" ) - && QGL_constructExtensionFunc( table.m_glCheckFramebufferStatus, "glCheckFramebufferStatus" ) - && QGL_constructExtensionFunc( table.m_glDeleteFramebuffers, "glDeleteFramebuffers" ) - && QGL_constructExtensionFunc( table.m_glDeleteRenderbuffers, "glDeleteRenderbuffers" ) - && QGL_constructExtensionFunc( table.m_glFramebufferRenderbuffer, "glFramebufferRenderbuffer" ) - && QGL_constructExtensionFunc( table.m_glFramebufferTexture1D, "glFramebufferTexture1D" ) - && QGL_constructExtensionFunc( table.m_glFramebufferTexture2D, "glFramebufferTexture2D" ) - && QGL_constructExtensionFunc( table.m_glFramebufferTexture3D, "glFramebufferTexture3D" ) - && QGL_constructExtensionFunc( table.m_glFramebufferTextureLayer, "glFramebufferTextureLayer" ) - && QGL_constructExtensionFunc( table.m_glGenFramebuffers, "glGenFramebuffers" ) - && QGL_constructExtensionFunc( table.m_glGenRenderbuffers, "glGenRenderbuffers" ) - && QGL_constructExtensionFunc( table.m_glGenerateMipmap, "glGenerateMipmap" ) - && QGL_constructExtensionFunc( table.m_glGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv" ) - && QGL_constructExtensionFunc( table.m_glGetRenderbufferParameteriv, "glGetRenderbufferParameteriv" ) - && QGL_constructExtensionFunc( table.m_glIsFramebuffer, "glIsFramebuffer" ) - && QGL_constructExtensionFunc( table.m_glIsRenderbuffer, "glIsRenderbuffer" ) - && QGL_constructExtensionFunc( table.m_glRenderbufferStorage, "glRenderbufferStorage" ) - && QGL_constructExtensionFunc( table.m_glRenderbufferStorageMultisample, "glRenderbufferStorageMultisample" ); + QGL_constructExtensionFunc( table.m_glBindFramebuffer, "glBindFramebuffer" ) + && QGL_constructExtensionFunc( table.m_glBindRenderbuffer, "glBindRenderbuffer" ) + && QGL_constructExtensionFunc( table.m_glBlitFramebuffer, "glBlitFramebuffer" ) + && QGL_constructExtensionFunc( table.m_glCheckFramebufferStatus, "glCheckFramebufferStatus" ) + && QGL_constructExtensionFunc( table.m_glDeleteFramebuffers, "glDeleteFramebuffers" ) + && QGL_constructExtensionFunc( table.m_glDeleteRenderbuffers, "glDeleteRenderbuffers" ) + && QGL_constructExtensionFunc( table.m_glFramebufferRenderbuffer, "glFramebufferRenderbuffer" ) + && QGL_constructExtensionFunc( table.m_glFramebufferTexture1D, "glFramebufferTexture1D" ) + && QGL_constructExtensionFunc( table.m_glFramebufferTexture2D, "glFramebufferTexture2D" ) + && QGL_constructExtensionFunc( table.m_glFramebufferTexture3D, "glFramebufferTexture3D" ) + && QGL_constructExtensionFunc( table.m_glFramebufferTextureLayer, "glFramebufferTextureLayer" ) + && QGL_constructExtensionFunc( table.m_glGenFramebuffers, "glGenFramebuffers" ) + && QGL_constructExtensionFunc( table.m_glGenRenderbuffers, "glGenRenderbuffers" ) + && QGL_constructExtensionFunc( table.m_glGenerateMipmap, "glGenerateMipmap" ) + && QGL_constructExtensionFunc( table.m_glGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv" ) + && QGL_constructExtensionFunc( table.m_glGetRenderbufferParameteriv, "glGetRenderbufferParameteriv" ) + && QGL_constructExtensionFunc( table.m_glIsFramebuffer, "glIsFramebuffer" ) + && QGL_constructExtensionFunc( table.m_glIsRenderbuffer, "glIsRenderbuffer" ) + && QGL_constructExtensionFunc( table.m_glRenderbufferStorage, "glRenderbufferStorage" ) + && QGL_constructExtensionFunc( table.m_glRenderbufferStorageMultisample, "glRenderbufferStorageMultisample" ); if ( !table.support_ARB_framebuffer_object ) { extension_not_implemented( "GL_ARB_framebuffer_object" ); @@ -1512,22 +1512,22 @@ void QGL_assertNoErrors( const char *file, int line ){ class QglAPI { -OpenGLBinding m_qgl; + OpenGLBinding m_qgl; public: -typedef OpenGLBinding Type; -STRING_CONSTANT( Name, "*" ); + typedef OpenGLBinding Type; + STRING_CONSTANT( Name, "*" ); -QglAPI(){ - QGL_Init( m_qgl ); + QglAPI(){ + QGL_Init( m_qgl ); - m_qgl.assertNoErrors = &QGL_assertNoErrors; -} -~QglAPI(){ - QGL_Shutdown( m_qgl ); -} -OpenGLBinding* getTable(){ - return &m_qgl; -} + m_qgl.assertNoErrors = &QGL_assertNoErrors; + } + ~QglAPI(){ + QGL_Shutdown( m_qgl ); + } + OpenGLBinding* getTable(){ + return &m_qgl; + } }; #include "modulesystem/singletonmodule.h" diff --git a/radiant/referencecache.cpp b/radiant/referencecache.cpp index ee3ab806..190e879e 100644 --- a/radiant/referencecache.cpp +++ b/radiant/referencecache.cpp @@ -119,7 +119,7 @@ bool file_saveBackup( const char* path ){ backup << StringRange( path, path_get_extension( path ) ) << "bak"; return ( !file_exists( backup.c_str() ) || file_remove( backup.c_str() ) ) // remove backup - && file_move( path, backup.c_str() ); // rename current to backup + && file_move( path, backup.c_str() ); // rename current to backup } globalErrorStream() << "map path is not writeable: " << makeQuoted( path ) << "\n"; @@ -152,9 +152,9 @@ NodeSmartReference g_nullModel( g_nullNode ); class NullModelLoader : public ModelLoader { public: -scene::Node& loadModel( ArchiveFile& file ){ - return g_nullModel; -} + scene::Node& loadModel( ArchiveFile& file ){ + return g_nullModel; + } }; namespace @@ -312,10 +312,10 @@ bool g_realised = false; // name may be absolute or relative const char* rootPath( const char* name ){ return GlobalFileSystem().findRoot( - path_is_absolute( name ) - ? name - : GlobalFileSystem().findFile( name ) - ); + path_is_absolute( name ) + ? name + : GlobalFileSystem().findFile( name ) + ); } } @@ -368,10 +368,10 @@ struct ModelResource : public Resource ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() ); if ( i == g_modelCache.end() ) { i = ModelCache_insert( - m_path.c_str(), - m_name.c_str(), - Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) - ); + m_path.c_str(), + m_name.c_str(), + Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) + ); } setModel( ( *i ).value ); @@ -494,8 +494,8 @@ struct ModelResource : public Resource } bool isModified() const { return ( ( !string_empty( m_path.c_str() ) // had or has an absolute path - && m_modified != modified() ) // AND disk timestamp changed - || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed + && m_modified != modified() ) // AND disk timestamp changed + || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed } void refresh(){ if ( isModified() ) { @@ -508,117 +508,117 @@ struct ModelResource : public Resource class HashtableReferenceCache : public ReferenceCache, public ModuleObserver { -typedef HashedCache ModelReferences; -ModelReferences m_references; -std::size_t m_unrealised; + typedef HashedCache ModelReferences; + ModelReferences m_references; + std::size_t m_unrealised; -class ModelReferencesSnapshot -{ -ModelReferences& m_references; -typedef std::list Iterators; -Iterators m_iterators; -public: -typedef Iterators::iterator iterator; -ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){ - for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i ) + class ModelReferencesSnapshot { - m_references.capture( i ); - m_iterators.push_back( i ); - } -} -~ModelReferencesSnapshot(){ - for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i ) - { - m_references.release( *i ); - } -} -iterator begin(){ - return m_iterators.begin(); -} -iterator end(){ - return m_iterators.end(); -} -}; - -public: - -typedef ModelReferences::iterator iterator; - -HashtableReferenceCache() : m_unrealised( 1 ){ -} - -iterator begin(){ - return m_references.begin(); -} -iterator end(){ - return m_references.end(); -} - -void clear(){ - m_references.clear(); -} - -Resource* capture( const char* path ){ - //globalOutputStream() << "capture: \"" << path << "\"\n"; - return m_references.capture( CopiedString( path ) ).get(); -} -void release( const char* path ){ - m_references.release( CopiedString( path ) ); - //globalOutputStream() << "release: \"" << path << "\"\n"; -} - -void setEntityCreator( EntityCreator& entityCreator ){ - g_entityCreator = &entityCreator; -} - -bool realised() const { - return m_unrealised == 0; -} -void realise(){ - ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" ); - if ( --m_unrealised == 0 ) { - g_realised = true; - - { - ModelReferencesSnapshot snapshot( m_references ); - for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) + ModelReferences& m_references; + typedef std::list Iterators; + Iterators m_iterators; + public: + typedef Iterators::iterator iterator; + ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){ + for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i ) { - ModelReferences::value_type& value = *( *i ); - if ( value.value.count() != 1 ) { - value.value.get()->realise(); + m_references.capture( i ); + m_iterators.push_back( i ); + } + } + ~ModelReferencesSnapshot(){ + for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i ) + { + m_references.release( *i ); + } + } + iterator begin(){ + return m_iterators.begin(); + } + iterator end(){ + return m_iterators.end(); + } + }; + +public: + + typedef ModelReferences::iterator iterator; + + HashtableReferenceCache() : m_unrealised( 1 ){ + } + + iterator begin(){ + return m_references.begin(); + } + iterator end(){ + return m_references.end(); + } + + void clear(){ + m_references.clear(); + } + + Resource* capture( const char* path ){ + //globalOutputStream() << "capture: \"" << path << "\"\n"; + return m_references.capture( CopiedString( path ) ).get(); + } + void release( const char* path ){ + m_references.release( CopiedString( path ) ); + //globalOutputStream() << "release: \"" << path << "\"\n"; + } + + void setEntityCreator( EntityCreator& entityCreator ){ + g_entityCreator = &entityCreator; + } + + bool realised() const { + return m_unrealised == 0; + } + void realise(){ + ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" ); + if ( --m_unrealised == 0 ) { + g_realised = true; + + { + ModelReferencesSnapshot snapshot( m_references ); + for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) + { + ModelReferences::value_type& value = *( *i ); + if ( value.value.count() != 1 ) { + value.value.get()->realise(); + } } } } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - g_realised = false; + void unrealise(){ + if ( ++m_unrealised == 1 ) { + g_realised = false; - { - ModelReferencesSnapshot snapshot( m_references ); - for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) { - ModelReferences::value_type& value = *( *i ); - if ( value.value.count() != 1 ) { - value.value.get()->unrealise(); + ModelReferencesSnapshot snapshot( m_references ); + for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) + { + ModelReferences::value_type& value = *( *i ); + if ( value.value.count() != 1 ) { + value.value.get()->unrealise(); + } } } - } - ModelCache_clear(); - } -} -void refresh(){ - ModelReferencesSnapshot snapshot( m_references ); - for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) - { - ModelResource* resource = ( *( *i ) ).value.get(); - if ( !resource->isMap() ) { - resource->refresh(); + ModelCache_clear(); + } + } + void refresh(){ + ModelReferencesSnapshot snapshot( m_references ); + for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i ) + { + ModelResource* resource = ( *( *i ) ).value.get(); + if ( !resource->isMap() ) { + resource->refresh(); + } } } -} }; namespace @@ -630,8 +630,8 @@ HashtableReferenceCache g_referenceCache; class ResourceVisitor { public: -virtual void visit( const char* name, const char* path, const - }; + virtual void visit( const char* name, const char* path, const +}; #endif void SaveReferences(){ @@ -683,44 +683,44 @@ class ReferenceDependencies : public GlobalFileSystemModuleRef, public GlobalFiletypesModuleRef { -ModelModulesRef m_model_modules; -MapModulesRef m_map_modules; + ModelModulesRef m_model_modules; + MapModulesRef m_map_modules; public: -ReferenceDependencies() : - m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ), - m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) ) -{ -} -ModelModules& getModelModules(){ - return m_model_modules.get(); -} -MapModules& getMapModules(){ - return m_map_modules.get(); -} + ReferenceDependencies() : + m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ), + m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) ) + { + } + ModelModules& getModelModules(){ + return m_model_modules.get(); + } + MapModules& getMapModules(){ + return m_map_modules.get(); + } }; class ReferenceAPI : public TypeSystemRef { -ReferenceCache* m_reference; + ReferenceCache* m_reference; public: -typedef ReferenceCache Type; -STRING_CONSTANT( Name, "*" ); + typedef ReferenceCache Type; + STRING_CONSTANT( Name, "*" ); -ReferenceAPI(){ - g_nullModel = NewNullModel(); + ReferenceAPI(){ + g_nullModel = NewNullModel(); - GlobalFileSystem().attach( g_referenceCache ); + GlobalFileSystem().attach( g_referenceCache ); - m_reference = &GetReferenceCache(); -} -~ReferenceAPI(){ - GlobalFileSystem().detach( g_referenceCache ); + m_reference = &GetReferenceCache(); + } + ~ReferenceAPI(){ + GlobalFileSystem().detach( g_referenceCache ); - g_nullModel = g_nullNode; -} -ReferenceCache* getTable(){ - return m_reference; -} + g_nullModel = g_nullNode; + } + ReferenceCache* getTable(){ + return m_reference; + } }; typedef SingletonModule ReferenceModule; diff --git a/radiant/renderer.h b/radiant/renderer.h index f100fc4a..55ab02eb 100644 --- a/radiant/renderer.h +++ b/radiant/renderer.h @@ -51,59 +51,59 @@ inline VolumeIntersectionValue Cullable_testVisible( scene::Instance& instance, template class CullingWalker { -const VolumeTest& m_volume; -const _Walker& m_walker; + const VolumeTest& m_volume; + const _Walker& m_walker; public: -CullingWalker( const VolumeTest& volume, const _Walker& walker ) - : m_volume( volume ), m_walker( walker ){ -} -bool pre( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { - VolumeIntersectionValue visible = Cullable_testVisible( instance, m_volume, parentVisible ); - if ( visible != c_volumeOutside ) { - return m_walker.pre( path, instance ); + CullingWalker( const VolumeTest& volume, const _Walker& walker ) + : m_volume( volume ), m_walker( walker ){ + } + bool pre( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { + VolumeIntersectionValue visible = Cullable_testVisible( instance, m_volume, parentVisible ); + if ( visible != c_volumeOutside ) { + return m_walker.pre( path, instance ); + } + return true; + } + void post( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { + return m_walker.post( path, instance ); } - return true; -} -void post( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { - return m_walker.post( path, instance ); -} }; template class ForEachVisible : public scene::Graph::Walker { -const VolumeTest& m_volume; -const Walker_& m_walker; -mutable std::vector m_state; + const VolumeTest& m_volume; + const Walker_& m_walker; + mutable std::vector m_state; public: -ForEachVisible( const VolumeTest& volume, const Walker_& walker ) - : m_volume( volume ), m_walker( walker ){ - m_state.push_back( c_volumePartial ); -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - VolumeIntersectionValue visible = ( path.top().get().visible() ) ? m_state.back() : c_volumeOutside; - - if ( visible == c_volumePartial ) { - visible = m_volume.TestAABB( instance.worldAABB() ); + ForEachVisible( const VolumeTest& volume, const Walker_& walker ) + : m_volume( volume ), m_walker( walker ){ + m_state.push_back( c_volumePartial ); } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + VolumeIntersectionValue visible = ( path.top().get().visible() ) ? m_state.back() : c_volumeOutside; - m_state.push_back( visible ); + if ( visible == c_volumePartial ) { + visible = m_volume.TestAABB( instance.worldAABB() ); + } - if ( visible == c_volumeOutside ) { - return false; - } - else - { - return m_walker.pre( path, instance, m_state.back() ); - } -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( m_state.back() != c_volumeOutside ) { - m_walker.post( path, instance, m_state.back() ); - } + m_state.push_back( visible ); - m_state.pop_back(); -} + if ( visible == c_volumeOutside ) { + return false; + } + else + { + return m_walker.pre( path, instance, m_state.back() ); + } + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( m_state.back() != c_volumeOutside ) { + m_walker.post( path, instance, m_state.back() ); + } + + m_state.pop_back(); + } }; template @@ -113,57 +113,57 @@ inline void Scene_forEachVisible( scene::Graph& graph, const VolumeTest& volume, class RenderHighlighted { -Renderer& m_renderer; -const VolumeTest& m_volume; + Renderer& m_renderer; + const VolumeTest& m_volume; public: -RenderHighlighted( Renderer& renderer, const VolumeTest& volume ) - : m_renderer( renderer ), m_volume( volume ){ -} -void render( const Renderable& renderable ) const { - switch ( m_renderer.getStyle() ) - { - case Renderer::eFullMaterials: - renderable.renderSolid( m_renderer, m_volume ); - break; - case Renderer::eWireframeOnly: - renderable.renderWireframe( m_renderer, m_volume ); - break; + RenderHighlighted( Renderer& renderer, const VolumeTest& volume ) + : m_renderer( renderer ), m_volume( volume ){ } -} -typedef ConstMemberCaller1 RenderCaller; - -bool pre( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { - m_renderer.PushState(); - - if ( Cullable_testVisible( instance, m_volume, parentVisible ) != c_volumeOutside ) { - Renderable* renderable = Instance_getRenderable( instance ); - if ( renderable ) { - renderable->viewChanged(); - } - - if ( Instance_isSelected( instance ) ) { - if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) { - m_renderer.Highlight( Renderer::eFace ); - } - else if ( renderable ) { - renderable->renderComponents( m_renderer, m_volume ); - } - //if( !(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && path.size() == 2) ) - //if( !( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && node_is_group( path.top() ) ) ) - if( !( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && Node_isEntity( path.top() ) ) ) - m_renderer.Highlight( Renderer::ePrimitive ); - } - - if ( renderable ) { - render( *renderable ); + void render( const Renderable& renderable ) const { + switch ( m_renderer.getStyle() ) + { + case Renderer::eFullMaterials: + renderable.renderSolid( m_renderer, m_volume ); + break; + case Renderer::eWireframeOnly: + renderable.renderWireframe( m_renderer, m_volume ); + break; } } + typedef ConstMemberCaller1 RenderCaller; - return true; -} -void post( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { - m_renderer.PopState(); -} + bool pre( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { + m_renderer.PushState(); + + if ( Cullable_testVisible( instance, m_volume, parentVisible ) != c_volumeOutside ) { + Renderable* renderable = Instance_getRenderable( instance ); + if ( renderable ) { + renderable->viewChanged(); + } + + if ( Instance_isSelected( instance ) ) { + if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) { + m_renderer.Highlight( Renderer::eFace ); + } + else if ( renderable ) { + renderable->renderComponents( m_renderer, m_volume ); + } + //if( !(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && path.size() == 2) ) + //if( !( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && node_is_group( path.top() ) ) ) + if( !( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent && Node_isEntity( path.top() ) ) ) + m_renderer.Highlight( Renderer::ePrimitive ); + } + + if ( renderable ) { + render( *renderable ); + } + } + + return true; + } + void post( const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible ) const { + m_renderer.PopState(); + } }; inline void Scene_Render( Renderer& renderer, const VolumeTest& volume ){ diff --git a/radiant/renderstate.cpp b/radiant/renderstate.cpp index d01eb433..200d8381 100644 --- a/radiant/renderstate.cpp +++ b/radiant/renderstate.cpp @@ -75,10 +75,10 @@ inline void debug_colour( const char* comment ){ Vector4 v; glGetFloatv( GL_CURRENT_COLOR, reinterpret_cast( &v ) ); globalOutputStream() << comment << " colour: " - << v[0] << " " - << v[1] << " " - << v[2] << " " - << v[3]; + << v[0] << " " + << v[1] << " " + << v[2] << " " + << v[3]; if ( glIsEnabled( GL_COLOR_ARRAY ) ) { globalOutputStream() << " ARRAY"; } @@ -119,9 +119,9 @@ void Renderer_ResetStats(){ const char* Renderer_GetStats(){ g_renderer_stats.clear(); g_renderer_stats << "prims: " << Unsigned( g_count_prims ) - << " | states: " << Unsigned( g_count_states ) - << " | transforms: " << Unsigned( g_count_transforms ) - << " | msec: " << g_timer.elapsed_msec(); + << " | states: " << Unsigned( g_count_states ) + << " | transforms: " << Unsigned( g_count_transforms ) + << " | msec: " << g_timer.elapsed_msec(); return g_renderer_stats.c_str(); } @@ -207,114 +207,114 @@ bool g_depthfillPass_enabled = false; class GLSLBumpProgram : public GLProgram { public: -GLhandleARB m_program; -qtexture_t* m_light_attenuation_xy; -qtexture_t* m_light_attenuation_z; -GLint u_view_origin; -GLint u_light_origin; -GLint u_light_color; -GLint u_bump_scale; -GLint u_specular_exponent; + GLhandleARB m_program; + qtexture_t* m_light_attenuation_xy; + qtexture_t* m_light_attenuation_z; + GLint u_view_origin; + GLint u_light_origin; + GLint u_light_color; + GLint u_bump_scale; + GLint u_specular_exponent; -GLSLBumpProgram() : m_program( 0 ), m_light_attenuation_xy( 0 ), m_light_attenuation_z( 0 ){ -} - -void create(){ - // create program - m_program = glCreateProgramObjectARB(); - - // create shader - { - StringOutputStream filename( 256 ); - createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_vp.glsl" ), GL_VERTEX_SHADER_ARB ); - createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_fp.glsl" ), GL_FRAGMENT_SHADER_ARB ); + GLSLBumpProgram() : m_program( 0 ), m_light_attenuation_xy( 0 ), m_light_attenuation_z( 0 ){ } - GLSLProgram_link( m_program ); - GLSLProgram_validate( m_program ); + void create(){ + // create program + m_program = glCreateProgramObjectARB(); - glUseProgramObjectARB( m_program ); + // create shader + { + StringOutputStream filename( 256 ); + createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_vp.glsl" ), GL_VERTEX_SHADER_ARB ); + createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_fp.glsl" ), GL_FRAGMENT_SHADER_ARB ); + } - glBindAttribLocationARB( m_program, c_attr_TexCoord0, "attr_TexCoord0" ); - glBindAttribLocationARB( m_program, c_attr_Tangent, "attr_Tangent" ); - glBindAttribLocationARB( m_program, c_attr_Binormal, "attr_Binormal" ); + GLSLProgram_link( m_program ); + GLSLProgram_validate( m_program ); - glUniform1iARB( glGetUniformLocationARB( m_program, "u_diffusemap" ), 0 ); - glUniform1iARB( glGetUniformLocationARB( m_program, "u_bumpmap" ), 1 ); - glUniform1iARB( glGetUniformLocationARB( m_program, "u_specularmap" ), 2 ); - glUniform1iARB( glGetUniformLocationARB( m_program, "u_attenuationmap_xy" ), 3 ); - glUniform1iARB( glGetUniformLocationARB( m_program, "u_attenuationmap_z" ), 4 ); + glUseProgramObjectARB( m_program ); - u_view_origin = glGetUniformLocationARB( m_program, "u_view_origin" ); - u_light_origin = glGetUniformLocationARB( m_program, "u_light_origin" ); - u_light_color = glGetUniformLocationARB( m_program, "u_light_color" ); - u_bump_scale = glGetUniformLocationARB( m_program, "u_bump_scale" ); - u_specular_exponent = glGetUniformLocationARB( m_program, "u_specular_exponent" ); + glBindAttribLocationARB( m_program, c_attr_TexCoord0, "attr_TexCoord0" ); + glBindAttribLocationARB( m_program, c_attr_Tangent, "attr_Tangent" ); + glBindAttribLocationARB( m_program, c_attr_Binormal, "attr_Binormal" ); - glUseProgramObjectARB( 0 ); + glUniform1iARB( glGetUniformLocationARB( m_program, "u_diffusemap" ), 0 ); + glUniform1iARB( glGetUniformLocationARB( m_program, "u_bumpmap" ), 1 ); + glUniform1iARB( glGetUniformLocationARB( m_program, "u_specularmap" ), 2 ); + glUniform1iARB( glGetUniformLocationARB( m_program, "u_attenuationmap_xy" ), 3 ); + glUniform1iARB( glGetUniformLocationARB( m_program, "u_attenuationmap_z" ), 4 ); - GlobalOpenGL_debugAssertNoErrors(); -} + u_view_origin = glGetUniformLocationARB( m_program, "u_view_origin" ); + u_light_origin = glGetUniformLocationARB( m_program, "u_light_origin" ); + u_light_color = glGetUniformLocationARB( m_program, "u_light_color" ); + u_bump_scale = glGetUniformLocationARB( m_program, "u_bump_scale" ); + u_specular_exponent = glGetUniformLocationARB( m_program, "u_specular_exponent" ); -void destroy(){ - glDeleteObjectARB( m_program ); - m_program = 0; -} + glUseProgramObjectARB( 0 ); -void enable(){ - glUseProgramObjectARB( m_program ); + GlobalOpenGL_debugAssertNoErrors(); + } - glEnableVertexAttribArrayARB( c_attr_TexCoord0 ); - glEnableVertexAttribArrayARB( c_attr_Tangent ); - glEnableVertexAttribArrayARB( c_attr_Binormal ); + void destroy(){ + glDeleteObjectARB( m_program ); + m_program = 0; + } - GlobalOpenGL_debugAssertNoErrors(); + void enable(){ + glUseProgramObjectARB( m_program ); - debug_string( "enable bump" ); - g_bumpGLSLPass_enabled = true; -} + glEnableVertexAttribArrayARB( c_attr_TexCoord0 ); + glEnableVertexAttribArrayARB( c_attr_Tangent ); + glEnableVertexAttribArrayARB( c_attr_Binormal ); -void disable(){ - glUseProgramObjectARB( 0 ); + GlobalOpenGL_debugAssertNoErrors(); - glDisableVertexAttribArrayARB( c_attr_TexCoord0 ); - glDisableVertexAttribArrayARB( c_attr_Tangent ); - glDisableVertexAttribArrayARB( c_attr_Binormal ); + debug_string( "enable bump" ); + g_bumpGLSLPass_enabled = true; + } - GlobalOpenGL_debugAssertNoErrors(); + void disable(){ + glUseProgramObjectARB( 0 ); - debug_string( "disable bump" ); - g_bumpGLSLPass_enabled = false; -} + glDisableVertexAttribArrayARB( c_attr_TexCoord0 ); + glDisableVertexAttribArrayARB( c_attr_Tangent ); + glDisableVertexAttribArrayARB( c_attr_Binormal ); -void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ - Matrix4 world2local( localToWorld ); - matrix4_affine_invert( world2local ); + GlobalOpenGL_debugAssertNoErrors(); - Vector3 localLight( origin ); - matrix4_transform_point( world2local, localLight ); + debug_string( "disable bump" ); + g_bumpGLSLPass_enabled = false; + } - Vector3 localViewer( viewer ); - matrix4_transform_point( world2local, localViewer ); + void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ + Matrix4 world2local( localToWorld ); + matrix4_affine_invert( world2local ); - Matrix4 local2light( world2light ); - matrix4_multiply_by_matrix4( local2light, localToWorld ); // local->world->light + Vector3 localLight( origin ); + matrix4_transform_point( world2local, localLight ); - glUniform3fARB( u_view_origin, localViewer.x(), localViewer.y(), localViewer.z() ); - glUniform3fARB( u_light_origin, localLight.x(), localLight.y(), localLight.z() ); - glUniform3fARB( u_light_color, colour.x(), colour.y(), colour.z() ); - glUniform1fARB( u_bump_scale, 1.0 ); - glUniform1fARB( u_specular_exponent, 32.0 ); + Vector3 localViewer( viewer ); + matrix4_transform_point( world2local, localViewer ); - glActiveTexture( GL_TEXTURE3 ); - glClientActiveTexture( GL_TEXTURE3 ); + Matrix4 local2light( world2light ); + matrix4_multiply_by_matrix4( local2light, localToWorld ); // local->world->light - glMatrixMode( GL_TEXTURE ); - glLoadMatrixf( reinterpret_cast( &local2light ) ); - glMatrixMode( GL_MODELVIEW ); + glUniform3fARB( u_view_origin, localViewer.x(), localViewer.y(), localViewer.z() ); + glUniform3fARB( u_light_origin, localLight.x(), localLight.y(), localLight.z() ); + glUniform3fARB( u_light_color, colour.x(), colour.y(), colour.z() ); + glUniform1fARB( u_bump_scale, 1.0 ); + glUniform1fARB( u_specular_exponent, 32.0 ); - GlobalOpenGL_debugAssertNoErrors(); -} + glActiveTexture( GL_TEXTURE3 ); + glClientActiveTexture( GL_TEXTURE3 ); + + glMatrixMode( GL_TEXTURE ); + glLoadMatrixf( reinterpret_cast( &local2light ) ); + glMatrixMode( GL_MODELVIEW ); + + GlobalOpenGL_debugAssertNoErrors(); + } }; GLSLBumpProgram g_bumpGLSL; @@ -323,43 +323,43 @@ GLSLBumpProgram g_bumpGLSL; class GLSLDepthFillProgram : public GLProgram { public: -GLhandleARB m_program; + GLhandleARB m_program; -void create(){ - // create program - m_program = glCreateProgramObjectARB(); + void create(){ + // create program + m_program = glCreateProgramObjectARB(); - // create shader - { - StringOutputStream filename( 256 ); - createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/zfill_vp.glsl" ), GL_VERTEX_SHADER_ARB ); - createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/zfill_fp.glsl" ), GL_FRAGMENT_SHADER_ARB ); + // create shader + { + StringOutputStream filename( 256 ); + createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/zfill_vp.glsl" ), GL_VERTEX_SHADER_ARB ); + createShader( m_program, filename( GlobalRadiant().getAppPath(), "gl/zfill_fp.glsl" ), GL_FRAGMENT_SHADER_ARB ); + } + + GLSLProgram_link( m_program ); + GLSLProgram_validate( m_program ); + + GlobalOpenGL_debugAssertNoErrors(); } - GLSLProgram_link( m_program ); - GLSLProgram_validate( m_program ); - - GlobalOpenGL_debugAssertNoErrors(); -} - -void destroy(){ - glDeleteObjectARB( m_program ); - m_program = 0; -} -void enable(){ - glUseProgramObjectARB( m_program ); - GlobalOpenGL_debugAssertNoErrors(); - debug_string( "enable depthfill" ); - g_depthfillPass_enabled = true; -} -void disable(){ - glUseProgramObjectARB( 0 ); - GlobalOpenGL_debugAssertNoErrors(); - debug_string( "disable depthfill" ); - g_depthfillPass_enabled = false; -} -void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ -} + void destroy(){ + glDeleteObjectARB( m_program ); + m_program = 0; + } + void enable(){ + glUseProgramObjectARB( m_program ); + GlobalOpenGL_debugAssertNoErrors(); + debug_string( "enable depthfill" ); + g_depthfillPass_enabled = true; + } + void disable(){ + glUseProgramObjectARB( 0 ); + GlobalOpenGL_debugAssertNoErrors(); + debug_string( "disable depthfill" ); + g_depthfillPass_enabled = false; + } + void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ + } }; GLSLDepthFillProgram g_depthFillGLSL; @@ -390,153 +390,153 @@ void createProgram( const char* filename, GLenum type ){ class ARBBumpProgram : public GLProgram { public: -GLuint m_vertex_program; -GLuint m_fragment_program; + GLuint m_vertex_program; + GLuint m_fragment_program; -void create(){ - glEnable( GL_VERTEX_PROGRAM_ARB ); - glEnable( GL_FRAGMENT_PROGRAM_ARB ); + void create(){ + glEnable( GL_VERTEX_PROGRAM_ARB ); + glEnable( GL_FRAGMENT_PROGRAM_ARB ); - { - glGenProgramsARB( 1, &m_vertex_program ); - glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); - StringOutputStream filename( 256 ); - createProgram( filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_vp.glp" ), GL_VERTEX_PROGRAM_ARB ); + { + glGenProgramsARB( 1, &m_vertex_program ); + glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); + StringOutputStream filename( 256 ); + createProgram( filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_vp.glp" ), GL_VERTEX_PROGRAM_ARB ); - glGenProgramsARB( 1, &m_fragment_program ); - glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); - createProgram( filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_fp.glp" ), GL_FRAGMENT_PROGRAM_ARB ); + glGenProgramsARB( 1, &m_fragment_program ); + glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); + createProgram( filename( GlobalRadiant().getAppPath(), "gl/lighting_DBS_omni_fp.glp" ), GL_FRAGMENT_PROGRAM_ARB ); + } + + glDisable( GL_VERTEX_PROGRAM_ARB ); + glDisable( GL_FRAGMENT_PROGRAM_ARB ); + + GlobalOpenGL_debugAssertNoErrors(); } - glDisable( GL_VERTEX_PROGRAM_ARB ); - glDisable( GL_FRAGMENT_PROGRAM_ARB ); + void destroy(){ + glDeleteProgramsARB( 1, &m_vertex_program ); + glDeleteProgramsARB( 1, &m_fragment_program ); + GlobalOpenGL_debugAssertNoErrors(); + } - GlobalOpenGL_debugAssertNoErrors(); -} + void enable(){ + glEnable( GL_VERTEX_PROGRAM_ARB ); + glEnable( GL_FRAGMENT_PROGRAM_ARB ); + glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); + glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); -void destroy(){ - glDeleteProgramsARB( 1, &m_vertex_program ); - glDeleteProgramsARB( 1, &m_fragment_program ); - GlobalOpenGL_debugAssertNoErrors(); -} + glEnableVertexAttribArrayARB( 8 ); + glEnableVertexAttribArrayARB( 9 ); + glEnableVertexAttribArrayARB( 10 ); + glEnableVertexAttribArrayARB( 11 ); -void enable(){ - glEnable( GL_VERTEX_PROGRAM_ARB ); - glEnable( GL_FRAGMENT_PROGRAM_ARB ); - glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); - glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); + GlobalOpenGL_debugAssertNoErrors(); + } - glEnableVertexAttribArrayARB( 8 ); - glEnableVertexAttribArrayARB( 9 ); - glEnableVertexAttribArrayARB( 10 ); - glEnableVertexAttribArrayARB( 11 ); + void disable(){ + glDisable( GL_VERTEX_PROGRAM_ARB ); + glDisable( GL_FRAGMENT_PROGRAM_ARB ); - GlobalOpenGL_debugAssertNoErrors(); -} + glDisableVertexAttribArrayARB( 8 ); + glDisableVertexAttribArrayARB( 9 ); + glDisableVertexAttribArrayARB( 10 ); + glDisableVertexAttribArrayARB( 11 ); -void disable(){ - glDisable( GL_VERTEX_PROGRAM_ARB ); - glDisable( GL_FRAGMENT_PROGRAM_ARB ); + GlobalOpenGL_debugAssertNoErrors(); + } - glDisableVertexAttribArrayARB( 8 ); - glDisableVertexAttribArrayARB( 9 ); - glDisableVertexAttribArrayARB( 10 ); - glDisableVertexAttribArrayARB( 11 ); + void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ + Matrix4 world2local( localToWorld ); + matrix4_affine_invert( world2local ); - GlobalOpenGL_debugAssertNoErrors(); -} + Vector3 localLight( origin ); + matrix4_transform_point( world2local, localLight ); -void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ - Matrix4 world2local( localToWorld ); - matrix4_affine_invert( world2local ); + Vector3 localViewer( viewer ); + matrix4_transform_point( world2local, localViewer ); - Vector3 localLight( origin ); - matrix4_transform_point( world2local, localLight ); + Matrix4 local2light( world2light ); + matrix4_multiply_by_matrix4( local2light, localToWorld ); // local->world->light - Vector3 localViewer( viewer ); - matrix4_transform_point( world2local, localViewer ); + // view origin + glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 4, localViewer.x(), localViewer.y(), localViewer.z(), 0 ); - Matrix4 local2light( world2light ); - matrix4_multiply_by_matrix4( local2light, localToWorld ); // local->world->light + // light origin + glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 2, localLight.x(), localLight.y(), localLight.z(), 1 ); - // view origin - glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 4, localViewer.x(), localViewer.y(), localViewer.z(), 0 ); + // light colour + glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 3, colour.x(), colour.y(), colour.z(), 0 ); - // light origin - glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 2, localLight.x(), localLight.y(), localLight.z(), 1 ); + // bump scale + glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 1, 1, 0, 0, 0 ); - // light colour - glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 3, colour.x(), colour.y(), colour.z(), 0 ); - - // bump scale - glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 1, 1, 0, 0, 0 ); - - // specular exponent - glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 5, 32, 0, 0, 0 ); + // specular exponent + glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 5, 32, 0, 0, 0 ); - glActiveTexture( GL_TEXTURE3 ); - glClientActiveTexture( GL_TEXTURE3 ); + glActiveTexture( GL_TEXTURE3 ); + glClientActiveTexture( GL_TEXTURE3 ); - glMatrixMode( GL_TEXTURE ); - glLoadMatrixf( reinterpret_cast( &local2light ) ); - glMatrixMode( GL_MODELVIEW ); + glMatrixMode( GL_TEXTURE ); + glLoadMatrixf( reinterpret_cast( &local2light ) ); + glMatrixMode( GL_MODELVIEW ); - GlobalOpenGL_debugAssertNoErrors(); -} + GlobalOpenGL_debugAssertNoErrors(); + } }; class ARBDepthFillProgram : public GLProgram { public: -GLuint m_vertex_program; -GLuint m_fragment_program; + GLuint m_vertex_program; + GLuint m_fragment_program; -void create(){ - glEnable( GL_VERTEX_PROGRAM_ARB ); - glEnable( GL_FRAGMENT_PROGRAM_ARB ); + void create(){ + glEnable( GL_VERTEX_PROGRAM_ARB ); + glEnable( GL_FRAGMENT_PROGRAM_ARB ); - { - glGenProgramsARB( 1, &m_vertex_program ); - glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); - StringOutputStream filename( 256 ); - createProgram( filename( GlobalRadiant().getAppPath(), "gl/zfill_vp.glp" ), GL_VERTEX_PROGRAM_ARB ); + { + glGenProgramsARB( 1, &m_vertex_program ); + glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); + StringOutputStream filename( 256 ); + createProgram( filename( GlobalRadiant().getAppPath(), "gl/zfill_vp.glp" ), GL_VERTEX_PROGRAM_ARB ); - glGenProgramsARB( 1, &m_fragment_program ); - glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); - createProgram( filename( GlobalRadiant().getAppPath(), "gl/zfill_fp.glp" ), GL_FRAGMENT_PROGRAM_ARB ); + glGenProgramsARB( 1, &m_fragment_program ); + glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); + createProgram( filename( GlobalRadiant().getAppPath(), "gl/zfill_fp.glp" ), GL_FRAGMENT_PROGRAM_ARB ); + } + + glDisable( GL_VERTEX_PROGRAM_ARB ); + glDisable( GL_FRAGMENT_PROGRAM_ARB ); + + GlobalOpenGL_debugAssertNoErrors(); } - glDisable( GL_VERTEX_PROGRAM_ARB ); - glDisable( GL_FRAGMENT_PROGRAM_ARB ); + void destroy(){ + glDeleteProgramsARB( 1, &m_vertex_program ); + glDeleteProgramsARB( 1, &m_fragment_program ); + GlobalOpenGL_debugAssertNoErrors(); + } - GlobalOpenGL_debugAssertNoErrors(); -} + void enable(){ + glEnable( GL_VERTEX_PROGRAM_ARB ); + glEnable( GL_FRAGMENT_PROGRAM_ARB ); + glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); + glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); -void destroy(){ - glDeleteProgramsARB( 1, &m_vertex_program ); - glDeleteProgramsARB( 1, &m_fragment_program ); - GlobalOpenGL_debugAssertNoErrors(); -} + GlobalOpenGL_debugAssertNoErrors(); + } -void enable(){ - glEnable( GL_VERTEX_PROGRAM_ARB ); - glEnable( GL_FRAGMENT_PROGRAM_ARB ); - glBindProgramARB( GL_VERTEX_PROGRAM_ARB, m_vertex_program ); - glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, m_fragment_program ); + void disable(){ + glDisable( GL_VERTEX_PROGRAM_ARB ); + glDisable( GL_FRAGMENT_PROGRAM_ARB ); - GlobalOpenGL_debugAssertNoErrors(); -} + GlobalOpenGL_debugAssertNoErrors(); + } -void disable(){ - glDisable( GL_VERTEX_PROGRAM_ARB ); - glDisable( GL_FRAGMENT_PROGRAM_ARB ); - - GlobalOpenGL_debugAssertNoErrors(); -} - -void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ -} + void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ){ + } }; ARBBumpProgram g_bumpARB; @@ -626,23 +626,23 @@ void enableVertexProgram(){ //combiner 0 does tex0+tex1 -> spare0 glCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, - GL_UNSIGNED_IDENTITY_NV, GL_RGB ); + GL_UNSIGNED_IDENTITY_NV, GL_RGB ); glCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, - GL_UNSIGNED_INVERT_NV, GL_RGB ); + GL_UNSIGNED_INVERT_NV, GL_RGB ); glCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, - GL_UNSIGNED_IDENTITY_NV, GL_RGB ); + GL_UNSIGNED_IDENTITY_NV, GL_RGB ); glCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, - GL_UNSIGNED_INVERT_NV, GL_RGB ); + GL_UNSIGNED_INVERT_NV, GL_RGB ); glCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, - GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); + GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); //combiner 1 does tex2 dot tex3 -> spare1 glCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, - GL_EXPAND_NORMAL_NV, GL_RGB ); + GL_EXPAND_NORMAL_NV, GL_RGB ); glCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, - GL_EXPAND_NORMAL_NV, GL_RGB ); + GL_EXPAND_NORMAL_NV, GL_RGB ); glCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV, - GL_NONE, GL_NONE, GL_TRUE, GL_FALSE, GL_FALSE ); + GL_NONE, GL_NONE, GL_TRUE, GL_FALSE, GL_FALSE ); @@ -705,10 +705,10 @@ void disableVertexProgram(){ class GLstringNV { public: -const GLubyte* m_string; -const GLint m_length; -GLstringNV( const char* string ) : m_string( reinterpret_cast( string ) ), m_length( GLint( string_length( string ) ) ){ -} + const GLubyte* m_string; + const GLint m_length; + GLstringNV( const char* string ) : m_string( reinterpret_cast( string ) ), m_length( GLint( string_length( string ) ) ){ + } }; GLstringNV g_light_origin( "light_origin" ); @@ -840,36 +840,36 @@ void OpenGLState_constructDefault( OpenGLState& state ){ class OpenGLStateBucket { public: -struct RenderTransform -{ - const Matrix4* m_transform; - const OpenGLRenderable *m_renderable; - const RendererLight* m_light; + struct RenderTransform + { + const Matrix4* m_transform; + const OpenGLRenderable *m_renderable; + const RendererLight* m_light; - RenderTransform( const OpenGLRenderable& renderable, const Matrix4& transform, const RendererLight* light ) - : m_transform( &transform ), m_renderable( &renderable ), m_light( light ){ - } -}; + RenderTransform( const OpenGLRenderable& renderable, const Matrix4& transform, const RendererLight* light ) + : m_transform( &transform ), m_renderable( &renderable ), m_light( light ){ + } + }; -typedef std::vector Renderables; + typedef std::vector Renderables; private: -OpenGLState m_state; -Renderables m_renderables; + OpenGLState m_state; + Renderables m_renderables; public: -OpenGLStateBucket(){ -} -void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const RendererLight* light = 0 ){ - m_renderables.push_back( RenderTransform( renderable, modelview, light ) ); -} + OpenGLStateBucket(){ + } + void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const RendererLight* light = 0 ){ + m_renderables.push_back( RenderTransform( renderable, modelview, light ) ); + } -OpenGLState& state(){ - return m_state; -} + OpenGLState& state(){ + return m_state; + } -void render( OpenGLState& current, unsigned int globalstate, const Vector3& viewer ); + void render( OpenGLState& current, unsigned int globalstate, const Vector3& viewer ); }; #define LIGHT_SHADER_DEBUG 0 @@ -882,9 +882,9 @@ LightDebugShaders g_lightDebugShaders; class OpenGLStateLess { public: -bool operator()( const OpenGLState& self, const OpenGLState& other ) const { - return OpenGLState_less( self, other ); -} + bool operator()( const OpenGLState& self, const OpenGLState& other ) const { + return OpenGLState_less( self, other ); + } }; typedef ConstReference OpenGLStateReference; @@ -893,158 +893,158 @@ OpenGLStates g_state_sorted; class OpenGLStateBucketAdd { -OpenGLStateBucket& m_bucket; -const OpenGLRenderable& m_renderable; -const Matrix4& m_modelview; + OpenGLStateBucket& m_bucket; + const OpenGLRenderable& m_renderable; + const Matrix4& m_modelview; public: -typedef const RendererLight& first_argument_type; + typedef const RendererLight& first_argument_type; -OpenGLStateBucketAdd( OpenGLStateBucket& bucket, const OpenGLRenderable& renderable, const Matrix4& modelview ) : - m_bucket( bucket ), m_renderable( renderable ), m_modelview( modelview ){ -} -void operator()( const RendererLight& light ){ - m_bucket.addRenderable( m_renderable, m_modelview, &light ); -} + OpenGLStateBucketAdd( OpenGLStateBucket& bucket, const OpenGLRenderable& renderable, const Matrix4& modelview ) : + m_bucket( bucket ), m_renderable( renderable ), m_modelview( modelview ){ + } + void operator()( const RendererLight& light ){ + m_bucket.addRenderable( m_renderable, m_modelview, &light ); + } }; class CountLights { -std::size_t m_count; + std::size_t m_count; public: -typedef RendererLight& first_argument_type; + typedef RendererLight& first_argument_type; -CountLights() : m_count( 0 ){ -} -void operator()( const RendererLight& light ){ - ++m_count; -} -std::size_t count() const { - return m_count; -} + CountLights() : m_count( 0 ){ + } + void operator()( const RendererLight& light ){ + ++m_count; + } + std::size_t count() const { + return m_count; + } }; class OpenGLShader final : public Shader { -typedef std::list Passes; -Passes m_passes; -IShader* m_shader; -std::size_t m_used; -ModuleObservers m_observers; + typedef std::list Passes; + Passes m_passes; + IShader* m_shader; + std::size_t m_used; + ModuleObservers m_observers; public: -OpenGLShader() : m_shader( 0 ), m_used( 0 ){ -} -~OpenGLShader(){ -} -void construct( const char* name ); -void destroy(){ - if ( m_shader ) { - m_shader->DecRef(); + OpenGLShader() : m_shader( 0 ), m_used( 0 ){ } - m_shader = 0; + ~OpenGLShader(){ + } + void construct( const char* name ); + void destroy(){ + if ( m_shader ) { + m_shader->DecRef(); + } + m_shader = 0; - for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) - { - delete *i; + for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) + { + delete *i; + } + m_passes.clear(); } - m_passes.clear(); -} -void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights ){ - for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) - { + void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights ){ + for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) + { #if LIGHT_SHADER_DEBUG - if ( ( ( *i )->state().m_state & RENDER_BUMP ) != 0 ) { - if ( lights != 0 ) { - CountLights counter; - lights->forEachLight( makeCallback1( counter ) ); - globalOutputStream() << "count = " << counter.count() << "\n"; - for ( std::size_t i = 0; i < counter.count(); ++i ) - { - g_lightDebugShaders[counter.count()]->addRenderable( renderable, modelview ); + if ( ( ( *i )->state().m_state & RENDER_BUMP ) != 0 ) { + if ( lights != 0 ) { + CountLights counter; + lights->forEachLight( makeCallback1( counter ) ); + globalOutputStream() << "count = " << counter.count() << "\n"; + for ( std::size_t i = 0; i < counter.count(); ++i ) + { + g_lightDebugShaders[counter.count()]->addRenderable( renderable, modelview ); + } } } - } - else + else #else - if ( ( ( *i )->state().m_state & RENDER_BUMP ) != 0 ) { - if ( lights != 0 ) { - OpenGLStateBucketAdd add( *( *i ), renderable, modelview ); - lights->forEachLight( makeCallback1( add ) ); + if ( ( ( *i )->state().m_state & RENDER_BUMP ) != 0 ) { + if ( lights != 0 ) { + OpenGLStateBucketAdd add( *( *i ), renderable, modelview ); + lights->forEachLight( makeCallback1( add ) ); + } + } + else +#endif + { + ( *i )->addRenderable( renderable, modelview ); } } - else -#endif - { - ( *i )->addRenderable( renderable, modelview ); + } + void incrementUsed(){ + if ( ++m_used == 1 && m_shader != 0 ) { + m_shader->SetInUse( true ); } } -} -void incrementUsed(){ - if ( ++m_used == 1 && m_shader != 0 ) { - m_shader->SetInUse( true ); + void decrementUsed(){ + if ( --m_used == 0 && m_shader != 0 ) { + m_shader->SetInUse( false ); + } } -} -void decrementUsed(){ - if ( --m_used == 0 && m_shader != 0 ) { - m_shader->SetInUse( false ); + bool realised() const { + return m_shader != 0; } -} -bool realised() const { - return m_shader != 0; -} -void attach( ModuleObserver& observer ){ - if ( realised() ) { - observer.realise(); + void attach( ModuleObserver& observer ){ + if ( realised() ) { + observer.realise(); + } + m_observers.attach( observer ); } - m_observers.attach( observer ); -} -void detach( ModuleObserver& observer ){ - if ( realised() ) { - observer.unrealise(); + void detach( ModuleObserver& observer ){ + if ( realised() ) { + observer.unrealise(); + } + m_observers.detach( observer ); } - m_observers.detach( observer ); -} -void realise( const CopiedString& name ){ - construct( name.c_str() ); + void realise( const CopiedString& name ){ + construct( name.c_str() ); - if ( m_used != 0 && m_shader != 0 ) { - m_shader->SetInUse( true ); + if ( m_used != 0 && m_shader != 0 ) { + m_shader->SetInUse( true ); + } + + for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) + { + g_state_sorted.insert( OpenGLStates::value_type( OpenGLStateReference( ( *i )->state() ), *i ) ); + } + + m_observers.realise(); } + void unrealise(){ + m_observers.unrealise(); - for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) - { - g_state_sorted.insert( OpenGLStates::value_type( OpenGLStateReference( ( *i )->state() ), *i ) ); + for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) + { + g_state_sorted.erase( OpenGLStateReference( ( *i )->state() ) ); + } + + destroy(); } - - m_observers.realise(); -} -void unrealise(){ - m_observers.unrealise(); - - for ( Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i ) - { - g_state_sorted.erase( OpenGLStateReference( ( *i )->state() ) ); + qtexture_t& getTexture() const { + ASSERT_NOTNULL( m_shader ); + return *m_shader->getTexture(); + } + unsigned int getFlags() const { + ASSERT_NOTNULL( m_shader ); + return m_shader->getFlags(); + } + IShader& getShader() const { + ASSERT_NOTNULL( m_shader ); + return *m_shader; + } + OpenGLState& appendDefaultPass(){ + m_passes.push_back( new OpenGLStateBucket ); + OpenGLState& state = m_passes.back()->state(); + OpenGLState_constructDefault( state ); + return state; } - - destroy(); -} -qtexture_t& getTexture() const { - ASSERT_NOTNULL( m_shader ); - return *m_shader->getTexture(); -} -unsigned int getFlags() const { - ASSERT_NOTNULL( m_shader ); - return m_shader->getFlags(); -} -IShader& getShader() const { - ASSERT_NOTNULL( m_shader ); - return *m_shader; -} -OpenGLState& appendDefaultPass(){ - m_passes.push_back( new OpenGLStateBucket ); - OpenGLState& state = m_passes.back()->state(); - OpenGLState_constructDefault( state ); - return state; -} }; @@ -1058,62 +1058,62 @@ typedef std::set RendererLights; class LinearLightList : public LightList { -LightCullable& m_cullable; -RendererLights& m_allLights; -Callback m_evaluateChanged; + LightCullable& m_cullable; + RendererLights& m_allLights; + Callback m_evaluateChanged; -typedef std::list Lights; -mutable Lights m_lights; -mutable bool m_lightsChanged; + typedef std::list Lights; + mutable Lights m_lights; + mutable bool m_lightsChanged; public: -LinearLightList( LightCullable& cullable, RendererLights& lights, const Callback& evaluateChanged ) : - m_cullable( cullable ), m_allLights( lights ), m_evaluateChanged( evaluateChanged ){ - m_lightsChanged = true; -} -void evaluateLights() const { - m_evaluateChanged(); - if ( m_lightsChanged ) { - m_lightsChanged = false; + LinearLightList( LightCullable& cullable, RendererLights& lights, const Callback& evaluateChanged ) : + m_cullable( cullable ), m_allLights( lights ), m_evaluateChanged( evaluateChanged ){ + m_lightsChanged = true; + } + void evaluateLights() const { + m_evaluateChanged(); + if ( m_lightsChanged ) { + m_lightsChanged = false; - m_lights.clear(); - m_cullable.clearLights(); - for ( RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i ) - { - if ( lightEnabled( *( *i ), m_cullable ) ) { - m_lights.push_back( *i ); - m_cullable.insertLight( *( *i ) ); + m_lights.clear(); + m_cullable.clearLights(); + for ( RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i ) + { + if ( lightEnabled( *( *i ), m_cullable ) ) { + m_lights.push_back( *i ); + m_cullable.insertLight( *( *i ) ); + } } } - } #if ( DEBUG_LIGHT_SYNC ) - else - { - Lights lights; - for ( RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i ) + else { - if ( lightEnabled( *( *i ), m_cullable ) ) { - lights.push_back( *i ); + Lights lights; + for ( RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i ) + { + if ( lightEnabled( *( *i ), m_cullable ) ) { + lights.push_back( *i ); + } } - } - ASSERT_MESSAGE( - !std::lexicographical_compare( lights.begin(), lights.end(), m_lights.begin(), m_lights.end() ) - && !std::lexicographical_compare( m_lights.begin(), m_lights.end(), lights.begin(), lights.end() ), - "lights out of sync" + ASSERT_MESSAGE( + !std::lexicographical_compare( lights.begin(), lights.end(), m_lights.begin(), m_lights.end() ) + && !std::lexicographical_compare( m_lights.begin(), m_lights.end(), lights.begin(), lights.end() ), + "lights out of sync" ); - } + } #endif -} -void forEachLight( const RendererLightCallback& callback ) const { - evaluateLights(); - - for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) - { - callback( *( *i ) ); } -} -void lightsChanged() const { - m_lightsChanged = true; -} + void forEachLight( const RendererLightCallback& callback ) const { + evaluateLights(); + + for ( Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i ) + { + callback( *( *i ) ); + } + } + void lightsChanged() const { + m_lightsChanged = true; + } }; inline void setFogState( const OpenGLFogState& state ){ @@ -1130,360 +1130,360 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned class OpenGLShaderCache final : public ShaderCache, public TexturesCacheObserver, public ModuleObserver { -class CreateOpenGLShader -{ -OpenGLShaderCache* m_cache; -public: -explicit CreateOpenGLShader( OpenGLShaderCache* cache = 0 ) - : m_cache( cache ){ -} -OpenGLShader* construct( const CopiedString& name ){ - OpenGLShader* shader = new OpenGLShader; - if ( m_cache->realised() ) { - shader->realise( name ); - } - return shader; -} -void destroy( OpenGLShader* shader ){ - if ( m_cache->realised() ) { - shader->unrealise(); - } - delete shader; -} -}; + class CreateOpenGLShader + { + OpenGLShaderCache* m_cache; + public: + explicit CreateOpenGLShader( OpenGLShaderCache* cache = 0 ) + : m_cache( cache ){ + } + OpenGLShader* construct( const CopiedString& name ){ + OpenGLShader* shader = new OpenGLShader; + if ( m_cache->realised() ) { + shader->realise( name ); + } + return shader; + } + void destroy( OpenGLShader* shader ){ + if ( m_cache->realised() ) { + shader->unrealise(); + } + delete shader; + } + }; -typedef HashedCache, CreateOpenGLShader> Shaders; -Shaders m_shaders; -std::size_t m_unrealised; + typedef HashedCache, CreateOpenGLShader> Shaders; + Shaders m_shaders; + std::size_t m_unrealised; -bool m_lightingEnabled; -bool m_lightingSupported; -bool m_useShaderLanguage; + bool m_lightingEnabled; + bool m_lightingSupported; + bool m_useShaderLanguage; public: -OpenGLShaderCache() - : m_shaders( CreateOpenGLShader( this ) ), - m_unrealised( 3 ), // wait until shaders, gl-context and textures are realised before creating any render-states - m_lightingEnabled( true ), - m_lightingSupported( false ), - m_useShaderLanguage( false ), - m_lightsChanged( true ), - m_traverseRenderablesMutex( false ){ -} -~OpenGLShaderCache(){ - for ( Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) - { - globalOutputStream() << "leaked shader: " << makeQuoted( ( *i ).key.c_str() ) << "\n"; + OpenGLShaderCache() : + m_shaders( CreateOpenGLShader( this ) ), + m_unrealised( 3 ), // wait until shaders, gl-context and textures are realised before creating any render-states + m_lightingEnabled( true ), + m_lightingSupported( false ), + m_useShaderLanguage( false ), + m_lightsChanged( true ), + m_traverseRenderablesMutex( false ){ } -} -Shader* capture( const char* name ){ - ASSERT_MESSAGE( name[0] == '$' - || *name == '[' - || *name == '<' - || *name == '(' - || *name == '{' - || strchr( name, '\\' ) == 0, "shader name contains invalid characters: \"" << name << "\"" ); -#if DEBUG_SHADERS - globalOutputStream() << "shaders capture: " << makeQuoted( name ) << '\n'; -#endif - return m_shaders.capture( name ).get(); -} -void release( const char *name ){ -#if DEBUG_SHADERS - globalOutputStream() << "shaders release: " << makeQuoted( name ) << '\n'; -#endif - m_shaders.release( name ); -} -void render( RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer ){ - glMatrixMode( GL_PROJECTION ); - glLoadMatrixf( reinterpret_cast( &projection ) ); - #if 0 - //qglGetFloatv(GL_PROJECTION_MATRIX, reinterpret_cast(&projection)); - #endif - - glMatrixMode( GL_MODELVIEW ); - glLoadMatrixf( reinterpret_cast( &modelview ) ); - #if 0 - //qglGetFloatv(GL_MODELVIEW_MATRIX, reinterpret_cast(&modelview)); - #endif - - ASSERT_MESSAGE( realised(), "render states are not realised" ); - - // global settings that are not set in renderstates - glFrontFace( GL_CW ); - glCullFace( GL_BACK ); - glPolygonOffset( -1, 1 ); - { - const GLubyte pattern[132] = { - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55 - }; - glPolygonStipple( pattern ); - } - glEnableClientState( GL_VERTEX_ARRAY ); - g_vertexArray_enabled = true; - glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); - - if ( GlobalOpenGL().GL_1_3() ) { - glActiveTexture( GL_TEXTURE0 ); - glClientActiveTexture( GL_TEXTURE0 ); - } - - if ( GlobalOpenGL().ARB_shader_objects() ) { - glUseProgramObjectARB( 0 ); - glDisableVertexAttribArrayARB( c_attr_TexCoord0 ); - glDisableVertexAttribArrayARB( c_attr_Tangent ); - glDisableVertexAttribArrayARB( c_attr_Binormal ); - } - - if ( globalstate & RENDER_TEXTURE ) { - glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); - glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); - } - - OpenGLState current; - OpenGLState_constructDefault( current ); - current.m_sort = OpenGLState::eSortFirst; - - // default renderstate settings - glLineStipple( current.m_linestipple_factor, current.m_linestipple_pattern ); - glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); - glDisable( GL_LIGHTING ); - glDisable( GL_TEXTURE_2D ); - glDisableClientState( GL_TEXTURE_COORD_ARRAY ); - g_texcoordArray_enabled = false; - glDisableClientState( GL_COLOR_ARRAY ); - g_colorArray_enabled = false; - glDisableClientState( GL_NORMAL_ARRAY ); - g_normalArray_enabled = false; - glDisable( GL_BLEND ); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - glDisable( GL_CULL_FACE ); - glShadeModel( GL_FLAT ); - glDisable( GL_DEPTH_TEST ); - glDepthMask( GL_FALSE ); - glDisable( GL_ALPHA_TEST ); - glDisable( GL_LINE_STIPPLE ); - glDisable( GL_POLYGON_STIPPLE ); - glDisable( GL_POLYGON_OFFSET_LINE ); - - glBindTexture( GL_TEXTURE_2D, 0 ); - glColor4f( 1,1,1,1 ); - glDepthFunc( GL_LESS ); - glAlphaFunc( GL_ALWAYS, 0 ); - glLineWidth( 1 ); - glPointSize( 1 ); - - glHint( GL_FOG_HINT, GL_NICEST ); - glDisable( GL_FOG ); - setFogState( OpenGLFogState() ); - - GlobalOpenGL_debugAssertNoErrors(); - - debug_string( "begin rendering" ); - for ( OpenGLStates::iterator i = g_state_sorted.begin(); i != g_state_sorted.end(); ++i ) - { - ( *i ).second->render( current, globalstate, viewer ); - } - debug_string( "end rendering" ); - - OpenGLState reset = current; /* popmatrix after RENDER_TEXT */ - reset.m_state = current.m_state & ~RENDER_TEXT; - OpenGLState_apply( reset, current, globalstate ); -} -void realise(){ - if ( --m_unrealised == 0 ) { - if ( lightingSupported() && lightingEnabled() ) { - if ( useShaderLanguage() ) { - g_bumpGLSL.create(); - g_depthFillGLSL.create(); - } - else - { - g_bumpARB.create(); - g_depthFillARB.create(); - } - } - + ~OpenGLShaderCache(){ for ( Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) { - if ( !( *i ).value.empty() ) { - ( *i ).value->realise( i->key ); - } + globalOutputStream() << "leaked shader: " << makeQuoted( ( *i ).key.c_str() ) << "\n"; } } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - for ( Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) + Shader* capture( const char* name ){ + ASSERT_MESSAGE( name[0] == '$' + || *name == '[' + || *name == '<' + || *name == '(' + || *name == '{' + || strchr( name, '\\' ) == 0, "shader name contains invalid characters: \"" << name << "\"" ); +#if DEBUG_SHADERS + globalOutputStream() << "shaders capture: " << makeQuoted( name ) << '\n'; +#endif + return m_shaders.capture( name ).get(); + } + void release( const char *name ){ +#if DEBUG_SHADERS + globalOutputStream() << "shaders release: " << makeQuoted( name ) << '\n'; +#endif + m_shaders.release( name ); + } + void render( RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer ){ + glMatrixMode( GL_PROJECTION ); + glLoadMatrixf( reinterpret_cast( &projection ) ); +#if 0 + //qglGetFloatv(GL_PROJECTION_MATRIX, reinterpret_cast(&projection)); +#endif + + glMatrixMode( GL_MODELVIEW ); + glLoadMatrixf( reinterpret_cast( &modelview ) ); +#if 0 + //qglGetFloatv(GL_MODELVIEW_MATRIX, reinterpret_cast(&modelview)); +#endif + + ASSERT_MESSAGE( realised(), "render states are not realised" ); + + // global settings that are not set in renderstates + glFrontFace( GL_CW ); + glCullFace( GL_BACK ); + glPolygonOffset( -1, 1 ); { - if ( !( *i ).value.empty() ) { - ( *i ).value->unrealise(); - } + const GLubyte pattern[132] = { + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55 + }; + glPolygonStipple( pattern ); } - if ( GlobalOpenGL().contextValid && lightingSupported() && lightingEnabled() ) { - if ( useShaderLanguage() ) { - g_bumpGLSL.destroy(); - g_depthFillGLSL.destroy(); + glEnableClientState( GL_VERTEX_ARRAY ); + g_vertexArray_enabled = true; + glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); + + if ( GlobalOpenGL().GL_1_3() ) { + glActiveTexture( GL_TEXTURE0 ); + glClientActiveTexture( GL_TEXTURE0 ); + } + + if ( GlobalOpenGL().ARB_shader_objects() ) { + glUseProgramObjectARB( 0 ); + glDisableVertexAttribArrayARB( c_attr_TexCoord0 ); + glDisableVertexAttribArrayARB( c_attr_Tangent ); + glDisableVertexAttribArrayARB( c_attr_Binormal ); + } + + if ( globalstate & RENDER_TEXTURE ) { + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + } + + OpenGLState current; + OpenGLState_constructDefault( current ); + current.m_sort = OpenGLState::eSortFirst; + + // default renderstate settings + glLineStipple( current.m_linestipple_factor, current.m_linestipple_pattern ); + glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); + glDisable( GL_LIGHTING ); + glDisable( GL_TEXTURE_2D ); + glDisableClientState( GL_TEXTURE_COORD_ARRAY ); + g_texcoordArray_enabled = false; + glDisableClientState( GL_COLOR_ARRAY ); + g_colorArray_enabled = false; + glDisableClientState( GL_NORMAL_ARRAY ); + g_normalArray_enabled = false; + glDisable( GL_BLEND ); + glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glDisable( GL_CULL_FACE ); + glShadeModel( GL_FLAT ); + glDisable( GL_DEPTH_TEST ); + glDepthMask( GL_FALSE ); + glDisable( GL_ALPHA_TEST ); + glDisable( GL_LINE_STIPPLE ); + glDisable( GL_POLYGON_STIPPLE ); + glDisable( GL_POLYGON_OFFSET_LINE ); + + glBindTexture( GL_TEXTURE_2D, 0 ); + glColor4f( 1,1,1,1 ); + glDepthFunc( GL_LESS ); + glAlphaFunc( GL_ALWAYS, 0 ); + glLineWidth( 1 ); + glPointSize( 1 ); + + glHint( GL_FOG_HINT, GL_NICEST ); + glDisable( GL_FOG ); + setFogState( OpenGLFogState() ); + + GlobalOpenGL_debugAssertNoErrors(); + + debug_string( "begin rendering" ); + for ( OpenGLStates::iterator i = g_state_sorted.begin(); i != g_state_sorted.end(); ++i ) + { + ( *i ).second->render( current, globalstate, viewer ); + } + debug_string( "end rendering" ); + + OpenGLState reset = current; /* popmatrix after RENDER_TEXT */ + reset.m_state = current.m_state & ~RENDER_TEXT; + OpenGLState_apply( reset, current, globalstate ); + } + void realise(){ + if ( --m_unrealised == 0 ) { + if ( lightingSupported() && lightingEnabled() ) { + if ( useShaderLanguage() ) { + g_bumpGLSL.create(); + g_depthFillGLSL.create(); + } + else + { + g_bumpARB.create(); + g_depthFillARB.create(); + } } - else + + for ( Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) { - g_bumpARB.destroy(); - g_depthFillARB.destroy(); + if ( !( *i ).value.empty() ) { + ( *i ).value->realise( i->key ); + } } } } -} -bool realised(){ - return m_unrealised == 0; -} - - -bool lightingEnabled() const { - return m_lightingEnabled; -} -bool lightingSupported() const { - return m_lightingSupported; -} -bool useShaderLanguage() const { - return m_useShaderLanguage; -} -void setLighting( bool supported, bool enabled ){ - bool refresh = ( m_lightingSupported && m_lightingEnabled ) != ( supported && enabled ); - - if ( refresh ) { - unrealise(); - GlobalShaderSystem().setLightingEnabled( supported && enabled ); - } - - m_lightingSupported = supported; - m_lightingEnabled = enabled; - - if ( refresh ) { - realise(); - } -} -void extensionsInitialised(){ - setLighting( GlobalOpenGL().GL_1_3() - && GlobalOpenGL().ARB_vertex_program() - && GlobalOpenGL().ARB_fragment_program() - && GlobalOpenGL().ARB_shader_objects() - && GlobalOpenGL().ARB_vertex_shader() - && GlobalOpenGL().ARB_fragment_shader() - && GlobalOpenGL().ARB_shading_language_100(), - m_lightingEnabled - ); - - if ( !lightingSupported() ) { - globalWarningStream() << "Lighting mode requires OpenGL features not supported by your graphics drivers:\n"; - if ( !GlobalOpenGL().GL_1_3() ) { - globalOutputStream() << " GL version 1.3 or better\n"; - } - if ( !GlobalOpenGL().ARB_vertex_program() ) { - globalOutputStream() << " GL_ARB_vertex_program\n"; - } - if ( !GlobalOpenGL().ARB_fragment_program() ) { - globalOutputStream() << " GL_ARB_fragment_program\n"; - } - if ( !GlobalOpenGL().ARB_shader_objects() ) { - globalOutputStream() << " GL_ARB_shader_objects\n"; - } - if ( !GlobalOpenGL().ARB_vertex_shader() ) { - globalOutputStream() << " GL_ARB_vertex_shader\n"; - } - if ( !GlobalOpenGL().ARB_fragment_shader() ) { - globalOutputStream() << " GL_ARB_fragment_shader\n"; - } - if ( !GlobalOpenGL().ARB_shading_language_100() ) { - globalOutputStream() << " GL_ARB_shading_language_100\n"; + void unrealise(){ + if ( ++m_unrealised == 1 ) { + for ( Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i ) + { + if ( !( *i ).value.empty() ) { + ( *i ).value->unrealise(); + } + } + if ( GlobalOpenGL().contextValid && lightingSupported() && lightingEnabled() ) { + if ( useShaderLanguage() ) { + g_bumpGLSL.destroy(); + g_depthFillGLSL.destroy(); + } + else + { + g_bumpARB.destroy(); + g_depthFillARB.destroy(); + } + } } } -} -void setLightingEnabled( bool enabled ){ - setLighting( m_lightingSupported, enabled ); -} + bool realised(){ + return m_unrealised == 0; + } + + + bool lightingEnabled() const { + return m_lightingEnabled; + } + bool lightingSupported() const { + return m_lightingSupported; + } + bool useShaderLanguage() const { + return m_useShaderLanguage; + } + void setLighting( bool supported, bool enabled ){ + bool refresh = ( m_lightingSupported && m_lightingEnabled ) != ( supported && enabled ); + + if ( refresh ) { + unrealise(); + GlobalShaderSystem().setLightingEnabled( supported && enabled ); + } + + m_lightingSupported = supported; + m_lightingEnabled = enabled; + + if ( refresh ) { + realise(); + } + } + void extensionsInitialised(){ + setLighting( GlobalOpenGL().GL_1_3() + && GlobalOpenGL().ARB_vertex_program() + && GlobalOpenGL().ARB_fragment_program() + && GlobalOpenGL().ARB_shader_objects() + && GlobalOpenGL().ARB_vertex_shader() + && GlobalOpenGL().ARB_fragment_shader() + && GlobalOpenGL().ARB_shading_language_100(), + m_lightingEnabled + ); + + if ( !lightingSupported() ) { + globalWarningStream() << "Lighting mode requires OpenGL features not supported by your graphics drivers:\n"; + if ( !GlobalOpenGL().GL_1_3() ) { + globalOutputStream() << " GL version 1.3 or better\n"; + } + if ( !GlobalOpenGL().ARB_vertex_program() ) { + globalOutputStream() << " GL_ARB_vertex_program\n"; + } + if ( !GlobalOpenGL().ARB_fragment_program() ) { + globalOutputStream() << " GL_ARB_fragment_program\n"; + } + if ( !GlobalOpenGL().ARB_shader_objects() ) { + globalOutputStream() << " GL_ARB_shader_objects\n"; + } + if ( !GlobalOpenGL().ARB_vertex_shader() ) { + globalOutputStream() << " GL_ARB_vertex_shader\n"; + } + if ( !GlobalOpenGL().ARB_fragment_shader() ) { + globalOutputStream() << " GL_ARB_fragment_shader\n"; + } + if ( !GlobalOpenGL().ARB_shading_language_100() ) { + globalOutputStream() << " GL_ARB_shading_language_100\n"; + } + } + } + void setLightingEnabled( bool enabled ){ + setLighting( m_lightingSupported, enabled ); + } // light culling -RendererLights m_lights; -bool m_lightsChanged; -typedef std::map LightLists; -LightLists m_lightLists; + RendererLights m_lights; + bool m_lightsChanged; + typedef std::map LightLists; + LightLists m_lightLists; -const LightList& attach( LightCullable& cullable ){ - return ( *m_lightLists.insert( LightLists::value_type( &cullable, LinearLightList( cullable, m_lights, EvaluateChangedCaller( *this ) ) ) ).first ).second; -} -void detach( LightCullable& cullable ){ - m_lightLists.erase( &cullable ); -} -void changed( LightCullable& cullable ){ - LightLists::iterator i = m_lightLists.find( &cullable ); - ASSERT_MESSAGE( i != m_lightLists.end(), "cullable not attached" ); - ( *i ).second.lightsChanged(); -} -void attach( RendererLight& light ){ - const bool inserted = m_lights.insert( &light ).second; - ASSERT_MESSAGE( inserted, "light could not be attached" ); - changed( light ); -} -void detach( RendererLight& light ){ - const bool erased = m_lights.erase( &light ); - ASSERT_MESSAGE( erased, "light could not be detached" ); - changed( light ); -} -void changed( RendererLight& light ){ - m_lightsChanged = true; -} -void evaluateChanged(){ - if ( m_lightsChanged ) { - m_lightsChanged = false; - for ( LightLists::iterator i = m_lightLists.begin(); i != m_lightLists.end(); ++i ) - { - ( *i ).second.lightsChanged(); + const LightList& attach( LightCullable& cullable ){ + return ( *m_lightLists.insert( LightLists::value_type( &cullable, LinearLightList( cullable, m_lights, EvaluateChangedCaller( *this ) ) ) ).first ).second; + } + void detach( LightCullable& cullable ){ + m_lightLists.erase( &cullable ); + } + void changed( LightCullable& cullable ){ + LightLists::iterator i = m_lightLists.find( &cullable ); + ASSERT_MESSAGE( i != m_lightLists.end(), "cullable not attached" ); + ( *i ).second.lightsChanged(); + } + void attach( RendererLight& light ){ + const bool inserted = m_lights.insert( &light ).second; + ASSERT_MESSAGE( inserted, "light could not be attached" ); + changed( light ); + } + void detach( RendererLight& light ){ + const bool erased = m_lights.erase( &light ); + ASSERT_MESSAGE( erased, "light could not be detached" ); + changed( light ); + } + void changed( RendererLight& light ){ + m_lightsChanged = true; + } + void evaluateChanged(){ + if ( m_lightsChanged ) { + m_lightsChanged = false; + for ( LightLists::iterator i = m_lightLists.begin(); i != m_lightLists.end(); ++i ) + { + ( *i ).second.lightsChanged(); + } } } -} -typedef MemberCaller EvaluateChangedCaller; + typedef MemberCaller EvaluateChangedCaller; -typedef std::set Renderables; -Renderables m_renderables; -mutable bool m_traverseRenderablesMutex; + typedef std::set Renderables; + Renderables m_renderables; + mutable bool m_traverseRenderablesMutex; // renderables -void attachRenderable( const Renderable& renderable ){ - ASSERT_MESSAGE( !m_traverseRenderablesMutex, "attaching renderable during traversal" ); - const bool inserted = m_renderables.insert( &renderable ).second; - ASSERT_MESSAGE( inserted, "renderable could not be attached" ); -} -void detachRenderable( const Renderable& renderable ){ - ASSERT_MESSAGE( !m_traverseRenderablesMutex, "detaching renderable during traversal" ); - const bool erased = m_renderables.erase( &renderable ); - ASSERT_MESSAGE( erased, "renderable could not be detached" ); -} -void forEachRenderable( const RenderableCallback& callback ) const { - ASSERT_MESSAGE( !m_traverseRenderablesMutex, "for-each during traversal" ); - m_traverseRenderablesMutex = true; - for ( Renderables::const_iterator i = m_renderables.begin(); i != m_renderables.end(); ++i ) - { - callback( *( *i ) ); + void attachRenderable( const Renderable& renderable ){ + ASSERT_MESSAGE( !m_traverseRenderablesMutex, "attaching renderable during traversal" ); + const bool inserted = m_renderables.insert( &renderable ).second; + ASSERT_MESSAGE( inserted, "renderable could not be attached" ); + } + void detachRenderable( const Renderable& renderable ){ + ASSERT_MESSAGE( !m_traverseRenderablesMutex, "detaching renderable during traversal" ); + const bool erased = m_renderables.erase( &renderable ); + ASSERT_MESSAGE( erased, "renderable could not be detached" ); + } + void forEachRenderable( const RenderableCallback& callback ) const { + ASSERT_MESSAGE( !m_traverseRenderablesMutex, "for-each during traversal" ); + m_traverseRenderablesMutex = true; + for ( Renderables::const_iterator i = m_renderables.begin(); i != m_renderables.end(); ++i ) + { + callback( *( *i ) ); + } + m_traverseRenderablesMutex = false; } - m_traverseRenderablesMutex = false; -} }; static OpenGLShaderCache* g_ShaderCache; @@ -1622,7 +1622,7 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned glLoadIdentity(); GLint viewprt[4]; glGetIntegerv( GL_VIEWPORT, viewprt ); - //globalOutputStream() << viewprt[2] << " " << viewprt[3] << "\n"; + //globalOutputStream() << viewprt[2] << " " << viewprt[3] << "\n"; glOrtho( 0, viewprt[2], 0, viewprt[3], -100, 100 ); glTranslated( double( viewprt[2] ) / 2.0, double( viewprt[3] ) / 2.0, 0 ); glMatrixMode( GL_MODELVIEW ); @@ -1832,8 +1832,8 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned } if ( state & RENDER_LINESTIPPLE - && ( self.m_linestipple_factor != current.m_linestipple_factor - || self.m_linestipple_pattern != current.m_linestipple_pattern ) ) { + && ( self.m_linestipple_factor != current.m_linestipple_factor + || self.m_linestipple_pattern != current.m_linestipple_pattern ) ) { glLineStipple( self.m_linestipple_factor, self.m_linestipple_pattern ); GlobalOpenGL_debugAssertNoErrors(); current.m_linestipple_factor = self.m_linestipple_factor; @@ -1842,8 +1842,8 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned if ( state & RENDER_ALPHATEST - && ( self.m_alphafunc != current.m_alphafunc - || self.m_alpharef != current.m_alpharef ) ) { + && ( self.m_alphafunc != current.m_alphafunc + || self.m_alpharef != current.m_alpharef ) ) { glAlphaFunc( self.m_alphafunc, self.m_alpharef ); GlobalOpenGL_debugAssertNoErrors(); current.m_alphafunc = self.m_alphafunc; @@ -1895,10 +1895,7 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned } if ( !( state & RENDER_TEXTURE ) - && ( self.m_colour[0] != current.m_colour[0] - || self.m_colour[1] != current.m_colour[1] - || self.m_colour[2] != current.m_colour[2] - || self.m_colour[3] != current.m_colour[3] ) ) { + && self.m_colour != current.m_colour ) { glColor4fv( vector4_to_array( self.m_colour ) ); debug_colour( "setting non-texture" ); GlobalOpenGL_debugAssertNoErrors(); @@ -1906,7 +1903,7 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned current.m_colour = self.m_colour; if ( state & RENDER_BLEND - && ( self.m_blend_src != current.m_blend_src || self.m_blend_dst != current.m_blend_dst ) ) { + && ( self.m_blend_src != current.m_blend_src || self.m_blend_dst != current.m_blend_dst ) ) { glBlendFunc( self.m_blend_src, self.m_blend_dst ); GlobalOpenGL_debugAssertNoErrors(); current.m_blend_src = self.m_blend_src; @@ -1914,14 +1911,14 @@ void OpenGLState_apply( const OpenGLState& self, OpenGLState& current, unsigned } if ( !( state & RENDER_FILL ) - && self.m_linewidth != current.m_linewidth ) { + && self.m_linewidth != current.m_linewidth ) { glLineWidth( self.m_linewidth ); GlobalOpenGL_debugAssertNoErrors(); current.m_linewidth = self.m_linewidth; } if ( !( state & RENDER_FILL ) - && self.m_pointsize != current.m_pointsize ) { + && self.m_pointsize != current.m_pointsize ) { glPointSize( self.m_pointsize ); GlobalOpenGL_debugAssertNoErrors(); current.m_pointsize = self.m_pointsize; @@ -1954,8 +1951,8 @@ void Renderables_flush( OpenGLStateBucket::Renderables& renderables, OpenGLState if ( lightShader.firstLayer() != 0 ) { GLuint attenuation_xy = lightShader.firstLayer()->texture()->texture_number; GLuint attenuation_z = lightShader.lightFalloffImage() != 0 - ? lightShader.lightFalloffImage()->texture_number - : static_cast( g_defaultPointLight )->getShader().lightFalloffImage()->texture_number; + ? lightShader.lightFalloffImage()->texture_number + : static_cast( g_defaultPointLight )->getShader().lightFalloffImage()->texture_number; setTextureState( current.m_texture3, attenuation_xy, GL_TEXTURE3 ); glActiveTexture( GL_TEXTURE3 ); @@ -2033,37 +2030,37 @@ void OpenGLStateBucket::render( OpenGLState& current, unsigned int globalstate, class OpenGLStateMap : public OpenGLStateLibrary { -typedef std::map States; -States m_states; + typedef std::map States; + States m_states; public: -~OpenGLStateMap(){ - ASSERT_MESSAGE( m_states.empty(), "OpenGLStateMap::~OpenGLStateMap: not empty" ); -} + ~OpenGLStateMap(){ + ASSERT_MESSAGE( m_states.empty(), "OpenGLStateMap::~OpenGLStateMap: not empty" ); + } -typedef States::iterator iterator; -iterator begin(){ - return m_states.begin(); -} -iterator end(){ - return m_states.end(); -} + typedef States::iterator iterator; + iterator begin(){ + return m_states.begin(); + } + iterator end(){ + return m_states.end(); + } -void getDefaultState( OpenGLState& state ) const { - OpenGLState_constructDefault( state ); -} + void getDefaultState( OpenGLState& state ) const { + OpenGLState_constructDefault( state ); + } -void insert( const char* name, const OpenGLState& state ){ - bool inserted = m_states.insert( States::value_type( name, state ) ).second; - ASSERT_MESSAGE( inserted, "OpenGLStateMap::insert: " << name << " already exists" ); -} -void erase( const char* name ){ - std::size_t count = m_states.erase( name ); - ASSERT_MESSAGE( count == 1, "OpenGLStateMap::erase: " << name << " does not exist" ); -} + void insert( const char* name, const OpenGLState& state ){ + bool inserted = m_states.insert( States::value_type( name, state ) ).second; + ASSERT_MESSAGE( inserted, "OpenGLStateMap::insert: " << name << " already exists" ); + } + void erase( const char* name ){ + std::size_t count = m_states.erase( name ); + ASSERT_MESSAGE( count == 1, "OpenGLStateMap::erase: " << name << " does not exist" ); + } -iterator find( const char* name ){ - return m_states.find( name ); -} + iterator find( const char* name ){ + return m_states.find( name ); + } }; OpenGLStateMap* g_openglStates = 0; @@ -2140,13 +2137,13 @@ void OpenGLShader::construct( const char* name ){ break; case '$': - { - OpenGLStateMap::iterator i = g_openglStates->find( name ); - if ( i != g_openglStates->end() ) { - state = ( *i ).second; - break; + { + OpenGLStateMap::iterator i = g_openglStates->find( name ); + if ( i != g_openglStates->end() ) { + state = ( *i ).second; + break; + } } - } if ( string_equal( name + 1, "TEXT" ) ) { state.m_state = RENDER_CULLFACE | RENDER_COLOURWRITE | RENDER_FILL | RENDER_TEXTURE | RENDER_BLEND | RENDER_TEXT; state.m_sort = OpenGLState::eSortText; @@ -2494,20 +2491,20 @@ void OpenGLShader::construct( const char* name ){ class OpenGLStateLibraryAPI { -OpenGLStateMap m_stateMap; + OpenGLStateMap m_stateMap; public: -typedef OpenGLStateLibrary Type; -STRING_CONSTANT( Name, "*" ); + typedef OpenGLStateLibrary Type; + STRING_CONSTANT( Name, "*" ); -OpenGLStateLibraryAPI(){ - g_openglStates = &m_stateMap; -} -~OpenGLStateLibraryAPI(){ - g_openglStates = 0; -} -OpenGLStateLibrary* getTable(){ - return &m_stateMap; -} + OpenGLStateLibraryAPI(){ + g_openglStates = &m_stateMap; + } + ~OpenGLStateLibraryAPI(){ + g_openglStates = 0; + } + OpenGLStateLibrary* getTable(){ + return &m_stateMap; + } }; typedef SingletonModule OpenGLStateLibraryModule; @@ -2517,29 +2514,29 @@ StaticRegisterModule staticRegisterOpenGLStateLibrary( StaticOpenGLStateLibraryM class ShaderCacheDependencies : public GlobalShadersModuleRef, public GlobalTexturesModuleRef, public GlobalOpenGLStateLibraryModuleRef { public: -ShaderCacheDependencies() : - GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ){ -} + ShaderCacheDependencies() : + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ){ + } }; class ShaderCacheAPI { -ShaderCache* m_shaderCache; + ShaderCache* m_shaderCache; public: -typedef ShaderCache Type; -STRING_CONSTANT( Name, "*" ); + typedef ShaderCache Type; + STRING_CONSTANT( Name, "*" ); -ShaderCacheAPI(){ - ShaderCache_Construct(); + ShaderCacheAPI(){ + ShaderCache_Construct(); - m_shaderCache = GetShaderCache(); -} -~ShaderCacheAPI(){ - ShaderCache_Destroy(); -} -ShaderCache* getTable(){ - return m_shaderCache; -} + m_shaderCache = GetShaderCache(); + } + ~ShaderCacheAPI(){ + ShaderCache_Destroy(); + } + ShaderCache* getTable(){ + return m_shaderCache; + } }; typedef SingletonModule ShaderCacheModule; diff --git a/radiant/scenegraph.cpp b/radiant/scenegraph.cpp index 5ff09e30..6b03bea6 100644 --- a/radiant/scenegraph.cpp +++ b/radiant/scenegraph.cpp @@ -35,176 +35,176 @@ class StringEqualPredicate { -const char* m_string; + const char* m_string; public: -StringEqualPredicate( const char* string ) : m_string( string ){ -} -bool operator()( const char* other ) const { - return string_equal( m_string, other ); -} + StringEqualPredicate( const char* string ) : m_string( string ){ + } + bool operator()( const char* other ) const { + return string_equal( m_string, other ); + } }; template class TypeIdMap { -typedef const char* TypeName; -typedef TypeName TypeNames[SIZE]; -TypeNames m_typeNames; -TypeName* m_typeNamesEnd; + typedef const char* TypeName; + typedef TypeName TypeNames[SIZE]; + TypeNames m_typeNames; + TypeName* m_typeNamesEnd; public: -TypeIdMap() : m_typeNamesEnd( m_typeNames ){ -} -TypeId getTypeId( const char* name ){ - TypeName* i = std::find_if( m_typeNames, m_typeNamesEnd, StringEqualPredicate( name ) ); - if ( i == m_typeNamesEnd ) { - ASSERT_MESSAGE( m_typeNamesEnd != m_typeNames + SIZE, "reached maximum number of type names supported (" << Unsigned( SIZE ) << ")" ); - *m_typeNamesEnd++ = name; + TypeIdMap() : m_typeNamesEnd( m_typeNames ){ + } + TypeId getTypeId( const char* name ){ + TypeName* i = std::find_if( m_typeNames, m_typeNamesEnd, StringEqualPredicate( name ) ); + if ( i == m_typeNamesEnd ) { + ASSERT_MESSAGE( m_typeNamesEnd != m_typeNames + SIZE, "reached maximum number of type names supported (" << Unsigned( SIZE ) << ")" ); + *m_typeNamesEnd++ = name; + } + return i - m_typeNames; } - return i - m_typeNames; -} }; class CompiledGraph final : public scene::Graph, public scene::Instantiable::Observer { -typedef std::map InstanceMap; + typedef std::map InstanceMap; -InstanceMap m_instances; -scene::Instantiable::Observer* m_observer; -Signal0 m_boundsChanged; -scene::Path m_rootpath; -Signal0 m_sceneChangedCallbacks; + InstanceMap m_instances; + scene::Instantiable::Observer* m_observer; + Signal0 m_boundsChanged; + scene::Path m_rootpath; + Signal0 m_sceneChangedCallbacks; -TypeIdMap m_nodeTypeIds; -TypeIdMap m_instanceTypeIds; + TypeIdMap m_nodeTypeIds; + TypeIdMap m_instanceTypeIds; public: -CompiledGraph( scene::Instantiable::Observer* observer ) - : m_observer( observer ){ -} - -void addSceneChangedCallback( const SignalHandler& handler ){ - m_sceneChangedCallbacks.connectLast( handler ); -} -void sceneChanged(){ - m_sceneChangedCallbacks(); -} - -scene::Node& root(){ - ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); - return m_rootpath.top(); -} -void insert_root( scene::Node& root ){ - //globalOutputStream() << "insert_root\n"; - - ASSERT_MESSAGE( m_rootpath.empty(), "scenegraph root already exists" ); - - root.IncRef(); - - Node_traverseSubgraph( root, InstanceSubgraphWalker( this, scene::Path(), 0 ) ); - - m_rootpath.push( makeReference( root ) ); -} -void erase_root(){ - //globalOutputStream() << "erase_root\n"; - - ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); - - scene::Node& root = m_rootpath.top(); - - m_rootpath.pop(); - - Node_traverseSubgraph( root, UninstanceSubgraphWalker( this, scene::Path() ) ); - - root.DecRef(); -} -void boundsChanged(){ - m_boundsChanged(); -} - -void traverse( const Walker& walker ){ - traverse_subgraph( walker, m_instances.begin() ); -} - -void traverse_subgraph( const Walker& walker, const scene::Path& start ){ - if ( !m_instances.empty() ) { - traverse_subgraph( walker, m_instances.find( PathConstReference( start ) ) ); + CompiledGraph( scene::Instantiable::Observer* observer ) + : m_observer( observer ){ } -} -scene::Instance* find( const scene::Path& path ){ - InstanceMap::iterator i = m_instances.find( PathConstReference( path ) ); - if ( i == m_instances.end() ) { - return 0; + void addSceneChangedCallback( const SignalHandler& handler ){ + m_sceneChangedCallbacks.connectLast( handler ); + } + void sceneChanged(){ + m_sceneChangedCallbacks(); } - return ( *i ).second; -} -void insert( scene::Instance* instance ){ - m_instances.insert( InstanceMap::value_type( PathConstReference( instance->path() ), instance ) ); + scene::Node& root(){ + ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); + return m_rootpath.top(); + } + void insert_root( scene::Node& root ){ + //globalOutputStream() << "insert_root\n"; - m_observer->insert( instance ); -} -void erase( scene::Instance* instance ){ - m_observer->erase( instance ); + ASSERT_MESSAGE( m_rootpath.empty(), "scenegraph root already exists" ); - m_instances.erase( PathConstReference( instance->path() ) ); -} + root.IncRef(); -SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ){ - return m_boundsChanged.connectLast( boundsChanged ); -} -void removeBoundsChangedCallback( SignalHandlerId id ){ - m_boundsChanged.disconnect( id ); -} + Node_traverseSubgraph( root, InstanceSubgraphWalker( this, scene::Path(), 0 ) ); -TypeId getNodeTypeId( const char* name ){ - return m_nodeTypeIds.getTypeId( name ); -} + m_rootpath.push( makeReference( root ) ); + } + void erase_root(){ + //globalOutputStream() << "erase_root\n"; -TypeId getInstanceTypeId( const char* name ){ - return m_instanceTypeIds.getTypeId( name ); -} + ASSERT_MESSAGE( !m_rootpath.empty(), "scenegraph root does not exist" ); + + scene::Node& root = m_rootpath.top(); + + m_rootpath.pop(); + + Node_traverseSubgraph( root, UninstanceSubgraphWalker( this, scene::Path() ) ); + + root.DecRef(); + } + void boundsChanged(){ + m_boundsChanged(); + } + + void traverse( const Walker& walker ){ + traverse_subgraph( walker, m_instances.begin() ); + } + + void traverse_subgraph( const Walker& walker, const scene::Path& start ){ + if ( !m_instances.empty() ) { + traverse_subgraph( walker, m_instances.find( PathConstReference( start ) ) ); + } + } + + scene::Instance* find( const scene::Path& path ){ + InstanceMap::iterator i = m_instances.find( PathConstReference( path ) ); + if ( i == m_instances.end() ) { + return 0; + } + return ( *i ).second; + } + + void insert( scene::Instance* instance ){ + m_instances.insert( InstanceMap::value_type( PathConstReference( instance->path() ), instance ) ); + + m_observer->insert( instance ); + } + void erase( scene::Instance* instance ){ + m_observer->erase( instance ); + + m_instances.erase( PathConstReference( instance->path() ) ); + } + + SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ){ + return m_boundsChanged.connectLast( boundsChanged ); + } + void removeBoundsChangedCallback( SignalHandlerId id ){ + m_boundsChanged.disconnect( id ); + } + + TypeId getNodeTypeId( const char* name ){ + return m_nodeTypeIds.getTypeId( name ); + } + + TypeId getInstanceTypeId( const char* name ){ + return m_instanceTypeIds.getTypeId( name ); + } private: -bool pre( const Walker& walker, const InstanceMap::iterator& i ){ - return walker.pre( i->first, *i->second ); -} + bool pre( const Walker& walker, const InstanceMap::iterator& i ){ + return walker.pre( i->first, *i->second ); + } -void post( const Walker& walker, const InstanceMap::iterator& i ){ - walker.post( i->first, *i->second ); -} + void post( const Walker& walker, const InstanceMap::iterator& i ){ + walker.post( i->first, *i->second ); + } -void traverse_subgraph( const Walker& walker, InstanceMap::iterator i ){ - Stack stack; - if ( i != m_instances.end() ) { - const std::size_t startSize = ( *i ).first.get().size(); - do - { - if ( i != m_instances.end() - && stack.size() < ( ( *i ).first.get().size() - startSize + 1 ) ) { - stack.push( i ); - ++i; - if ( !pre( walker, stack.top() ) ) { - // skip subgraph - while ( i != m_instances.end() - && stack.size() < ( ( *i ).first.get().size() - startSize + 1 ) ) - { - ++i; + void traverse_subgraph( const Walker& walker, InstanceMap::iterator i ){ + Stack stack; + if ( i != m_instances.end() ) { + const std::size_t startSize = ( *i ).first.get().size(); + do + { + if ( i != m_instances.end() + && stack.size() < ( ( *i ).first.get().size() - startSize + 1 ) ) { + stack.push( i ); + ++i; + if ( !pre( walker, stack.top() ) ) { + // skip subgraph + while ( i != m_instances.end() + && stack.size() < ( ( *i ).first.get().size() - startSize + 1 ) ) + { + ++i; + } } } + else + { + post( walker, stack.top() ); + stack.pop(); + } } - else - { - post( walker, stack.top() ); - stack.pop(); - } + while ( !stack.empty() ); } - while ( !stack.empty() ); } -} }; namespace @@ -221,14 +221,14 @@ GraphTreeModel* scene_graph_get_tree_model(){ class SceneGraphObserver : public scene::Instantiable::Observer { public: -void insert( scene::Instance* instance ){ - g_sceneGraph->sceneChanged(); - graph_tree_model_insert( g_tree_model, *instance ); -} -void erase( scene::Instance* instance ){ - g_sceneGraph->sceneChanged(); - graph_tree_model_erase( g_tree_model, *instance ); -} + void insert( scene::Instance* instance ){ + g_sceneGraph->sceneChanged(); + graph_tree_model_insert( g_tree_model, *instance ); + } + void erase( scene::Instance* instance ){ + g_sceneGraph->sceneChanged(); + graph_tree_model_erase( g_tree_model, *instance ); + } }; SceneGraphObserver g_SceneGraphObserver; @@ -251,22 +251,22 @@ void SceneGraph_Destroy(){ class SceneGraphAPI { -scene::Graph* m_scenegraph; + scene::Graph* m_scenegraph; public: -typedef scene::Graph Type; -STRING_CONSTANT( Name, "*" ); + typedef scene::Graph Type; + STRING_CONSTANT( Name, "*" ); -SceneGraphAPI(){ - SceneGraph_Construct(); + SceneGraphAPI(){ + SceneGraph_Construct(); - m_scenegraph = g_sceneGraph; -} -~SceneGraphAPI(){ - SceneGraph_Destroy(); -} -scene::Graph* getTable(){ - return m_scenegraph; -} + m_scenegraph = g_sceneGraph; + } + ~SceneGraphAPI(){ + SceneGraph_Destroy(); + } + scene::Graph* getTable(){ + return m_scenegraph; + } }; typedef SingletonModule SceneGraphModule; diff --git a/radiant/select.cpp b/radiant/select.cpp index 93491278..aa15d1c6 100644 --- a/radiant/select.cpp +++ b/radiant/select.cpp @@ -59,34 +59,34 @@ select_workzone_t g_select_workzone; */ class CollectSelectedBrushesBounds : public SelectionSystem::Visitor { -AABB* m_bounds; // array of AABBs -Unsigned m_max; // max AABB-elements in array -Unsigned& m_count; // count of valid AABBs stored in array + AABB* m_bounds; // array of AABBs + Unsigned m_max; // max AABB-elements in array + Unsigned& m_count; // count of valid AABBs stored in array public: -CollectSelectedBrushesBounds( AABB* bounds, Unsigned max, Unsigned& count ) - : m_bounds( bounds ), - m_max( max ), - m_count( count ){ - m_count = 0; -} - -void visit( scene::Instance& instance ) const { - ASSERT_MESSAGE( m_count <= m_max, "Invalid m_count in CollectSelectedBrushesBounds" ); - - // stop if the array is already full - if ( m_count == m_max ) { - return; + CollectSelectedBrushesBounds( AABB* bounds, Unsigned max, Unsigned& count ) : + m_bounds( bounds ), + m_max( max ), + m_count( count ){ + m_count = 0; } - if ( Instance_isSelected( instance ) ) { - // brushes only - if ( Instance_getBrush( instance ) != 0 ) { - m_bounds[m_count] = instance.worldAABB(); - ++m_count; + void visit( scene::Instance& instance ) const { + ASSERT_MESSAGE( m_count <= m_max, "Invalid m_count in CollectSelectedBrushesBounds" ); + + // stop if the array is already full + if ( m_count == m_max ) { + return; + } + + if ( Instance_isSelected( instance ) ) { + // brushes only + if ( Instance_getBrush( instance ) != 0 ) { + m_bounds[m_count] = instance.worldAABB(); + ++m_count; + } } } -} }; /** @@ -96,82 +96,81 @@ void visit( scene::Instance& instance ) const { template class SelectByBounds : public scene::Graph::Walker { -AABB* m_aabbs; // selection aabbs -Unsigned m_count; // number of aabbs in m_aabbs -TSelectionPolicy policy; // type that contains a custom intersection method aabb<->aabb + AABB* m_aabbs; // selection aabbs + Unsigned m_count; // number of aabbs in m_aabbs + TSelectionPolicy policy; // type that contains a custom intersection method aabb<->aabb public: -SelectByBounds( AABB* aabbs, Unsigned count ) - : m_aabbs( aabbs ), - m_count( count ){ -} + SelectByBounds( AABB* aabbs, Unsigned count ) : + m_aabbs( aabbs ), + m_count( count ){ + } -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( path.top().get().visible() ){ - Selectable* selectable = Instance_getSelectable( instance ); + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( path.top().get().visible() ){ + Selectable* selectable = Instance_getSelectable( instance ); - // ignore worldspawn - Entity* entity = Node_getEntity( path.top() ); - if ( entity ) { - if ( string_equal( entity->getKeyValue( "classname" ), "worldspawn" ) ) { - return true; + // ignore worldspawn + Entity* entity = Node_getEntity( path.top() ); + if ( entity ) { + if ( string_equal( entity->getKeyValue( "classname" ), "worldspawn" ) ) { + return true; + } } - } - if ( ( path.size() > 1 ) && - ( !path.top().get().isRoot() ) && - ( selectable != 0 ) && - ( !node_is_group( path.top() ) ) - ) { - for ( Unsigned i = 0; i < m_count; ++i ) - { - if ( policy.Evaluate( m_aabbs[i], instance ) ) { - selectable->setSelected( true ); + if ( path.size() > 1 + && !path.top().get().isRoot() + && selectable != 0 + && !node_is_group( path.top() ) ) { + for ( Unsigned i = 0; i < m_count; ++i ) + { + if ( policy.Evaluate( m_aabbs[i], instance ) ) { + selectable->setSelected( true ); + } } } } - } - else{ - return false; + else{ + return false; + } + + return true; } - return true; -} + /** + Performs selection operation on the global scenegraph. + If delete_bounds_src is true, then the objects which were + used as source for the selection aabbs will be deleted. + */ + static void DoSelection( bool delete_bounds_src = true ){ + if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) { + // we may not need all AABBs since not all selected objects have to be brushes + const Unsigned max = (Unsigned)GlobalSelectionSystem().countSelected(); + AABB* aabbs = new AABB[max]; -/** - Performs selection operation on the global scenegraph. - If delete_bounds_src is true, then the objects which were - used as source for the selection aabbs will be deleted. - */ -static void DoSelection( bool delete_bounds_src = true ){ - if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) { - // we may not need all AABBs since not all selected objects have to be brushes - const Unsigned max = (Unsigned)GlobalSelectionSystem().countSelected(); - AABB* aabbs = new AABB[max]; + Unsigned count; + CollectSelectedBrushesBounds collector( aabbs, max, count ); + GlobalSelectionSystem().foreachSelected( collector ); - Unsigned count; - CollectSelectedBrushesBounds collector( aabbs, max, count ); - GlobalSelectionSystem().foreachSelected( collector ); + // nothing usable in selection + if ( !count ) { + delete[] aabbs; + return; + } - // nothing usable in selection - if ( !count ) { + // delete selected objects + if ( delete_bounds_src ) { // see deleteSelection + UndoableCommand undo( "deleteSelected" ); + Select_Delete(); + } + + // select objects with bounds + GlobalSceneGraph().traverse( SelectByBounds( aabbs, count ) ); + + SceneChangeNotify(); delete[] aabbs; - return; } - - // delete selected objects - if ( delete_bounds_src ) { // see deleteSelection - UndoableCommand undo( "deleteSelected" ); - Select_Delete(); - } - - // select objects with bounds - GlobalSceneGraph().traverse( SelectByBounds( aabbs, count ) ); - - SceneChangeNotify(); - delete[] aabbs; } -} }; /** @@ -181,16 +180,16 @@ static void DoSelection( bool delete_bounds_src = true ){ class SelectionPolicy_Touching { public: -bool Evaluate( const AABB& box, scene::Instance& instance ) const { - const AABB& other( instance.worldAABB() ); - for ( Unsigned i = 0; i < 3; ++i ) - { - if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] + other.extents[i] ) ) { - return false; + bool Evaluate( const AABB& box, scene::Instance& instance ) const { + const AABB& other( instance.worldAABB() ); + for ( Unsigned i = 0; i < 3; ++i ) + { + if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] + other.extents[i] ) ) { + return false; + } } + return true; } - return true; -} }; /** @@ -200,62 +199,62 @@ bool Evaluate( const AABB& box, scene::Instance& instance ) const { class SelectionPolicy_Inside { public: -bool Evaluate( const AABB& box, scene::Instance& instance ) const { - const AABB& other( instance.worldAABB() ); - for ( Unsigned i = 0; i < 3; ++i ) - { - if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] - other.extents[i] ) ) { - return false; + bool Evaluate( const AABB& box, scene::Instance& instance ) const { + const AABB& other( instance.worldAABB() ); + for ( Unsigned i = 0; i < 3; ++i ) + { + if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] - other.extents[i] ) ) { + return false; + } } + return true; } - return true; -} }; class DeleteSelected : public scene::Graph::Walker { -mutable bool m_remove; -mutable bool m_removedChild; + mutable bool m_remove; + mutable bool m_removedChild; public: -DeleteSelected() - : m_remove( false ), m_removedChild( false ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - m_removedChild = false; - - if ( Instance_isSelected( instance ) - && path.size() > 1 - && !path.top().get().isRoot() ) { - m_remove = true; - - return false; // dont traverse into child elements + DeleteSelected() + : m_remove( false ), m_removedChild( false ){ } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - - if ( m_removedChild ) { + bool pre( const scene::Path& path, scene::Instance& instance ) const { m_removedChild = false; - // delete empty entities - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 - && path.top().get_pointer() != Map_FindWorldspawn( g_map ) - && Node_getTraversable( path.top() )->empty() ) { + if ( Instance_isSelected( instance ) + && path.size() > 1 + && !path.top().get().isRoot() ) { + m_remove = true; + + return false; // dont traverse into child elements + } + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + + if ( m_removedChild ) { + m_removedChild = false; + + // delete empty entities + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && path.top().get_pointer() != Map_FindWorldspawn( g_map ) + && Node_getTraversable( path.top() )->empty() ) { + Path_deleteTop( path ); + } + } + + // node should be removed + if ( m_remove ) { + if ( Node_isEntity( path.parent() ) ) { + m_removedChild = true; + } + + m_remove = false; Path_deleteTop( path ); } } - - // node should be removed - if ( m_remove ) { - if ( Node_isEntity( path.parent() ) ) { - m_removedChild = true; - } - - m_remove = false; - Path_deleteTop( path ); - } -} }; void Scene_DeleteSelected( scene::Graph& graph ){ @@ -269,54 +268,54 @@ void Select_Delete( void ){ class InvertSelectionWalker : public scene::Graph::Walker { -SelectionSystem::EMode m_mode; -SelectionSystem::EComponentMode m_compmode; -mutable Selectable* m_selectable; + SelectionSystem::EMode m_mode; + SelectionSystem::EComponentMode m_compmode; + mutable Selectable* m_selectable; public: -InvertSelectionWalker( SelectionSystem::EMode mode, SelectionSystem::EComponentMode compmode ) - : m_mode( mode ), m_compmode( compmode ), m_selectable( 0 ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( !path.top().get().visible() ){ - m_selectable = 0; - return false; + InvertSelectionWalker( SelectionSystem::EMode mode, SelectionSystem::EComponentMode compmode ) + : m_mode( mode ), m_compmode( compmode ), m_selectable( 0 ){ } - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable ) { - switch ( m_mode ) - { - case SelectionSystem::eEntity: - if ( Node_isEntity( path.top() ) != 0 ) { - m_selectable = path.top().get().visible() ? selectable : 0; - } - break; - case SelectionSystem::ePrimitive: - m_selectable = path.top().get().visible() ? selectable : 0; - break; - case SelectionSystem::eComponent: - BrushInstance* brushinstance = Instance_getBrush( instance ); - if( brushinstance != 0 ){ - if( brushinstance->isSelected() ) - brushinstance->invertComponentSelection( m_compmode ); - } - else{ - PatchInstance* patchinstance = Instance_getPatch( instance ); - if( patchinstance != 0 && m_compmode == SelectionSystem::eVertex ){ - if( patchinstance->isSelected() ) - patchinstance->invertComponentSelection(); + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( !path.top().get().visible() ){ + m_selectable = 0; + return false; + } + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable ) { + switch ( m_mode ) + { + case SelectionSystem::eEntity: + if ( Node_isEntity( path.top() ) != 0 ) { + m_selectable = path.top().get().visible() ? selectable : 0; } + break; + case SelectionSystem::ePrimitive: + m_selectable = path.top().get().visible() ? selectable : 0; + break; + case SelectionSystem::eComponent: + BrushInstance* brushinstance = Instance_getBrush( instance ); + if( brushinstance != 0 ){ + if( brushinstance->isSelected() ) + brushinstance->invertComponentSelection( m_compmode ); + } + else{ + PatchInstance* patchinstance = Instance_getPatch( instance ); + if( patchinstance != 0 && m_compmode == SelectionSystem::eVertex ){ + if( patchinstance->isSelected() ) + patchinstance->invertComponentSelection(); + } + } + break; } - break; + } + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + if ( m_selectable != 0 ) { + m_selectable->setSelected( !m_selectable->isSelected() ); + m_selectable = 0; } } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - if ( m_selectable != 0 ) { - m_selectable->setSelected( !m_selectable->isSelected() ); - m_selectable = 0; - } -} }; void Scene_Invert_Selection( scene::Graph& graph ){ @@ -331,90 +330,90 @@ void Select_Invert(){ //interesting printings class ExpandSelectionToEntitiesWalker_dbg : public scene::Graph::Walker { -mutable std::size_t m_depth; -const scene::Node* m_world; + mutable std::size_t m_depth; + const scene::Node* m_world; public: -ExpandSelectionToEntitiesWalker_dbg() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - ++m_depth; - globalOutputStream() << "pre depth_" << m_depth; - globalOutputStream() << " path.size()_" << path.size(); - if ( path.top().get_pointer() == m_world ) - globalOutputStream() << " worldspawn"; - if( path.top().get().isRoot() ) - globalOutputStream() << " path.top().get().isRoot()"; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - globalOutputStream() << " entity!=0"; - if( entity->isContainer() ){ - globalOutputStream() << " entity->isContainer()"; - } - globalOutputStream() << " classname_" << entity->getKeyValue( "classname" ); + ExpandSelectionToEntitiesWalker_dbg() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ } - globalOutputStream() << "\n"; -// globalOutputStream() << "" << ; -// globalOutputStream() << "" << ; -// globalOutputStream() << "" << ; -// globalOutputStream() << "" << ; - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - globalOutputStream() << "post depth_" << m_depth; - globalOutputStream() << " path.size()_" << path.size(); - if ( path.top().get_pointer() == m_world ) - globalOutputStream() << " worldspawn"; - if( path.top().get().isRoot() ) - globalOutputStream() << " path.top().get().isRoot()"; - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - globalOutputStream() << " entity!=0"; - if( entity->isContainer() ){ - globalOutputStream() << " entity->isContainer()"; + bool pre( const scene::Path& path, scene::Instance& instance ) const { + ++m_depth; + globalOutputStream() << "pre depth_" << m_depth; + globalOutputStream() << " path.size()_" << path.size(); + if ( path.top().get_pointer() == m_world ) + globalOutputStream() << " worldspawn"; + if( path.top().get().isRoot() ) + globalOutputStream() << " path.top().get().isRoot()"; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + globalOutputStream() << " entity!=0"; + if( entity->isContainer() ){ + globalOutputStream() << " entity->isContainer()"; + } + globalOutputStream() << " classname_" << entity->getKeyValue( "classname" ); } - globalOutputStream() << " classname_" << entity->getKeyValue( "classname" ); + globalOutputStream() << "\n"; +// globalOutputStream() << "" << ; +// globalOutputStream() << "" << ; +// globalOutputStream() << "" << ; +// globalOutputStream() << "" << ; + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + globalOutputStream() << "post depth_" << m_depth; + globalOutputStream() << " path.size()_" << path.size(); + if ( path.top().get_pointer() == m_world ) + globalOutputStream() << " worldspawn"; + if( path.top().get().isRoot() ) + globalOutputStream() << " path.top().get().isRoot()"; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + globalOutputStream() << " entity!=0"; + if( entity->isContainer() ){ + globalOutputStream() << " entity->isContainer()"; + } + globalOutputStream() << " classname_" << entity->getKeyValue( "classname" ); + } + globalOutputStream() << "\n"; + --m_depth; } - globalOutputStream() << "\n"; - --m_depth; -} }; #endif class ExpandSelectionToPrimitivesWalker : public scene::Graph::Walker { -mutable std::size_t m_depth; -const scene::Node* m_world; + mutable std::size_t m_depth; + const scene::Node* m_world; public: -ExpandSelectionToPrimitivesWalker() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - ++m_depth; + ExpandSelectionToPrimitivesWalker() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + ++m_depth; - if( !path.top().get().visible() ) - return false; + if( !path.top().get().visible() ) + return false; -// if ( path.top().get_pointer() == m_world ) // ignore worldspawn -// return false; +// if ( path.top().get_pointer() == m_world ) // ignore worldspawn +// return false; - if ( m_depth == 2 ) { // entity depth - // traverse and select children if any one is selected - bool beselected = false; - const bool isContainer = Node_getEntity( path.top() )->isContainer(); - if ( instance.childSelected() || instance.isSelected() ) { - beselected = true; - Instance_setSelected( instance, !isContainer ); + if ( m_depth == 2 ) { // entity depth + // traverse and select children if any one is selected + bool beselected = false; + const bool isContainer = Node_getEntity( path.top() )->isContainer(); + if ( instance.childSelected() || instance.isSelected() ) { + beselected = true; + Instance_setSelected( instance, !isContainer ); + } + return isContainer && beselected; } - return isContainer && beselected; + else if ( m_depth == 3 ) { // primitive depth + Instance_setSelected( instance, true ); + return false; + } + return true; } - else if ( m_depth == 3 ) { // primitive depth - Instance_setSelected( instance, true ); - return false; + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} }; void Scene_ExpandSelectionToPrimitives(){ @@ -423,40 +422,40 @@ void Scene_ExpandSelectionToPrimitives(){ class ExpandSelectionToEntitiesWalker : public scene::Graph::Walker { -mutable std::size_t m_depth; -const scene::Node* m_world; + mutable std::size_t m_depth; + const scene::Node* m_world; public: -ExpandSelectionToEntitiesWalker() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - ++m_depth; + ExpandSelectionToEntitiesWalker() : m_depth( 0 ), m_world( Map_FindWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + ++m_depth; - if( !path.top().get().visible() ) - return false; + if( !path.top().get().visible() ) + return false; -// if ( path.top().get_pointer() == m_world ) // ignore worldspawn -// return false; +// if ( path.top().get_pointer() == m_world ) // ignore worldspawn +// return false; - if ( m_depth == 2 ) { // entity depth - // traverse and select children if any one is selected - bool beselected = false; - if ( instance.childSelected() || instance.isSelected() ) { - beselected = true; - if( path.top().get_pointer() != m_world ){ //avoid selecting world node - Instance_setSelected( instance, true ); + if ( m_depth == 2 ) { // entity depth + // traverse and select children if any one is selected + bool beselected = false; + if ( instance.childSelected() || instance.isSelected() ) { + beselected = true; + if( path.top().get_pointer() != m_world ){ //avoid selecting world node + Instance_setSelected( instance, true ); + } } + return Node_getEntity( path.top() )->isContainer() && beselected; } - return Node_getEntity( path.top() )->isContainer() && beselected; + else if ( m_depth == 3 ) { // primitive depth + Instance_setSelected( instance, true ); + return false; + } + return true; } - else if ( m_depth == 3 ) { // primitive depth - Instance_setSelected( instance, true ); - return false; + void post( const scene::Path& path, scene::Instance& instance ) const { + --m_depth; } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} }; void Scene_ExpandSelectionToEntities(){ @@ -728,36 +727,36 @@ bool propertyvalues_contain( const PropertyValues& propertyvalues, const char *s template class EntityFindByPropertyValueWalker : public scene::Graph::Walker { -const EntityMatcher& m_entityMatcher; -const scene::Node* m_world; + const EntityMatcher& m_entityMatcher; + const scene::Node* m_world; public: -EntityFindByPropertyValueWalker( const EntityMatcher& entityMatcher ) - : m_entityMatcher( entityMatcher ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( !path.top().get().visible() ){ - return false; + EntityFindByPropertyValueWalker( const EntityMatcher& entityMatcher ) + : m_entityMatcher( entityMatcher ), m_world( Map_FindWorldspawn( g_map ) ){ } - // ignore worldspawn - if ( path.top().get_pointer() == m_world ) { - return false; - } - - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - if( m_entityMatcher( entity ) ) { - Instance_getSelectable( instance )->setSelected( true ); - return true; + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( !path.top().get().visible() ){ + return false; } - return false; + // ignore worldspawn + if ( path.top().get_pointer() == m_world ) { + return false; + } + + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + if( m_entityMatcher( entity ) ) { + Instance_getSelectable( instance )->setSelected( true ); + return true; + } + return false; + } + else if( path.size() > 2 && !path.top().get().isRoot() ){ + Selectable* selectable = Instance_getSelectable( instance ); + if( selectable != 0 ) + selectable->setSelected( true ); + } + return true; } - else if( path.size() > 2 && !path.top().get().isRoot() ){ - Selectable* selectable = Instance_getSelectable( instance ); - if( selectable != 0 ) - selectable->setSelected( true ); - } - return true; -} }; template @@ -773,27 +772,27 @@ void Scene_EntitySelectByPropertyValues( scene::Graph& graph, const char *prop, class EntityGetSelectedPropertyValuesWalker : public scene::Graph::Walker { -PropertyValues& m_propertyvalues; -const char *m_prop; -const scene::Node* m_world; + PropertyValues& m_propertyvalues; + const char *m_prop; + const scene::Node* m_world; public: -EntityGetSelectedPropertyValuesWalker( const char *prop, PropertyValues& propertyvalues ) - : m_propertyvalues( propertyvalues ), m_prop( prop ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - if( path.top().get_pointer() != m_world ){ - if ( Instance_isSelected( instance ) || instance.childSelected() ) { - if ( !propertyvalues_contain( m_propertyvalues, entity->getKeyValue( m_prop ) ) ) { - m_propertyvalues.push_back( entity->getKeyValue( m_prop ) ); + EntityGetSelectedPropertyValuesWalker( const char *prop, PropertyValues& propertyvalues ) + : m_propertyvalues( propertyvalues ), m_prop( prop ), m_world( Map_FindWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + if( path.top().get_pointer() != m_world ){ + if ( Instance_isSelected( instance ) || instance.childSelected() ) { + if ( !propertyvalues_contain( m_propertyvalues, entity->getKeyValue( m_prop ) ) ) { + m_propertyvalues.push_back( entity->getKeyValue( m_prop ) ); + } } } + return false; } - return false; + return true; } - return true; -} }; /* class EntityGetSelectedPropertyValuesWalker : public scene::Graph::Walker @@ -960,18 +959,18 @@ ToggleItem g_hidden_item( g_hidden_caller ); class HideSelectedWalker : public scene::Graph::Walker { -bool m_hide; + bool m_hide; public: -HideSelectedWalker( bool hide ) - : m_hide( hide ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - g_nodes_be_hidden = m_hide; - hide_node( path.top(), m_hide ); + HideSelectedWalker( bool hide ) + : m_hide( hide ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + g_nodes_be_hidden = m_hide; + hide_node( path.top(), m_hide ); + } + return true; } - return true; -} }; void Scene_Hide_Selected( bool hide ){ @@ -994,15 +993,15 @@ void HideSelected(){ class HideAllWalker : public scene::Graph::Walker { -bool m_hide; + bool m_hide; public: -HideAllWalker( bool hide ) - : m_hide( hide ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - hide_node( path.top(), m_hide ); - return true; -} + HideAllWalker( bool hide ) + : m_hide( hide ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + hide_node( path.top(), m_hide ); + return true; + } }; void Scene_Hide_All( bool hide ){ @@ -1186,12 +1185,12 @@ inline Quaternion quaternion_for_euler_xyz_degrees( const Vector3& eulerXYZ ){ return quaternion_for_matrix4_rotation( matrix4_rotation_for_euler_xyz_degrees( eulerXYZ ) ); #elif 0 return quaternion_multiplied_by_quaternion( - quaternion_multiplied_by_quaternion( - quaternion_for_z( degrees_to_radians( eulerXYZ[2] ) ), - quaternion_for_y( degrees_to_radians( eulerXYZ[1] ) ) - ), - quaternion_for_x( degrees_to_radians( eulerXYZ[0] ) ) - ); + quaternion_multiplied_by_quaternion( + quaternion_for_z( degrees_to_radians( eulerXYZ[2] ) ), + quaternion_for_y( degrees_to_radians( eulerXYZ[1] ) ) + ), + quaternion_for_x( degrees_to_radians( eulerXYZ[0] ) ) + ); #elif 1 double cx = cos( degrees_to_radians( eulerXYZ[0] * 0.5 ) ); double sx = sin( degrees_to_radians( eulerXYZ[0] * 0.5 ) ); @@ -1201,11 +1200,11 @@ inline Quaternion quaternion_for_euler_xyz_degrees( const Vector3& eulerXYZ ){ double sz = sin( degrees_to_radians( eulerXYZ[2] * 0.5 ) ); return Quaternion( - cz * cy * sx - sz * sy * cx, - cz * sy * cx + sz * cy * sx, - sz * cy * cx - cz * sy * sx, - cz * cy * cx + sz * sy * sx - ); + cz * cy * sx - sz * sy * cx, + cz * sy * cx + sz * cy * sx, + sz * cy * cx - cz * sy * sx, + cz * cy * cx + sz * sy * sx + ); #endif } @@ -1280,30 +1279,30 @@ void DoRotateDlg(){ GtkWidget* label = gtk_label_new( " X " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 0, 1, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( " Y " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 1, 2, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( " Z " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 2, 3, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkAdjustment* adj = GTK_ADJUSTMENT( gtk_adjustment_new( 0, -359, 359, 1, 10, 0 ) ); GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 2 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 ); gtk_spin_button_set_wrap( spin, TRUE ); @@ -1316,8 +1315,8 @@ void DoRotateDlg(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 2 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 ); gtk_spin_button_set_wrap( spin, TRUE ); @@ -1328,8 +1327,8 @@ void DoRotateDlg(){ GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( adj, 1, 2 ) ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 ); gtk_spin_button_set_wrap( spin, TRUE ); @@ -1434,30 +1433,30 @@ void DoScaleDlg(){ GtkWidget* label = gtk_label_new( " X " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 0, 1, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( " Y " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 1, 2, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( " Z " ); gtk_widget_show( label ); gtk_table_attach( table, label, 0, 1, 2, 3, - (GtkAttachOptions) ( 0 ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* entry = gtk_entry_new(); gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" ); gtk_widget_show( entry ); gtk_table_attach( table, entry, 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_scale_dialog.x = entry; } @@ -1466,8 +1465,8 @@ void DoScaleDlg(){ gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" ); gtk_widget_show( entry ); gtk_table_attach( table, entry, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_scale_dialog.y = entry; } @@ -1476,8 +1475,8 @@ void DoScaleDlg(){ gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" ); gtk_widget_show( entry ); gtk_table_attach( table, entry, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_scale_dialog.z = entry; } @@ -1510,28 +1509,28 @@ void DoScaleDlg(){ class EntityGetSelectedPropertyValuesWalker_nonEmpty : public scene::Graph::Walker { -PropertyValues& m_propertyvalues; -const char *m_prop; -const scene::Node* m_world; + PropertyValues& m_propertyvalues; + const char *m_prop; + const scene::Node* m_world; public: -EntityGetSelectedPropertyValuesWalker_nonEmpty( const char *prop, PropertyValues& propertyvalues ) - : m_propertyvalues( propertyvalues ), m_prop( prop ), m_world( Map_FindWorldspawn( g_map ) ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Entity* entity = Node_getEntity( path.top() ); - if ( entity != 0 ){ - if( path.top().get_pointer() != m_world ){ - if ( Instance_isSelected( instance ) || instance.childSelected() ) { - const char* keyvalue = entity->getKeyValue( m_prop ); - if ( !string_empty( keyvalue ) && !propertyvalues_contain( m_propertyvalues, keyvalue ) ) { - m_propertyvalues.push_back( keyvalue ); + EntityGetSelectedPropertyValuesWalker_nonEmpty( const char *prop, PropertyValues& propertyvalues ) + : m_propertyvalues( propertyvalues ), m_prop( prop ), m_world( Map_FindWorldspawn( g_map ) ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ){ + if( path.top().get_pointer() != m_world ){ + if ( Instance_isSelected( instance ) || instance.childSelected() ) { + const char* keyvalue = entity->getKeyValue( m_prop ); + if ( !string_empty( keyvalue ) && !propertyvalues_contain( m_propertyvalues, keyvalue ) ) { + m_propertyvalues.push_back( keyvalue ); + } } } + return false; } - return false; + return true; } - return true; -} }; void Scene_EntityGetPropertyValues_nonEmpty( scene::Graph& graph, const char *prop, PropertyValues& propertyvalues ){ diff --git a/radiant/selection.cpp b/radiant/selection.cpp index ecb19e5c..3d3e91f9 100644 --- a/radiant/selection.cpp +++ b/radiant/selection.cpp @@ -76,9 +76,9 @@ inline Vector3 point_for_device_point( const Matrix4& device2object, const float inline Ray ray_for_device_point( const Matrix4& device2object, const float x, const float y ){ return ray_for_points( point_for_device_point( device2object, x, y, -1 ), // point at x, y, zNear - point_for_device_point( device2object, x, y, 0 ) // point at x, y, zFar - //point_for_device_point( device2object, x, y, 1 ) //sometimes is inaccurate up to negative ray direction - ); + point_for_device_point( device2object, x, y, 0 ) // point at x, y, zFar + //point_for_device_point( device2object, x, y, 1 ) //sometimes is inaccurate up to negative ray direction + ); } inline Vector3 sphere_intersect_ray( const Vector3& origin, float radius, const Ray& ray ){ @@ -121,13 +121,13 @@ const float g_radius = 64; inline Vector3 point_on_sphere( const Matrix4& device2object, const float x, const float y, const float radius = g_radius ){ return sphere_intersect_ray( g_origin, - radius, - ray_for_device_point( device2object, x, y ) ); + radius, + ray_for_device_point( device2object, x, y ) ); } inline Vector3 point_on_axis( const Vector3& axis, const Matrix4& device2object, const float x, const float y ){ return ray_intersect_ray( ray_for_device_point( device2object, x, y ), - Ray( Vector3( 0, 0, 0 ), axis ) ); + Ray( Vector3( 0, 0, 0 ), axis ) ); } inline Vector3 point_on_plane( const Matrix4& device2object, const float x, const float y ){ @@ -137,15 +137,15 @@ inline Vector3 point_on_plane( const Matrix4& device2object, const float x, cons inline Vector3 point_on_plane( const Plane3& plane, const Matrix4& object2device, const float x, const float y ){ return ray_intersect_plane( ray_for_device_point( matrix4_full_inverse( object2device ), x, y ), - plane ); + plane ); } //! a and b are unit vectors .. returns angle in radians inline float angle_between( const Vector3& a, const Vector3& b ){ return static_cast( 2.0 * atan2( - vector3_length( vector3_subtracted( a, b ) ), - vector3_length( vector3_added( a, b ) ) - ) ); + vector3_length( vector3_subtracted( a, b ) ), + vector3_length( vector3_added( a, b ) ) + ) ); } @@ -153,10 +153,10 @@ inline float angle_between( const Vector3& a, const Vector3& b ){ class test_quat { public: -test_quat( const Vector3& from, const Vector3& to ){ - Vector4 quaternion( quaternion_for_unit_vectors( from, to ) ); - Matrix4 matrix( matrix4_rotation_for_quaternion( quaternion_multiplied_by_quaternion( quaternion, c_quaternion_identity ) ) ); -} + test_quat( const Vector3& from, const Vector3& to ){ + Vector4 quaternion( quaternion_for_unit_vectors( from, to ) ); + Matrix4 matrix( matrix4_rotation_for_quaternion( quaternion_multiplied_by_quaternion( quaternion, c_quaternion_identity ) ) ); + } private: }; @@ -185,19 +185,19 @@ inline float distance_for_axis( const Vector3& a, const Vector3& b, const Vector class Manipulatable { public: -virtual void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ) = 0; -virtual void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ) = 0; -static const View* m_view; -static float m_device_point[2]; -static float m_device_epsilon[2]; -static void assign_static( const View& view, const float device_point[2], const float device_epsilon[2] ){ - m_view = &view; - m_device_point[0] = device_point[0]; - m_device_point[1] = device_point[1]; - m_device_epsilon[0] = device_epsilon[0]; - m_device_epsilon[1] = device_epsilon[1]; + virtual void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ) = 0; + virtual void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ) = 0; + static const View* m_view; + static float m_device_point[2]; + static float m_device_epsilon[2]; + static void assign_static( const View& view, const float device_point[2], const float device_epsilon[2] ){ + m_view = &view; + m_device_point[0] = device_point[0]; + m_device_point[1] = device_point[1]; + m_device_epsilon[0] = device_epsilon[0]; + m_device_epsilon[1] = device_epsilon[1]; -} + } }; const View* Manipulatable::m_view = 0; float Manipulatable::m_device_point[2]; @@ -205,103 +205,103 @@ float Manipulatable::m_device_epsilon[2]; inline Matrix4 transform_local2object( const Matrix4& local, const Matrix4& local2object ){ return matrix4_multiplied_by_matrix4( - matrix4_multiplied_by_matrix4( local2object, local ), - matrix4_full_inverse( local2object ) - ); + matrix4_multiplied_by_matrix4( local2object, local ), + matrix4_full_inverse( local2object ) + ); } inline Matrix4 transform_local2object( const Matrix4& localTransform, const Matrix4& local2parent, const Matrix4& parent2local ){ return matrix4_multiplied_by_matrix4( - matrix4_multiplied_by_matrix4( local2parent, localTransform ), - parent2local - ); + matrix4_multiplied_by_matrix4( local2parent, localTransform ), + parent2local + ); } class Rotatable { public: -virtual void rotate( const Quaternion& rotation ) = 0; + virtual void rotate( const Quaternion& rotation ) = 0; }; class RotateFree : public Manipulatable { -Vector3 m_start; -Rotatable& m_rotatable; + Vector3 m_start; + Rotatable& m_rotatable; public: -RotateFree( Rotatable& rotatable ) - : m_rotatable( rotatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_sphere( device2manip, x, y ); - vector3_normalise( m_start ); -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = point_on_sphere( device2manip, x, y ); - vector3_normalise( current ); + RotateFree( Rotatable& rotatable ) + : m_rotatable( rotatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_sphere( device2manip, x, y ); + vector3_normalise( m_start ); + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = point_on_sphere( device2manip, x, y ); + vector3_normalise( current ); - if( snap ) - for( std::size_t i = 0; i < 3; ++i ) - if( current[i] == 0.f ) - return m_rotatable.rotate( quaternion_for_axisangle( g_vector3_axes[i], float_snapped( angle_for_axis( m_start, current, g_vector3_axes[i] ), static_cast( c_pi / 12.0 ) ) ) ); + if( snap ) + for( std::size_t i = 0; i < 3; ++i ) + if( current[i] == 0.f ) + return m_rotatable.rotate( quaternion_for_axisangle( g_vector3_axes[i], float_snapped( angle_for_axis( m_start, current, g_vector3_axes[i] ), static_cast( c_pi / 12.0 ) ) ) ); - m_rotatable.rotate( quaternion_for_unit_vectors( m_start, current ) ); + m_rotatable.rotate( quaternion_for_unit_vectors( m_start, current ) ); // m_rotatable.rotate( quaternion_for_sphere_vectors( m_start, current ) ); //wrong math, 2x more sensitive -} + } }; class RotateAxis : public Manipulatable { -Vector3 m_axis; -Vector3 m_start; -float m_radius; -bool m_plane_way; -Plane3 m_plane; -Vector3 m_origin; -Rotatable& m_rotatable; + Vector3 m_axis; + Vector3 m_start; + float m_radius; + bool m_plane_way; + Plane3 m_plane; + Vector3 m_origin; + Rotatable& m_rotatable; public: -RotateAxis( Rotatable& rotatable ) - : m_radius( g_radius ), m_rotatable( rotatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - const float dot = vector3_dot( m_axis, m_view->fill()? vector3_normalised( m_view->getViewer() - transform_origin ) : m_view->getViewDir() ); - m_plane_way = fabs( dot ) > 0.1; + RotateAxis( Rotatable& rotatable ) + : m_radius( g_radius ), m_rotatable( rotatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + const float dot = vector3_dot( m_axis, m_view->fill()? vector3_normalised( m_view->getViewer() - transform_origin ) : m_view->getViewDir() ); + m_plane_way = fabs( dot ) > 0.1; - if( m_plane_way ){ - m_origin = transform_origin; - m_plane = Plane3( m_axis, vector3_dot( m_axis, m_origin ) ); - m_start = point_on_plane( m_plane, m_view->GetViewMatrix(), x, y ) - m_origin; - vector3_normalise( m_start ); + if( m_plane_way ){ + m_origin = transform_origin; + m_plane = Plane3( m_axis, vector3_dot( m_axis, m_origin ) ); + m_start = point_on_plane( m_plane, m_view->GetViewMatrix(), x, y ) - m_origin; + vector3_normalise( m_start ); + } + else{ + m_start = point_on_sphere( device2manip, x, y, m_radius ); + constrain_to_axis( m_start, m_axis ); + } } - else{ - m_start = point_on_sphere( device2manip, x, y, m_radius ); - constrain_to_axis( m_start, m_axis ); - } -} /// \brief Converts current position to a normalised vector orthogonal to axis. -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current; - if( m_plane_way ){ - current = point_on_plane( m_plane, m_view->GetViewMatrix(), x, y ) - m_origin; - vector3_normalise( current ); - } - else{ - current = point_on_sphere( device2manip, x, y, m_radius ); - constrain_to_axis( current, m_axis ); + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current; + if( m_plane_way ){ + current = point_on_plane( m_plane, m_view->GetViewMatrix(), x, y ) - m_origin; + vector3_normalise( current ); + } + else{ + current = point_on_sphere( device2manip, x, y, m_radius ); + constrain_to_axis( current, m_axis ); + } + + if( snap ){ + m_rotatable.rotate( quaternion_for_axisangle( m_axis, float_snapped( angle_for_axis( m_start, current, m_axis ), static_cast( c_pi / 12.0 ) ) ) ); + } + else{ + m_rotatable.rotate( quaternion_for_axisangle( m_axis, angle_for_axis( m_start, current, m_axis ) ) ); + } } - if( snap ){ - m_rotatable.rotate( quaternion_for_axisangle( m_axis, float_snapped( angle_for_axis( m_start, current, m_axis ), static_cast( c_pi / 12.0 ) ) ) ); + void SetAxis( const Vector3& axis ){ + m_axis = axis; } - else{ - m_rotatable.rotate( quaternion_for_axisangle( m_axis, angle_for_axis( m_start, current, m_axis ) ) ); + void SetRadius( const float radius ){ + m_radius = radius; } -} - -void SetAxis( const Vector3& axis ){ - m_axis = axis; -} -void SetRadius( const float radius ){ - m_radius = radius; -} }; @@ -312,8 +312,8 @@ void aabb_snap_translation( Vector3& move, const AABB& bounds ){ // globalOutputStream() << "move: " << move << "\n"; for( std::size_t i = 0; i < 3; ++i ){ if( fabs( move[i] ) > 1e-2f ){ - const float snapto1 = float_snapped( maxs[i] + move[i] , GetSnapGridSize() ); - const float snapto2 = float_snapped( mins[i] + move[i] , GetSnapGridSize() ); + const float snapto1 = float_snapped( maxs[i] + move[i], GetSnapGridSize() ); + const float snapto2 = float_snapped( mins[i] + move[i], GetSnapGridSize() ); const float dist1 = fabs( fabs( maxs[i] + move[i] ) - fabs( snapto1 ) ); const float dist2 = fabs( fabs( mins[i] + move[i] ) - fabs( snapto2 ) ); @@ -327,405 +327,405 @@ void aabb_snap_translation( Vector3& move, const AABB& bounds ){ inline Vector3 translation_local2object( const Vector3& local, const Matrix4& local2object ){ return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3( local2object, local ), - matrix4_full_inverse( local2object ) - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( local2object, local ), + matrix4_full_inverse( local2object ) + ) + ); } inline Vector3 translation_local2object( const Vector3& localTranslation, const Matrix4& local2parent, const Matrix4& parent2local ){ return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3( local2parent, localTranslation ), - parent2local - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( local2parent, localTranslation ), + parent2local + ) + ); } class Translatable { public: -virtual void translate( const Vector3& translation ) = 0; + virtual void translate( const Vector3& translation ) = 0; }; class TranslateAxis : public Manipulatable { -Vector3 m_start; -Vector3 m_axis; -Translatable& m_translatable; -AABB m_bounds; + Vector3 m_start; + Vector3 m_axis; + Translatable& m_translatable; + AABB m_bounds; public: -TranslateAxis( Translatable& translatable ) - : m_translatable( translatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_axis( m_axis, device2manip, x, y ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = point_on_axis( m_axis, device2manip, x, y ); - current = vector3_scaled( m_axis, distance_for_axis( m_start, current, m_axis ) ); + TranslateAxis( Translatable& translatable ) + : m_translatable( translatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_axis( m_axis, device2manip, x, y ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = point_on_axis( m_axis, device2manip, x, y ); + current = vector3_scaled( m_axis, distance_for_axis( m_start, current, m_axis ) ); - current = translation_local2object( current, manip2object ); - if( snapbbox ) - aabb_snap_translation( current, m_bounds ); - else - vector3_snap( current, GetSnapGridSize() ); + current = translation_local2object( current, manip2object ); + if( snapbbox ) + aabb_snap_translation( current, m_bounds ); + else + vector3_snap( current, GetSnapGridSize() ); - m_translatable.translate( current ); -} + m_translatable.translate( current ); + } -void SetAxis( const Vector3& axis ){ - m_axis = axis; -} + void SetAxis( const Vector3& axis ){ + m_axis = axis; + } }; class TranslateAxis2 : public Manipulatable { private: -Vector3 m_0; -Plane3 m_planeSelected; -std::size_t m_axisZ; -Plane3 m_planeZ; -Vector3 m_startZ; -Translatable& m_translatable; -AABB m_bounds; + Vector3 m_0; + Plane3 m_planeSelected; + std::size_t m_axisZ; + Plane3 m_planeZ; + Vector3 m_startZ; + Translatable& m_translatable; + AABB m_bounds; public: -TranslateAxis2( Translatable& translatable ) - : m_translatable( translatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_axisZ = vector3_max_abs_component_index( m_planeSelected.normal() ); - Vector3 xydir( m_view->getViewer() - m_0 ); - xydir[m_axisZ] = 0; - vector3_normalise( xydir ); - m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); - m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = g_vector3_axes[m_axisZ] * vector3_dot( m_planeSelected.normal(), ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) ) - * ( m_planeSelected.normal()[m_axisZ] >= 0? 1 : -1 ); + TranslateAxis2( Translatable& translatable ) + : m_translatable( translatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_axisZ = vector3_max_abs_component_index( m_planeSelected.normal() ); + Vector3 xydir( m_view->getViewer() - m_0 ); + xydir[m_axisZ] = 0; + vector3_normalise( xydir ); + m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); + m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = g_vector3_axes[m_axisZ] * vector3_dot( m_planeSelected.normal(), ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) ) + * ( m_planeSelected.normal()[m_axisZ] >= 0? 1 : -1 ); - if( !std::isfinite( current[0] ) || !std::isfinite( current[1] ) || !std::isfinite( current[2] ) ) // catch INF case, is likely with top of the box in 2D - return; + if( !std::isfinite( current[0] ) || !std::isfinite( current[1] ) || !std::isfinite( current[2] ) ) // catch INF case, is likely with top of the box in 2D + return; - if( snapbbox ) - aabb_snap_translation( current, m_bounds ); - else - vector3_snap( current, GetSnapGridSize() ); + if( snapbbox ) + aabb_snap_translation( current, m_bounds ); + else + vector3_snap( current, GetSnapGridSize() ); - m_translatable.translate( current ); -} -void set0( const Vector3& start, const Plane3& planeSelected ){ - m_0 = start; - m_planeSelected = planeSelected; -} + m_translatable.translate( current ); + } + void set0( const Vector3& start, const Plane3& planeSelected ){ + m_0 = start; + m_planeSelected = planeSelected; + } }; class TranslateFree : public Manipulatable { private: -Vector3 m_start; -Translatable& m_translatable; -AABB m_bounds; + Vector3 m_start; + Translatable& m_translatable; + AABB m_bounds; public: -TranslateFree( Translatable& translatable ) - : m_translatable( translatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_plane( device2manip, x, y ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = point_on_plane( device2manip, x, y ); - current = vector3_subtracted( current, m_start ); + TranslateFree( Translatable& translatable ) + : m_translatable( translatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_plane( device2manip, x, y ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = point_on_plane( device2manip, x, y ); + current = vector3_subtracted( current, m_start ); - if( snap ) - current *= g_vector3_axes[vector3_max_abs_component_index( current )]; + if( snap ) + current *= g_vector3_axes[vector3_max_abs_component_index( current )]; - current = translation_local2object( current, manip2object ); + current = translation_local2object( current, manip2object ); - if( snapbbox ) - aabb_snap_translation( current, m_bounds ); - else - vector3_snap( current, GetSnapGridSize() ); + if( snapbbox ) + aabb_snap_translation( current, m_bounds ); + else + vector3_snap( current, GetSnapGridSize() ); - m_translatable.translate( current ); -} + m_translatable.translate( current ); + } }; class TranslateFreeXY_Z : public Manipulatable { private: -Vector3 m_0; -std::size_t m_axisZ; -Plane3 m_planeXY; -Plane3 m_planeZ; -Vector3 m_startXY; -Vector3 m_startZ; -Translatable& m_translatable; -AABB m_bounds; + Vector3 m_0; + std::size_t m_axisZ; + Plane3 m_planeXY; + Plane3 m_planeZ; + Vector3 m_startXY; + Vector3 m_startZ; + Translatable& m_translatable; + AABB m_bounds; public: -static int m_viewdependent; -TranslateFreeXY_Z( Translatable& translatable ) - : m_translatable( translatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_axisZ = ( m_viewdependent || !m_view->fill() )? vector3_max_abs_component_index( m_view->getViewDir() ) : 2; - if( m_0 == g_vector3_identity ) /* special value to indicate missing good point to start with, i.e. while dragging components by clicking anywhere; m_startXY, m_startZ != m_0 in this case */ - m_0 = transform_origin; - m_planeXY = Plane3( g_vector3_axes[m_axisZ], m_0[m_axisZ] ); -#if 0 - Vector3 xydir( m_view->getViewDir() ); -#else - Vector3 xydir( m_view->getViewer() - m_0 ); -#endif - xydir[m_axisZ] = 0; - vector3_normalise( xydir ); - m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); - m_startXY = point_on_plane( m_planeXY, m_view->GetViewMatrix(), x, y ); - m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current; - if( alt && m_view->fill() ) - current = ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) * g_vector3_axes[m_axisZ]; - else{ - current = point_on_plane( m_planeXY, m_view->GetViewMatrix(), x, y ) - m_startXY; - current[m_axisZ] = 0; + static int m_viewdependent; + TranslateFreeXY_Z( Translatable& translatable ) + : m_translatable( translatable ){ } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_axisZ = ( m_viewdependent || !m_view->fill() )? vector3_max_abs_component_index( m_view->getViewDir() ) : 2; + if( m_0 == g_vector3_identity ) /* special value to indicate missing good point to start with, i.e. while dragging components by clicking anywhere; m_startXY, m_startZ != m_0 in this case */ + m_0 = transform_origin; + m_planeXY = Plane3( g_vector3_axes[m_axisZ], m_0[m_axisZ] ); +#if 0 + Vector3 xydir( m_view->getViewDir() ); +#else + Vector3 xydir( m_view->getViewer() - m_0 ); +#endif + xydir[m_axisZ] = 0; + vector3_normalise( xydir ); + m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); + m_startXY = point_on_plane( m_planeXY, m_view->GetViewMatrix(), x, y ); + m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current; + if( alt && m_view->fill() ) + current = ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) * g_vector3_axes[m_axisZ]; + else{ + current = point_on_plane( m_planeXY, m_view->GetViewMatrix(), x, y ) - m_startXY; + current[m_axisZ] = 0; + } - if( snap ) - current *= g_vector3_axes[vector3_max_abs_component_index( current )]; + if( snap ) + current *= g_vector3_axes[vector3_max_abs_component_index( current )]; - if( snapbbox ) - aabb_snap_translation( current, m_bounds ); - else - vector3_snap( current, GetSnapGridSize() ); + if( snapbbox ) + aabb_snap_translation( current, m_bounds ); + else + vector3_snap( current, GetSnapGridSize() ); - m_translatable.translate( current ); -} -void set0( const Vector3& start ){ - m_0 = start; -} + m_translatable.translate( current ); + } + void set0( const Vector3& start ){ + m_0 = start; + } }; int TranslateFreeXY_Z::m_viewdependent = 0; class Scalable { public: -virtual void scale( const Vector3& scaling ) = 0; + virtual void scale( const Vector3& scaling ) = 0; }; class ScaleAxis : public Manipulatable { private: -Vector3 m_start; -Vector3 m_axis; -Scalable& m_scalable; + Vector3 m_start; + Vector3 m_axis; + Scalable& m_scalable; -Vector3 m_choosen_extent; -AABB m_bounds; + Vector3 m_choosen_extent; + AABB m_bounds; public: -ScaleAxis( Scalable& scalable ) - : m_scalable( scalable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_axis( m_axis, device2manip, x, y ); - - m_choosen_extent = Vector3( - std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ), - std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ), - std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] ) - ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - //globalOutputStream() << "manip2object: " << manip2object << " device2manip: " << device2manip << " x: " << x << " y:" << y <<"\n"; - Vector3 current = point_on_axis( m_axis, device2manip, x, y ); - Vector3 delta = vector3_subtracted( current, m_start ); - - delta = translation_local2object( delta, manip2object ); - vector3_snap( delta, GetSnapGridSize() ); - vector3_scale( delta, m_axis ); - - Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.f ? GetSnapGridSize() : 1e-3f ) ); - for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize - if( float_snapped( m_start[i], 1e-3f ) != 0.f && start[i] == 0.f ){ - start[i] = GetSnapGridSize(); - } + ScaleAxis( Scalable& scalable ) + : m_scalable( scalable ){ } - //globalOutputStream() << "m_start: " << m_start << " start: " << start << " delta: " << delta <<"\n"; - /* boundless way */ - Vector3 scale( - start[0] == 0 ? 1 : 1 + delta[0] / start[0], - start[1] == 0 ? 1 : 1 + delta[1] / start[1], - start[2] == 0 ? 1 : 1 + delta[2] / start[2] + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_axis( m_axis, device2manip, x, y ); + + m_choosen_extent = Vector3( + std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ), + std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ), + std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] ) + ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + //globalOutputStream() << "manip2object: " << manip2object << " device2manip: " << device2manip << " x: " << x << " y:" << y <<"\n"; + Vector3 current = point_on_axis( m_axis, device2manip, x, y ); + Vector3 delta = vector3_subtracted( current, m_start ); + + delta = translation_local2object( delta, manip2object ); + vector3_snap( delta, GetSnapGridSize() ); + vector3_scale( delta, m_axis ); + + Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.f ? GetSnapGridSize() : 1e-3f ) ); + for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize + if( float_snapped( m_start[i], 1e-3f ) != 0.f && start[i] == 0.f ){ + start[i] = GetSnapGridSize(); + } + } + //globalOutputStream() << "m_start: " << m_start << " start: " << start << " delta: " << delta <<"\n"; + /* boundless way */ + Vector3 scale( + start[0] == 0 ? 1 : 1 + delta[0] / start[0], + start[1] == 0 ? 1 : 1 + delta[1] / start[1], + start[2] == 0 ? 1 : 1 + delta[2] / start[2] ); - /* try bbox way */ - for( std::size_t i = 0; i < 3; i++ ){ - if( m_choosen_extent[i] > 0.0625f && m_axis[i] != 0.f ){ //epsilon to prevent super high scale for set of models, having really small extent, formed by origins - scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i]; - if( snapbbox ){ - const float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() ); - scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f ); - } - } - } - if( snap ){ + /* try bbox way */ for( std::size_t i = 0; i < 3; i++ ){ - if( m_axis[i] == 0.f ){ - scale[i] = vector3_dot( scale, vector3_scaled( m_axis, m_axis ) ); + if( m_choosen_extent[i] > 0.0625f && m_axis[i] != 0.f ){ //epsilon to prevent super high scale for set of models, having really small extent, formed by origins + scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i]; + if( snapbbox ){ + const float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() ); + scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f ); + } } } + if( snap ){ + for( std::size_t i = 0; i < 3; i++ ){ + if( m_axis[i] == 0.f ){ + scale[i] = vector3_dot( scale, vector3_scaled( m_axis, m_axis ) ); + } + } + } + //globalOutputStream() << "scale: " << scale <<"\n"; + m_scalable.scale( scale ); } - //globalOutputStream() << "scale: " << scale <<"\n"; - m_scalable.scale( scale ); -} -void SetAxis( const Vector3& axis ){ - m_axis = axis; -} + void SetAxis( const Vector3& axis ){ + m_axis = axis; + } }; class ScaleFree : public Manipulatable { private: -Vector3 m_start; -Vector3 m_axis; -Vector3 m_axis2; -Scalable& m_scalable; + Vector3 m_start; + Vector3 m_axis; + Vector3 m_axis2; + Scalable& m_scalable; -Vector3 m_choosen_extent; -AABB m_bounds; + Vector3 m_choosen_extent; + AABB m_bounds; public: -ScaleFree( Scalable& scalable ) - : m_scalable( scalable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_plane( device2manip, x, y ); - - m_choosen_extent = Vector3( - std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], -( bounds.origin[0] - bounds.extents[0] - transform_origin[0] ) ), - std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], -( bounds.origin[1] - bounds.extents[1] - transform_origin[1] ) ), - std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], -( bounds.origin[2] - bounds.extents[2] - transform_origin[2] ) ) - ); - m_bounds = bounds; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = point_on_plane( device2manip, x, y ); - Vector3 delta = vector3_subtracted( current, m_start ); - - delta = translation_local2object( delta, manip2object ); - vector3_snap( delta, GetSnapGridSize() ); - if( m_axis != g_vector3_identity ) - delta = vector3_scaled( delta, m_axis ) + vector3_scaled( delta, m_axis2 ); - - Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.f ? GetSnapGridSize() : 1e-3f ) ); - for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize - if( float_snapped( m_start[i], 1e-3f ) != 0.f && start[i] == 0.f ){ - start[i] = GetSnapGridSize(); - } + ScaleFree( Scalable& scalable ) + : m_scalable( scalable ){ } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_plane( device2manip, x, y ); - const std::size_t ignore_axis = vector3_min_abs_component_index( m_start ); - if( snap ) - start[ignore_axis] = 0.f; + m_choosen_extent = Vector3( + std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], -( bounds.origin[0] - bounds.extents[0] - transform_origin[0] ) ), + std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], -( bounds.origin[1] - bounds.extents[1] - transform_origin[1] ) ), + std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], -( bounds.origin[2] - bounds.extents[2] - transform_origin[2] ) ) + ); + m_bounds = bounds; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = point_on_plane( device2manip, x, y ); + Vector3 delta = vector3_subtracted( current, m_start ); - Vector3 scale( - start[0] == 0 ? 1 : 1 + delta[0] / start[0], - start[1] == 0 ? 1 : 1 + delta[1] / start[1], - start[2] == 0 ? 1 : 1 + delta[2] / start[2] + delta = translation_local2object( delta, manip2object ); + vector3_snap( delta, GetSnapGridSize() ); + if( m_axis != g_vector3_identity ) + delta = vector3_scaled( delta, m_axis ) + vector3_scaled( delta, m_axis2 ); + + Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.f ? GetSnapGridSize() : 1e-3f ) ); + for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize + if( float_snapped( m_start[i], 1e-3f ) != 0.f && start[i] == 0.f ){ + start[i] = GetSnapGridSize(); + } + } + + const std::size_t ignore_axis = vector3_min_abs_component_index( m_start ); + if( snap ) + start[ignore_axis] = 0.f; + + Vector3 scale( + start[0] == 0 ? 1 : 1 + delta[0] / start[0], + start[1] == 0 ? 1 : 1 + delta[1] / start[1], + start[2] == 0 ? 1 : 1 + delta[2] / start[2] ); - //globalOutputStream() << "m_start: " << m_start << " start: " << start << " delta: " << delta <<"\n"; - for( std::size_t i = 0; i < 3; i++ ){ - if( m_choosen_extent[i] > 0.0625f && start[i] != 0.f ){ - scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i]; - if( snapbbox ){ - const float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() ); - scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f ); - } - } - } - //globalOutputStream() << "pre snap scale: " << scale <<"\n"; - if( snap ){ - float bestscale = ignore_axis != 0 ? scale[0] : scale[1]; - for( std::size_t i = ignore_axis != 0 ? 1 : 2; i < 3; i++ ){ - if( ignore_axis != i && fabs( scale[i] ) < fabs( bestscale ) ){ - bestscale = scale[i]; - } - //globalOutputStream() << "bestscale: " << bestscale <<"\n"; - } + //globalOutputStream() << "m_start: " << m_start << " start: " << start << " delta: " << delta <<"\n"; for( std::size_t i = 0; i < 3; i++ ){ - if( ignore_axis != i ){ - scale[i] = ( scale[i] < 0.f ) ? -fabs( bestscale ) : fabs( bestscale ); + if( m_choosen_extent[i] > 0.0625f && start[i] != 0.f ){ + scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i]; + if( snapbbox ){ + const float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() ); + scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f ); + } } } + //globalOutputStream() << "pre snap scale: " << scale <<"\n"; + if( snap ){ + float bestscale = ignore_axis != 0 ? scale[0] : scale[1]; + for( std::size_t i = ignore_axis != 0 ? 1 : 2; i < 3; i++ ){ + if( ignore_axis != i && fabs( scale[i] ) < fabs( bestscale ) ){ + bestscale = scale[i]; + } + //globalOutputStream() << "bestscale: " << bestscale <<"\n"; + } + for( std::size_t i = 0; i < 3; i++ ){ + if( ignore_axis != i ){ + scale[i] = ( scale[i] < 0.f ) ? -fabs( bestscale ) : fabs( bestscale ); + } + } + } + //globalOutputStream() << "scale: " << scale <<"\n"; + m_scalable.scale( scale ); + } + void SetAxes( const Vector3& axis, const Vector3& axis2 ){ + m_axis = axis; + m_axis2 = axis2; } - //globalOutputStream() << "scale: " << scale <<"\n"; - m_scalable.scale( scale ); -} -void SetAxes( const Vector3& axis, const Vector3& axis2 ){ - m_axis = axis; - m_axis2 = axis2; -} }; class Skewable { public: -virtual void skew( const Skew& skew ) = 0; + virtual void skew( const Skew& skew ) = 0; }; class SkewAxis : public Manipulatable { private: -Vector3 m_0; -Plane3 m_planeZ; + Vector3 m_0; + Plane3 m_planeZ; -int m_axis_which; -int m_axis_by; -int m_axis_by_sign; -Skewable& m_skewable; + int m_axis_which; + int m_axis_by; + int m_axis_by_sign; + Skewable& m_skewable; -float m_axis_by_extent; -AABB m_bounds; + float m_axis_by_extent; + AABB m_bounds; public: -SkewAxis( Skewable& skewable ) - : m_skewable( skewable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - Vector3 xydir( m_view->getViewer() - m_0 ); - xydir[m_axis_which] = 0; + SkewAxis( Skewable& skewable ) + : m_skewable( skewable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + Vector3 xydir( m_view->getViewer() - m_0 ); + xydir[m_axis_which] = 0; // xydir *= g_vector3_axes[vector3_max_abs_component_index( xydir )]; - vector3_normalise( xydir ); - m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); + vector3_normalise( xydir ); + m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); - m_bounds = bounds; - m_axis_by_extent = bounds.origin[m_axis_by] + bounds.extents[m_axis_by] * m_axis_by_sign - transform_origin[m_axis_by]; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - const Vector3 current = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_0; + m_bounds = bounds; + m_axis_by_extent = bounds.origin[m_axis_by] + bounds.extents[m_axis_by] * m_axis_by_sign - transform_origin[m_axis_by]; + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + const Vector3 current = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_0; // globalOutputStream() << m_axis_which << " by axis " << m_axis_by << "\n"; - m_skewable.skew( Skew( m_axis_by * 4 + m_axis_which, m_axis_by_extent != 0.f? float_snapped( current[m_axis_which], GetSnapGridSize() ) / m_axis_by_extent : 0 ) ); -} -void SetAxes( int axis_which, int axis_by, int axis_by_sign ){ - m_axis_which = axis_which; - m_axis_by = axis_by; - m_axis_by_sign = axis_by_sign; -} -void set0( const Vector3& start ){ - m_0 = start; -} + m_skewable.skew( Skew( m_axis_by * 4 + m_axis_which, m_axis_by_extent != 0.f? float_snapped( current[m_axis_which], GetSnapGridSize() ) / m_axis_by_extent : 0 ) ); + } + void SetAxes( int axis_which, int axis_by, int axis_by_sign ){ + m_axis_which = axis_which; + m_axis_by = axis_by; + m_axis_by_sign = axis_by_sign; + } + void set0( const Vector3& start ){ + m_0 = start; + } }; #include "brush.h" @@ -735,62 +735,62 @@ void set0( const Vector3& start ){ class DragNewBrush : public Manipulatable { private: -Vector3 m_0; -Vector3 m_size; -float m_setSizeZ; /* store separately for fine square/cube modes handling */ -scene::Node* m_newBrushNode; + Vector3 m_0; + Vector3 m_size; + float m_setSizeZ; /* store separately for fine square/cube modes handling */ + scene::Node* m_newBrushNode; public: -DragNewBrush(){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_setSizeZ = m_size[0] = m_size[1] = m_size[2] = GetGridSize(); - m_newBrushNode = 0; -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 diff_raw = point_on_plane( Plane3( g_vector3_axis_z, vector3_dot( g_vector3_axis_z, Vector3( m_size.x(), m_size.y(), m_setSizeZ ) + m_0 ) ), m_view->GetViewMatrix(), x, y ) - m_0; - const Vector3 xydir( vector3_normalised( Vector3( m_view->GetModelview()[2], m_view->GetModelview()[6], 0 ) ) ); - diff_raw.z() = ( point_on_plane( Plane3( xydir, vector3_dot( xydir, Vector3( m_size.x(), m_size.y(), m_setSizeZ ) + m_0 ) ), m_view->GetViewMatrix(), x, y ) - m_0 ).z(); - Vector3 diff = vector3_snapped( diff_raw, GetSnapGridSize() ); - - for ( std::size_t i = 0; i < 3; ++i ) - if( diff[i] == 0 ) - diff[i] = diff_raw[i] < 0? -GetGridSize() : GetGridSize(); - - if( alt ){ - diff.x() = m_size.x(); - diff.y() = m_size.y(); + DragNewBrush(){ } - else{ - diff.z() = m_size.z(); + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_setSizeZ = m_size[0] = m_size[1] = m_size[2] = GetGridSize(); + m_newBrushNode = 0; } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 diff_raw = point_on_plane( Plane3( g_vector3_axis_z, vector3_dot( g_vector3_axis_z, Vector3( m_size.x(), m_size.y(), m_setSizeZ ) + m_0 ) ), m_view->GetViewMatrix(), x, y ) - m_0; + const Vector3 xydir( vector3_normalised( Vector3( m_view->GetModelview()[2], m_view->GetModelview()[6], 0 ) ) ); + diff_raw.z() = ( point_on_plane( Plane3( xydir, vector3_dot( xydir, Vector3( m_size.x(), m_size.y(), m_setSizeZ ) + m_0 ) ), m_view->GetViewMatrix(), x, y ) - m_0 ).z(); + Vector3 diff = vector3_snapped( diff_raw, GetSnapGridSize() ); - const float z = vector4_projected( matrix4_transformed_vector4( m_view->GetViewMatrix(), Vector4( diff + m_0, 1 ) ) ).z(); - if( z != z || z > 1 ) //catch NAN and behind near, far planes cases - return; + for ( std::size_t i = 0; i < 3; ++i ) + if( diff[i] == 0 ) + diff[i] = diff_raw[i] < 0? -GetGridSize() : GetGridSize(); - if( snap || snapbbox ){ - const float squaresize = std::max( fabs( diff.x() ), fabs( diff.y() ) ); - diff.x() = diff.x() > 0? squaresize : -squaresize; //square - diff.y() = diff.y() > 0? squaresize : -squaresize; - if( snapbbox && !alt ) //cube - diff.z() = diff.z() > 0? squaresize : -squaresize; + if( alt ){ + diff.x() = m_size.x(); + diff.y() = m_size.y(); + } + else{ + diff.z() = m_size.z(); + } + + const float z = vector4_projected( matrix4_transformed_vector4( m_view->GetViewMatrix(), Vector4( diff + m_0, 1 ) ) ).z(); + if( z != z || z > 1 ) //catch NAN and behind near, far planes cases + return; + + if( snap || snapbbox ){ + const float squaresize = std::max( fabs( diff.x() ), fabs( diff.y() ) ); + diff.x() = diff.x() > 0? squaresize : -squaresize; //square + diff.y() = diff.y() > 0? squaresize : -squaresize; + if( snapbbox && !alt ) //cube + diff.z() = diff.z() > 0? squaresize : -squaresize; + } + + m_size = diff; + if( alt ) + m_setSizeZ = diff.z(); + + Vector3 mins( m_0 ); + Vector3 maxs( m_0 + diff ); + for ( std::size_t i = 0; i < 3; ++i ) + if( mins[i] > maxs[i] ) + std::swap( mins[i], maxs[i] ); + + Scene_BrushResize_Cuboid( m_newBrushNode, aabb_for_minmax( mins, maxs ) ); + } + void set0( const Vector3& start ){ + m_0 = start; } - - m_size = diff; - if( alt ) - m_setSizeZ = diff.z(); - - Vector3 mins( m_0 ); - Vector3 maxs( m_0 + diff ); - for ( std::size_t i = 0; i < 3; ++i ) - if( mins[i] > maxs[i] ) - std::swap( mins[i], maxs[i] ); - - Scene_BrushResize_Cuboid( m_newBrushNode, aabb_for_minmax( mins, maxs ) ); -} -void set0( const Vector3& start ){ - m_0 = start; -} }; @@ -798,27 +798,35 @@ void set0( const Vector3& start ){ class DragExtrudeFaces : public Manipulatable { private: -Vector3 m_0; -Plane3 m_planeSelected; -std::size_t m_axisZ; -Plane3 m_planeZ; -Vector3 m_startZ; + Vector3 m_0; + Plane3 m_planeSelected; + std::size_t m_axisZ; + Plane3 m_planeZ; + Vector3 m_startZ; -bool m_originalBrushSaved; -bool m_originalBrushChanged; + bool m_originalBrushSaved; + bool m_originalBrushChanged; public: class ExtrudeSource { public: BrushInstance* m_brushInstance; - struct InFaceOutBrush{ Face* m_face; PlanePoints m_planepoints; Brush* m_outBrush; }; + struct InFaceOutBrush{ + Face* m_face; + PlanePoints m_planepoints; + Brush* m_outBrush; + }; std::vector m_faces; std::vector::iterator faceFind( const Face* face ){ - return std::find_if( m_faces.begin(), m_faces.end(), [face]( const InFaceOutBrush& infaceoutbrush ){ return face == infaceoutbrush.m_face; } ); + return std::find_if( m_faces.begin(), m_faces.end(), [face]( const InFaceOutBrush& infaceoutbrush ){ + return face == infaceoutbrush.m_face; + } ); } std::vector::const_iterator faceFind( const Face* face ) const { - return std::find_if( m_faces.begin(), m_faces.end(), [face]( const InFaceOutBrush& infaceoutbrush ){ return face == infaceoutbrush.m_face; } ); + return std::find_if( m_faces.begin(), m_faces.end(), [face]( const InFaceOutBrush& infaceoutbrush ){ + return face == infaceoutbrush.m_face; + } ); } bool faceExcluded( const Face* face ) const { return faceFind( face ) == m_faces.end(); @@ -826,268 +834,268 @@ public: }; std::vector m_extrudeSources; -DragExtrudeFaces(){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_axisZ = vector3_max_abs_component_index( m_planeSelected.normal() ); - Vector3 xydir( m_view->getViewer() - m_0 ); - xydir[m_axisZ] = 0; - vector3_normalise( xydir ); - m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); - m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); + DragExtrudeFaces(){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_axisZ = vector3_max_abs_component_index( m_planeSelected.normal() ); + Vector3 xydir( m_view->getViewer() - m_0 ); + xydir[m_axisZ] = 0; + vector3_normalise( xydir ); + m_planeZ = Plane3( xydir, vector3_dot( xydir, m_0 ) ); + m_startZ = point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ); - m_originalBrushSaved = false; - m_originalBrushChanged = false; + m_originalBrushSaved = false; + m_originalBrushChanged = false; - UndoableCommand undo( "ExtrudeBrushFaces" ); - for( ExtrudeSource& source : m_extrudeSources ){ - for( auto& infaceoutbrush : source.m_faces ){ - const Face* face = infaceoutbrush.m_face; + UndoableCommand undo( "ExtrudeBrushFaces" ); + for( ExtrudeSource& source : m_extrudeSources ){ + for( auto& infaceoutbrush : source.m_faces ){ + const Face* face = infaceoutbrush.m_face; - NodeSmartReference node( GlobalBrushCreator().createBrush() ); - Node_getTraversable( source.m_brushInstance->path().parent() )->insert( node ); + NodeSmartReference node( GlobalBrushCreator().createBrush() ); + Node_getTraversable( source.m_brushInstance->path().parent() )->insert( node ); - scene::Path path( source.m_brushInstance->path() ); - path.pop(); - path.push( makeReference( node.get() ) ); - selectPath( path, true ); + scene::Path path( source.m_brushInstance->path() ); + path.pop(); + path.push( makeReference( node.get() ) ); + selectPath( path, true ); - Brush* brush = Node_getBrush( node.get() ); - infaceoutbrush.m_outBrush = brush; + Brush* brush = Node_getBrush( node.get() ); + infaceoutbrush.m_outBrush = brush; - Face* f = brush->addFace( *face ); - f->getPlane().offset( GetGridSize() ); - f->planeChanged(); + Face* f = brush->addFace( *face ); + f->getPlane().offset( GetGridSize() ); + f->planeChanged(); - f = brush->addFace( *face ); - f->getPlane().reverse(); - f->planeChanged(); + f = brush->addFace( *face ); + f->getPlane().reverse(); + f->planeChanged(); - for( const WindingVertex& vertex : face->getWinding() ){ - if( vertex.adjacent != c_brush_maxFaces ){ - f = brush->addFace( **std::next( source.m_brushInstance->getBrush().begin(), vertex.adjacent ) ); + for( const WindingVertex& vertex : face->getWinding() ){ + if( vertex.adjacent != c_brush_maxFaces ){ + f = brush->addFace( **std::next( source.m_brushInstance->getBrush().begin(), vertex.adjacent ) ); - const DoubleVector3 cross = vector3_cross( f->plane3_().normal(), face->plane3_().normal() ); - f->getPlane().copy( vertex.vertex, vertex.vertex + cross * 64, vertex.vertex + face->plane3_().normal() * 64 ); - f->planeChanged(); + const DoubleVector3 cross = vector3_cross( f->plane3_().normal(), face->plane3_().normal() ); + f->getPlane().copy( vertex.vertex, vertex.vertex + cross * 64, vertex.vertex + face->plane3_().normal() * 64 ); + f->planeChanged(); + } } } } } -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = g_vector3_axes[m_axisZ] * vector3_dot( m_planeSelected.normal(), ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) ) - * ( m_planeSelected.normal()[m_axisZ] >= 0? 1 : -1 ); + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = g_vector3_axes[m_axisZ] * vector3_dot( m_planeSelected.normal(), ( point_on_plane( m_planeZ, m_view->GetViewMatrix(), x, y ) - m_startZ ) ) + * ( m_planeSelected.normal()[m_axisZ] >= 0? 1 : -1 ); - if( !std::isfinite( current[0] ) || !std::isfinite( current[1] ) || !std::isfinite( current[2] ) ) // catch INF case, is likely with top of the box in 2D - return; + if( !std::isfinite( current[0] ) || !std::isfinite( current[1] ) || !std::isfinite( current[2] ) ) // catch INF case, is likely with top of the box in 2D + return; - vector3_snap( current, GetSnapGridSize() ); + vector3_snap( current, GetSnapGridSize() ); - const float offset = fabs( m_planeSelected.normal()[m_axisZ] ) * ( vector3_dot( current, m_planeSelected.normal() ) >= 0? - std::max( GetGridSize(), static_cast( vector3_length( current ) ) ) - : -std::max( GetGridSize(), static_cast( vector3_length( current ) ) ) ); + const float offset = fabs( m_planeSelected.normal()[m_axisZ] ) * std::copysign( + std::max( static_cast( GetGridSize() ), vector3_length( current ) ), + vector3_dot( current, m_planeSelected.normal() ) ); - if( offset >= 0 ){ // extrude outside - if( m_originalBrushChanged ){ - m_originalBrushChanged = false; + if( offset >= 0 ){ // extrude outside + if( m_originalBrushChanged ){ + m_originalBrushChanged = false; + for( ExtrudeSource& source : m_extrudeSources ){ + // revert original brush + for( auto& infaceoutbrush : source.m_faces ){ + Face* face = infaceoutbrush.m_face; + face->getPlane().copy( infaceoutbrush.m_planepoints ); + face->planeChanged(); + } + } + } for( ExtrudeSource& source : m_extrudeSources ){ + Brush& brush0 = source.m_brushInstance->getBrush(); + if( source.m_faces.size() > 1 ){ + Brush* tmpbrush = new Brush( brush0 ); + offsetFaces( source, *tmpbrush, offset ); + brush_extrudeDiag( brush0, *tmpbrush, source ); + delete tmpbrush; + } + else{ + for( auto& infaceoutbrush : source.m_faces ){ + const Face* face = infaceoutbrush.m_face; + Brush* brush = infaceoutbrush.m_outBrush; + brush->clear(); + + Face* f = brush->addFace( *face ); + f->getPlane().offset( offset ); + f->planeChanged(); + + f = brush->addFace( *face ); + f->getPlane().reverse(); + f->planeChanged(); + + for( const WindingVertex& vertex : face->getWinding() ){ + if( vertex.adjacent != c_brush_maxFaces ){ + brush->addFace( **std::next( brush0.begin(), vertex.adjacent ) ); + } + } + } + } + } + } + else{ // extrude inside + if( !m_originalBrushSaved ){ + m_originalBrushSaved = true; + for( ExtrudeSource& source : m_extrudeSources ) + for( auto& infaceoutbrush : source.m_faces ) + infaceoutbrush.m_face->undoSave(); + } + m_originalBrushChanged = true; + + for( ExtrudeSource& source : m_extrudeSources ){ + Brush& brush0 = source.m_brushInstance->getBrush(); // revert original brush for( auto& infaceoutbrush : source.m_faces ){ Face* face = infaceoutbrush.m_face; face->getPlane().copy( infaceoutbrush.m_planepoints ); face->planeChanged(); } - } - } - for( ExtrudeSource& source : m_extrudeSources ){ - Brush& brush0 = source.m_brushInstance->getBrush(); - if( source.m_faces.size() > 1 ){ - Brush* tmpbrush = new Brush( brush0 ); - offsetFaces( source, *tmpbrush, offset ); - brush_extrudeDiag( brush0, *tmpbrush, source ); - delete tmpbrush; - } - else{ - for( auto& infaceoutbrush : source.m_faces ){ - const Face* face = infaceoutbrush.m_face; - Brush* brush = infaceoutbrush.m_outBrush; - brush->clear(); + if( source.m_faces.size() > 1 ){ + Brush* tmpbrush = new Brush( brush0 ); + tmpbrush->evaluateBRep(); + offsetFaces( source, brush0, offset ); + if( brush0.hasContributingFaces() ) + brush_extrudeDiag( brush0, *tmpbrush, source ); + delete tmpbrush; + } + else{ + for( auto& infaceoutbrush : source.m_faces ){ + Face* face = infaceoutbrush.m_face; + Brush* brush = infaceoutbrush.m_outBrush; + brush->clear(); - Face* f = brush->addFace( *face ); - f->getPlane().offset( offset ); - f->planeChanged(); + brush->copy( brush0 ); - f = brush->addFace( *face ); - f->getPlane().reverse(); - f->planeChanged(); + Face* f = brush->addFace( *face ); + f->getPlane().offset( offset ); + f->getPlane().reverse(); + f->planeChanged(); - for( const WindingVertex& vertex : face->getWinding() ){ - if( vertex.adjacent != c_brush_maxFaces ){ - brush->addFace( **std::next( brush0.begin(), vertex.adjacent ) ); - } + brush->removeEmptyFaces(); + // modify original brush + face->getPlane().offset( offset ); + face->planeChanged(); } } } } } - else{ // extrude inside - if( !m_originalBrushSaved ){ - m_originalBrushSaved = true; - for( ExtrudeSource& source : m_extrudeSources ) - for( auto& infaceoutbrush : source.m_faces ) - infaceoutbrush.m_face->undoSave(); - } - m_originalBrushChanged = true; - - for( ExtrudeSource& source : m_extrudeSources ){ - Brush& brush0 = source.m_brushInstance->getBrush(); - // revert original brush - for( auto& infaceoutbrush : source.m_faces ){ - Face* face = infaceoutbrush.m_face; - face->getPlane().copy( infaceoutbrush.m_planepoints ); - face->planeChanged(); - } - if( source.m_faces.size() > 1 ){ - Brush* tmpbrush = new Brush( brush0 ); - tmpbrush->evaluateBRep(); - offsetFaces( source, brush0, offset ); - if( brush0.hasContributingFaces() ) - brush_extrudeDiag( brush0, *tmpbrush, source ); - delete tmpbrush; - } - else{ - for( auto& infaceoutbrush : source.m_faces ){ - Face* face = infaceoutbrush.m_face; - Brush* brush = infaceoutbrush.m_outBrush; - brush->clear(); - - brush->copy( brush0 ); - - Face* f = brush->addFace( *face ); - f->getPlane().offset( offset ); - f->getPlane().reverse(); - f->planeChanged(); - - brush->removeEmptyFaces(); - // modify original brush - face->getPlane().offset( offset ); - face->planeChanged(); - } - } - } + void set0( const Vector3& start, const Plane3& planeSelected ){ + m_0 = start; + m_planeSelected = planeSelected; } -} -void set0( const Vector3& start, const Plane3& planeSelected ){ - m_0 = start; - m_planeSelected = planeSelected; -} private: -void offsetFaces( const ExtrudeSource& source, Brush& brush, const float offset ){ - const Brush& brush0 = source.m_brushInstance->getBrush(); - for( Brush::const_iterator i0 = brush0.begin(); i0 != brush0.end(); ++i0 ){ - const Face& face0 = *( *i0 ); - if( !source.faceExcluded( &face0 ) ){ - Face& face = *( *std::next( brush.begin(), std::distance( brush0.begin(), i0 ) ) ); - face.getPlane().offset( offset ); - face.planeChanged(); + void offsetFaces( const ExtrudeSource& source, Brush& brush, const float offset ){ + const Brush& brush0 = source.m_brushInstance->getBrush(); + for( Brush::const_iterator i0 = brush0.begin(); i0 != brush0.end(); ++i0 ){ + const Face& face0 = *( *i0 ); + if( !source.faceExcluded( &face0 ) ){ + Face& face = *( *std::next( brush.begin(), std::distance( brush0.begin(), i0 ) ) ); + face.getPlane().offset( offset ); + face.planeChanged(); + } } + brush.evaluateBRep(); } - brush.evaluateBRep(); -} -/* brush0, brush2 are supposed to have same amount of faces in the same order; brush2 bigger than brush0 */ -void brush_extrudeDiag( const Brush& brush0, const Brush& brush2, ExtrudeSource& source ){ - TextureProjection projection; - TexDef_Construct_Default( projection ); + /* brush0, brush2 are supposed to have same amount of faces in the same order; brush2 bigger than brush0 */ + void brush_extrudeDiag( const Brush& brush0, const Brush& brush2, ExtrudeSource& source ){ + TextureProjection projection; + TexDef_Construct_Default( projection ); - for( Brush::const_iterator i0 = brush0.begin(); i0 != brush0.end(); ++i0 ){ - const Face& face0 = *( *i0 ); - const Face& face2 = *( *std::next( brush2.begin(), std::distance( brush0.begin(), i0 ) ) ); + for( Brush::const_iterator i0 = brush0.begin(); i0 != brush0.end(); ++i0 ){ + const Face& face0 = *( *i0 ); + const Face& face2 = *( *std::next( brush2.begin(), std::distance( brush0.begin(), i0 ) ) ); - auto infaceoutbrush_iter = source.faceFind( &face0 ); // brush0 = source.m_brushInstance->getBrush() - if( infaceoutbrush_iter != source.m_faces.end() ) { - if( face0.contributes() || face2.contributes() ) { - const char* shader = face0.GetShader(); + auto infaceoutbrush_iter = source.faceFind( &face0 ); // brush0 = source.m_brushInstance->getBrush() + if( infaceoutbrush_iter != source.m_faces.end() ) { + if( face0.contributes() || face2.contributes() ) { + const char* shader = face0.GetShader(); - Brush* outBrush = ( *infaceoutbrush_iter ).m_outBrush; - outBrush->clear(); + Brush* outBrush = ( *infaceoutbrush_iter ).m_outBrush; + outBrush->clear(); - if( face0.contributes() ){ - if( Face* newFace = outBrush->addFace( face0 ) ) { - newFace->flipWinding(); - } - } - if( face2.contributes() ){ - outBrush->addFace( face2 ); - } - - if( face0.contributes() && face2.contributes() ){ //sew two valid windings - const auto addSidePlanes = [&outBrush, shader, &projection]( const Winding& winding0, const Winding& winding2, const DoubleVector3 normal, const bool swap ){ - for( std::size_t index0 = 0; index0 < winding0.numpoints; ++index0 ){ - const std::size_t next = Winding_next( winding0, index0 ); - Vector3 BestPoint; - double bestdot = -1; - for( std::size_t index2 = 0; index2 < winding2.numpoints; ++index2 ){ - const double dot = vector3_dot( - vector3_normalised( - vector3_cross( - winding0[index0].vertex - winding0[next].vertex, - winding0[index0].vertex - winding2[index2].vertex - ) - ), - normal - ); - if( dot > bestdot ) { - bestdot = dot; - BestPoint = winding2[index2].vertex; - } - } - outBrush->addPlane( winding0[swap? next : index0].vertex, - winding0[swap? index0 : next].vertex, - BestPoint, - shader, - projection ); + if( face0.contributes() ){ + if( Face* newFace = outBrush->addFace( face0 ) ) { + newFace->flipWinding(); } - }; - //insert side planes from each winding perspective, as their form may change after brush expansion - addSidePlanes( face0.getWinding(), face2.getWinding(), face0.getPlane().plane3().normal(), false ); - addSidePlanes( face2.getWinding(), face0.getWinding(), face0.getPlane().plane3().normal(), true ); - } - else{ //one valid winding: this way may produce garbage with complex brushes, extruded partially, but does preferred result with simple ones - const auto addSidePlanes = [&outBrush, shader, &projection]( const Winding& winding0, const Brush& brush2, const Plane3 plane, const bool swap ){ - for( std::size_t index0 = 0; index0 < winding0.numpoints; ++index0 ){ - const std::size_t next = Winding_next( winding0, index0 ); - Vector3 BestPoint; - double bestdist = 999999; - for( const Face* f : brush2 ) { - const Winding& winding2 = f->getWinding(); + } + if( face2.contributes() ){ + outBrush->addFace( face2 ); + } + + if( face0.contributes() && face2.contributes() ){ //sew two valid windings + const auto addSidePlanes = [&outBrush, shader, &projection]( const Winding& winding0, const Winding& winding2, const DoubleVector3 normal, const bool swap ){ + for( std::size_t index0 = 0; index0 < winding0.numpoints; ++index0 ){ + const std::size_t next = Winding_next( winding0, index0 ); + Vector3 BestPoint; + double bestdot = -1; for( std::size_t index2 = 0; index2 < winding2.numpoints; ++index2 ){ - const double testdist = vector3_length( winding0[index0].vertex - winding2[index2].vertex ); - if( testdist < bestdist && plane3_distance_to_point( plane, winding2[index2].vertex ) > .05 ) { - bestdist = testdist; + const double dot = vector3_dot( + vector3_normalised( + vector3_cross( + winding0[index0].vertex - winding0[next].vertex, + winding0[index0].vertex - winding2[index2].vertex + ) + ), + normal + ); + if( dot > bestdot ) { + bestdot = dot; BestPoint = winding2[index2].vertex; } } + outBrush->addPlane( winding0[swap? next : index0].vertex, + winding0[swap? index0 : next].vertex, + BestPoint, + shader, + projection ); } - outBrush->addPlane( winding0[swap? next : index0].vertex, - winding0[swap? index0 : next].vertex, - BestPoint, - shader, - projection ); - } - }; + }; + //insert side planes from each winding perspective, as their form may change after brush expansion + addSidePlanes( face0.getWinding(), face2.getWinding(), face0.getPlane().plane3().normal(), false ); + addSidePlanes( face2.getWinding(), face0.getWinding(), face0.getPlane().plane3().normal(), true ); + } + else{ //one valid winding: this way may produce garbage with complex brushes, extruded partially, but does preferred result with simple ones + const auto addSidePlanes = [&outBrush, shader, &projection]( const Winding& winding0, const Brush& brush2, const Plane3 plane, const bool swap ){ + for( std::size_t index0 = 0; index0 < winding0.numpoints; ++index0 ){ + const std::size_t next = Winding_next( winding0, index0 ); + Vector3 BestPoint; + double bestdist = 999999; + for( const Face* f : brush2 ) { + const Winding& winding2 = f->getWinding(); + for( std::size_t index2 = 0; index2 < winding2.numpoints; ++index2 ){ + const double testdist = vector3_length( winding0[index0].vertex - winding2[index2].vertex ); + if( testdist < bestdist && plane3_distance_to_point( plane, winding2[index2].vertex ) > .05 ) { + bestdist = testdist; + BestPoint = winding2[index2].vertex; + } + } + } + outBrush->addPlane( winding0[swap? next : index0].vertex, + winding0[swap? index0 : next].vertex, + BestPoint, + shader, + projection ); + } + }; - if( face0.contributes() ) - addSidePlanes( face0.getWinding(), brush2, face0.getPlane().plane3(), false ); - else if( face2.contributes() ) - addSidePlanes( face2.getWinding(), brush0, plane3_flipped( face2.getPlane().plane3() ), true ); + if( face0.contributes() ) + addSidePlanes( face0.getWinding(), brush2, face0.getPlane().plane3(), false ); + else if( face2.contributes() ) + addSidePlanes( face2.getWinding(), brush0, plane3_flipped( face2.getPlane().plane3() ), true ); + } + outBrush->removeEmptyFaces(); } - outBrush->removeEmptyFaces(); } } } -} }; @@ -1098,58 +1106,58 @@ void brush_extrudeDiag( const Brush& brush0, const Brush& brush2, ExtrudeSource& class RenderableClippedPrimitive : public OpenGLRenderable { -struct primitive_t -{ - PointVertex m_points[9]; - std::size_t m_count; -}; -Matrix4 m_inverse; -std::vector m_primitives; -public: -Matrix4 m_world; - -void render( RenderStateFlags state ) const { - for ( std::size_t i = 0; i < m_primitives.size(); ++i ) + struct primitive_t { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_primitives[i].m_points[0].colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_primitives[i].m_points[0].vertex ); - switch ( m_primitives[i].m_count ) + PointVertex m_points[9]; + std::size_t m_count; + }; + Matrix4 m_inverse; + std::vector m_primitives; +public: + Matrix4 m_world; + + void render( RenderStateFlags state ) const { + for ( std::size_t i = 0; i < m_primitives.size(); ++i ) { - case 1: break; - case 2: glDrawArrays( GL_LINES, 0, GLsizei( m_primitives[i].m_count ) ); break; - default: glDrawArrays( GL_POLYGON, 0, GLsizei( m_primitives[i].m_count ) ); break; + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_primitives[i].m_points[0].colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_primitives[i].m_points[0].vertex ); + switch ( m_primitives[i].m_count ) + { + case 1: break; + case 2: glDrawArrays( GL_LINES, 0, GLsizei( m_primitives[i].m_count ) ); break; + default: glDrawArrays( GL_POLYGON, 0, GLsizei( m_primitives[i].m_count ) ); break; + } } } -} -void construct( const Matrix4& world2device ){ - m_inverse = matrix4_full_inverse( world2device ); - m_world = g_matrix4_identity; -} - -void insert( const Vector4 clipped[9], std::size_t count ){ - add_one(); - - m_primitives.back().m_count = count; - for ( std::size_t i = 0; i < count; ++i ) - { - Vector3 world_point( vector4_projected( matrix4_transformed_vector4( m_inverse, clipped[i] ) ) ); - m_primitives.back().m_points[i].vertex = vertex3f_for_vector3( world_point ); + void construct( const Matrix4& world2device ){ + m_inverse = matrix4_full_inverse( world2device ); + m_world = g_matrix4_identity; } -} -void destroy(){ - m_primitives.clear(); -} + void insert( const Vector4 clipped[9], std::size_t count ){ + add_one(); + + m_primitives.back().m_count = count; + for ( std::size_t i = 0; i < count; ++i ) + { + Vector3 world_point( vector4_projected( matrix4_transformed_vector4( m_inverse, clipped[i] ) ) ); + m_primitives.back().m_points[i].vertex = vertex3f_for_vector3( world_point ); + } + } + + void destroy(){ + m_primitives.clear(); + } private: -void add_one(){ - m_primitives.push_back( primitive_t() ); + void add_one(){ + m_primitives.push_back( primitive_t() ); - const Colour4b colour_clipped( 255, 127, 0, 255 ); + const Colour4b colour_clipped( 255, 127, 0, 255 ); - for ( std::size_t i = 0; i < 9; ++i ) - m_primitives.back().m_points[i].colour = colour_clipped; -} + for ( std::size_t i = 0; i < 9; ++i ) + m_primitives.back().m_points[i].colour = colour_clipped; + } }; #if defined( _DEBUG ) && !defined( _DEBUG_QUICKER ) @@ -1171,10 +1179,10 @@ bool point_test_polygon_2d( const point_t& P, point_iterator_t start, point_iter // loop through all edges of the polygon for ( point_iterator_t prev = finish - 1, cur = start; cur != finish; prev = cur, ++cur ) - { // edge from (*prev) to (*cur) + { // edge from (*prev) to (*cur) if ( ( ( ( *prev )[1] <= P[1] ) && ( ( *cur )[1] > P[1] ) ) // an upward crossing - || ( ( ( *prev )[1] > P[1] ) && ( ( *cur )[1] <= P[1] ) ) ) { // a downward crossing - // compute the actual edge-ray intersect x-coordinate + || ( ( ( *prev )[1] > P[1] ) && ( ( *cur )[1] <= P[1] ) ) ) { // a downward crossing + // compute the actual edge-ray intersect x-coordinate float vt = (float)( P[1] - ( *prev )[1] ) / ( ( *cur )[1] - ( *prev )[1] ); if ( P[0] < ( *prev )[0] + vt * ( ( *cur )[0] - ( *prev )[0] ) ) { // P[0] < intersect ++crossings; // a valid crossing of y=P[1] right of P[0] @@ -1216,7 +1224,7 @@ void BestPoint( std::size_t count, Vector4 clipped[9], SelectionIntersection& be double signed_area = triangle_signed_area_XY( normalised[0], normalised[1], normalised[2] ); if ( ( cull == eClipCullCW && signed_area > 0 ) - || ( cull == eClipCullCCW && signed_area < 0 ) ) { + || ( cull == eClipCullCCW && signed_area < 0 ) ) { return; } } @@ -1245,9 +1253,9 @@ void BestPoint( std::size_t count, Vector4 clipped[9], SelectionIntersection& be } else{ assign_if_closer( best, SelectionIntersection( depth, distance, ray_distance_to_plane( - Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ), - *plane - ) ) ); + Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ), + *plane + ) ) ); // globalOutputStream() << static_cast( ray_distance_to_plane( // Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ), // plane @@ -1262,19 +1270,19 @@ void BestPoint( std::size_t count, Vector4 clipped[9], SelectionIntersection& be plane = &plaine; } assign_if_closer( - best, - SelectionIntersection( - ray_distance_to_plane( - Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ), - *plane - ), - 0, - ray_distance_to_plane( - Ray( Vector3( 10, 8, 0 ), Vector3( 0, 0, 1 ) ), - *plane - ) - ) - ); + best, + SelectionIntersection( + ray_distance_to_plane( + Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ), + *plane + ), + 0, + ray_distance_to_plane( + Ray( Vector3( 10, 8, 0 ), Vector3( 0, 0, 1 ) ), + *plane + ) + ) + ); } #if defined( DEBUG_SELECTION ) @@ -1355,29 +1363,29 @@ void AABB_BestPoint( const Matrix4& local2view, clipcull_t cull, const AABB& aab for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 4 ) { BestPoint( - matrix4_clip_triangle( - local2view, - points[*i], - points[*( i + 1 )], - points[*( i + 3 )], - clipped - ), - clipped, - best, - cull - ); + matrix4_clip_triangle( + local2view, + points[*i], + points[*( i + 1 )], + points[*( i + 3 )], + clipped + ), + clipped, + best, + cull + ); BestPoint( - matrix4_clip_triangle( - local2view, - points[*( i + 1 )], - points[*( i + 2 )], - points[*( i + 3 )], - clipped - ), - clipped, - best, - cull - ); + matrix4_clip_triangle( + local2view, + points[*( i + 1 )], + points[*( i + 2 )], + points[*( i + 3 )], + clipped + ), + clipped, + best, + cull + ); } } @@ -1398,17 +1406,17 @@ void Triangles_BestPoint( const Matrix4& local2view, clipcull_t cull, FlatShaded { Vector4 clipped[9]; BestPoint( - matrix4_clip_triangle( - local2view, - reinterpret_cast( ( *x ).vertex ), - reinterpret_cast( ( *y ).vertex ), - reinterpret_cast( ( *z ).vertex ), - clipped - ), - clipped, - best, - cull - ); + matrix4_clip_triangle( + local2view, + reinterpret_cast( ( *x ).vertex ), + reinterpret_cast( ( *y ).vertex ), + reinterpret_cast( ( *z ).vertex ), + clipped + ), + clipped, + best, + cull + ); } } @@ -1417,40 +1425,40 @@ typedef std::multimap SelectableSortedSet; class SelectionPool : public Selector { -SelectableSortedSet m_pool; -SelectionIntersection m_intersection; -Selectable* m_selectable; + SelectableSortedSet m_pool; + SelectionIntersection m_intersection; + Selectable* m_selectable; public: -void pushSelectable( Selectable& selectable ){ - m_intersection = SelectionIntersection(); - m_selectable = &selectable; -} -void popSelectable(){ - addSelectable( m_intersection, m_selectable ); - m_intersection = SelectionIntersection(); -} -void addIntersection( const SelectionIntersection& intersection ){ - assign_if_closer( m_intersection, intersection ); -} -void addSelectable( const SelectionIntersection& intersection, Selectable* selectable ){ - if ( intersection.valid() ) { - m_pool.insert( SelectableSortedSet::value_type( intersection, selectable ) ); + void pushSelectable( Selectable& selectable ){ + m_intersection = SelectionIntersection(); + m_selectable = &selectable; + } + void popSelectable(){ + addSelectable( m_intersection, m_selectable ); + m_intersection = SelectionIntersection(); + } + void addIntersection( const SelectionIntersection& intersection ){ + assign_if_closer( m_intersection, intersection ); + } + void addSelectable( const SelectionIntersection& intersection, Selectable* selectable ){ + if ( intersection.valid() ) { + m_pool.insert( SelectableSortedSet::value_type( intersection, selectable ) ); + } } -} -typedef SelectableSortedSet::iterator iterator; + typedef SelectableSortedSet::iterator iterator; -iterator begin(){ - return m_pool.begin(); -} -iterator end(){ - return m_pool.end(); -} + iterator begin(){ + return m_pool.begin(); + } + iterator end(){ + return m_pool.end(); + } -bool failed(){ - return m_pool.empty(); -} + bool failed(){ + return m_pool.empty(); + } }; @@ -1512,12 +1520,12 @@ inline void draw_semicircle( const std::size_t segments, const float radius, Poi class Manipulator { public: -virtual Manipulatable* GetManipulatable() = 0; -virtual void testSelect( const View& view, const Matrix4& pivot2world ) = 0; -virtual void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ -} -virtual void setSelected( bool select ) = 0; -virtual bool isSelected() const = 0; + virtual Manipulatable* GetManipulatable() = 0; + virtual void testSelect( const View& view, const Matrix4& pivot2world ) = 0; + virtual void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ + } + virtual void setSelected( bool select ) = 0; + virtual bool isSelected() const = 0; }; @@ -1531,271 +1539,271 @@ inline Vector3 normalised_safe( const Vector3& self ){ class RotateManipulator : public Manipulator { -struct RenderableCircle : public OpenGLRenderable -{ - Array m_vertices; + struct RenderableCircle : public OpenGLRenderable + { + Array m_vertices; - RenderableCircle( std::size_t size ) : m_vertices( size ){ - } - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); - glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) ); - } - void setColour( const Colour4b& colour ){ - for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - ( *i ).colour = colour; + RenderableCircle( std::size_t size ) : m_vertices( size ){ } - } -}; - -struct RenderableSemiCircle : public OpenGLRenderable -{ - Array m_vertices; - - RenderableSemiCircle( std::size_t size ) : m_vertices( size ){ - } - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); - glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) ); - } - void setColour( const Colour4b& colour ){ - for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - ( *i ).colour = colour; + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); + glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) ); } - } -}; + void setColour( const Colour4b& colour ){ + for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + ( *i ).colour = colour; + } + } + }; -RotateFree m_free; -RotateAxis m_axis; -Vector3 m_axis_screen; -RenderableSemiCircle m_circle_x; -RenderableSemiCircle m_circle_y; -RenderableSemiCircle m_circle_z; -RenderableCircle m_circle_screen; -RenderableCircle m_circle_sphere; -SelectableBool m_selectable_x; -SelectableBool m_selectable_y; -SelectableBool m_selectable_z; -SelectableBool m_selectable_screen; -SelectableBool m_selectable_sphere; -Selectable* m_selectable_prev_ptr; -Pivot2World m_pivot; -Matrix4 m_local2world_x; -Matrix4 m_local2world_y; -Matrix4 m_local2world_z; -bool m_circle_x_visible; -bool m_circle_y_visible; -bool m_circle_z_visible; + struct RenderableSemiCircle : public OpenGLRenderable + { + Array m_vertices; + + RenderableSemiCircle( std::size_t size ) : m_vertices( size ){ + } + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); + glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) ); + } + void setColour( const Colour4b& colour ){ + for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + ( *i ).colour = colour; + } + } + }; + + RotateFree m_free; + RotateAxis m_axis; + Vector3 m_axis_screen; + RenderableSemiCircle m_circle_x; + RenderableSemiCircle m_circle_y; + RenderableSemiCircle m_circle_z; + RenderableCircle m_circle_screen; + RenderableCircle m_circle_sphere; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + SelectableBool m_selectable_sphere; + Selectable* m_selectable_prev_ptr; + Pivot2World m_pivot; + Matrix4 m_local2world_x; + Matrix4 m_local2world_y; + Matrix4 m_local2world_z; + bool m_circle_x_visible; + bool m_circle_y_visible; + bool m_circle_z_visible; public: -static Shader* m_state_outer; + static Shader* m_state_outer; -RotateManipulator( Rotatable& rotatable, std::size_t segments, float radius ) : - m_free( rotatable ), - m_axis( rotatable ), - m_circle_x( ( segments << 2 ) + 1 ), - m_circle_y( ( segments << 2 ) + 1 ), - m_circle_z( ( segments << 2 ) + 1 ), - m_circle_screen( segments << 3 ), - m_circle_sphere( segments << 3 ), - m_selectable_prev_ptr( 0 ){ - draw_semicircle( segments, radius, m_circle_x.m_vertices.data(), RemapYZX() ); - draw_semicircle( segments, radius, m_circle_y.m_vertices.data(), RemapZXY() ); - draw_semicircle( segments, radius, m_circle_z.m_vertices.data(), RemapXYZ() ); + RotateManipulator( Rotatable& rotatable, std::size_t segments, float radius ) : + m_free( rotatable ), + m_axis( rotatable ), + m_circle_x( ( segments << 2 ) + 1 ), + m_circle_y( ( segments << 2 ) + 1 ), + m_circle_z( ( segments << 2 ) + 1 ), + m_circle_screen( segments << 3 ), + m_circle_sphere( segments << 3 ), + m_selectable_prev_ptr( 0 ){ + draw_semicircle( segments, radius, m_circle_x.m_vertices.data(), RemapYZX() ); + draw_semicircle( segments, radius, m_circle_y.m_vertices.data(), RemapZXY() ); + draw_semicircle( segments, radius, m_circle_z.m_vertices.data(), RemapXYZ() ); - draw_circle( segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ() ); - draw_circle( segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ() ); -} - - -void UpdateColours(){ - m_circle_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); - m_circle_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); - m_circle_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); - m_circle_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); - m_circle_sphere.setColour( colourSelected( g_colour_sphere, false ) ); -} - -void updateCircleTransforms(){ - Vector3 localViewpoint( matrix4_transformed_direction( matrix4_transposed( m_pivot.m_worldSpace ), vector4_to_vector3( m_pivot.m_viewpointSpace.z() ) ) ); - - m_circle_x_visible = !vector3_equal_epsilon( g_vector3_axis_x, localViewpoint, 1e-6f ); - if ( m_circle_x_visible ) { - m_local2world_x = g_matrix4_identity; - vector4_to_vector3( m_local2world_x.y() ) = normalised_safe( - vector3_cross( g_vector3_axis_x, localViewpoint ) - ); - vector4_to_vector3( m_local2world_x.z() ) = normalised_safe( - vector3_cross( vector4_to_vector3( m_local2world_x.x() ), vector4_to_vector3( m_local2world_x.y() ) ) - ); - matrix4_premultiply_by_matrix4( m_local2world_x, m_pivot.m_worldSpace ); + draw_circle( segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ() ); + draw_circle( segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ() ); } - m_circle_y_visible = !vector3_equal_epsilon( g_vector3_axis_y, localViewpoint, 1e-6f ); - if ( m_circle_y_visible ) { - m_local2world_y = g_matrix4_identity; - vector4_to_vector3( m_local2world_y.z() ) = normalised_safe( - vector3_cross( g_vector3_axis_y, localViewpoint ) - ); - vector4_to_vector3( m_local2world_y.x() ) = normalised_safe( - vector3_cross( vector4_to_vector3( m_local2world_y.y() ), vector4_to_vector3( m_local2world_y.z() ) ) - ); - matrix4_premultiply_by_matrix4( m_local2world_y, m_pivot.m_worldSpace ); + + void UpdateColours(){ + m_circle_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); + m_circle_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); + m_circle_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); + m_circle_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); + m_circle_sphere.setColour( colourSelected( g_colour_sphere, false ) ); } - m_circle_z_visible = !vector3_equal_epsilon( g_vector3_axis_z, localViewpoint, 1e-6f ); - if ( m_circle_z_visible ) { - m_local2world_z = g_matrix4_identity; - vector4_to_vector3( m_local2world_z.x() ) = normalised_safe( - vector3_cross( g_vector3_axis_z, localViewpoint ) - ); - vector4_to_vector3( m_local2world_z.y() ) = normalised_safe( - vector3_cross( vector4_to_vector3( m_local2world_z.z() ), vector4_to_vector3( m_local2world_z.x() ) ) - ); - matrix4_premultiply_by_matrix4( m_local2world_z, m_pivot.m_worldSpace ); + void updateCircleTransforms(){ + Vector3 localViewpoint( matrix4_transformed_direction( matrix4_transposed( m_pivot.m_worldSpace ), vector4_to_vector3( m_pivot.m_viewpointSpace.z() ) ) ); + + m_circle_x_visible = !vector3_equal_epsilon( g_vector3_axis_x, localViewpoint, 1e-6f ); + if ( m_circle_x_visible ) { + m_local2world_x = g_matrix4_identity; + vector4_to_vector3( m_local2world_x.y() ) = normalised_safe( + vector3_cross( g_vector3_axis_x, localViewpoint ) + ); + vector4_to_vector3( m_local2world_x.z() ) = normalised_safe( + vector3_cross( vector4_to_vector3( m_local2world_x.x() ), vector4_to_vector3( m_local2world_x.y() ) ) + ); + matrix4_premultiply_by_matrix4( m_local2world_x, m_pivot.m_worldSpace ); + } + + m_circle_y_visible = !vector3_equal_epsilon( g_vector3_axis_y, localViewpoint, 1e-6f ); + if ( m_circle_y_visible ) { + m_local2world_y = g_matrix4_identity; + vector4_to_vector3( m_local2world_y.z() ) = normalised_safe( + vector3_cross( g_vector3_axis_y, localViewpoint ) + ); + vector4_to_vector3( m_local2world_y.x() ) = normalised_safe( + vector3_cross( vector4_to_vector3( m_local2world_y.y() ), vector4_to_vector3( m_local2world_y.z() ) ) + ); + matrix4_premultiply_by_matrix4( m_local2world_y, m_pivot.m_worldSpace ); + } + + m_circle_z_visible = !vector3_equal_epsilon( g_vector3_axis_z, localViewpoint, 1e-6f ); + if ( m_circle_z_visible ) { + m_local2world_z = g_matrix4_identity; + vector4_to_vector3( m_local2world_z.x() ) = normalised_safe( + vector3_cross( g_vector3_axis_z, localViewpoint ) + ); + vector4_to_vector3( m_local2world_z.y() ) = normalised_safe( + vector3_cross( vector4_to_vector3( m_local2world_z.z() ), vector4_to_vector3( m_local2world_z.x() ) ) + ); + matrix4_premultiply_by_matrix4( m_local2world_z, m_pivot.m_worldSpace ); + } } -} -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - updateCircleTransforms(); + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); + updateCircleTransforms(); - // temp hack - UpdateColours(); + // temp hack + UpdateColours(); - renderer.SetState( m_state_outer, Renderer::eWireframeOnly ); - renderer.SetState( m_state_outer, Renderer::eFullMaterials ); + renderer.SetState( m_state_outer, Renderer::eWireframeOnly ); + renderer.SetState( m_state_outer, Renderer::eFullMaterials ); - renderer.addRenderable( m_circle_screen, m_pivot.m_viewpointSpace ); - renderer.addRenderable( m_circle_sphere, m_pivot.m_viewpointSpace ); + renderer.addRenderable( m_circle_screen, m_pivot.m_viewpointSpace ); + renderer.addRenderable( m_circle_sphere, m_pivot.m_viewpointSpace ); - if ( m_circle_x_visible ) { - renderer.addRenderable( m_circle_x, m_local2world_x ); + if ( m_circle_x_visible ) { + renderer.addRenderable( m_circle_x, m_local2world_x ); + } + if ( m_circle_y_visible ) { + renderer.addRenderable( m_circle_y, m_local2world_y ); + } + if ( m_circle_z_visible ) { + renderer.addRenderable( m_circle_z, m_local2world_z ); + } } - if ( m_circle_y_visible ) { - renderer.addRenderable( m_circle_y, m_local2world_y ); - } - if ( m_circle_z_visible ) { - renderer.addRenderable( m_circle_z, m_local2world_z ); - } -} -void testSelect( const View& view, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - updateCircleTransforms(); + void testSelect( const View& view, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + updateCircleTransforms(); - SelectionPool selector; + SelectionPool selector; - { { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_x ) ); + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_x ) ); #if defined( DEBUG_SELECTION ) - g_render_clipped.construct( view.GetViewMatrix() ); + g_render_clipped.construct( view.GetViewMatrix() ); #endif - SelectionIntersection best; - LineStrip_BestPoint( local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best ); - selector.addSelectable( best, &m_selectable_x ); - } + SelectionIntersection best; + LineStrip_BestPoint( local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best ); + selector.addSelectable( best, &m_selectable_x ); + } - { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_y ) ); + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_y ) ); #if defined( DEBUG_SELECTION ) - g_render_clipped.construct( view.GetViewMatrix() ); + g_render_clipped.construct( view.GetViewMatrix() ); #endif - SelectionIntersection best; - LineStrip_BestPoint( local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best ); - selector.addSelectable( best, &m_selectable_y ); - } + SelectionIntersection best; + LineStrip_BestPoint( local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best ); + selector.addSelectable( best, &m_selectable_y ); + } - { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_z ) ); + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_z ) ); #if defined( DEBUG_SELECTION ) - g_render_clipped.construct( view.GetViewMatrix() ); + g_render_clipped.construct( view.GetViewMatrix() ); #endif - SelectionIntersection best; - LineStrip_BestPoint( local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best ); - selector.addSelectable( best, &m_selectable_z ); + SelectionIntersection best; + LineStrip_BestPoint( local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best ); + selector.addSelectable( best, &m_selectable_z ); + } } - } - - { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); { - SelectionIntersection best; - LineLoop_BestPoint( local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best ); - selector.addSelectable( best, &m_selectable_screen ); - } + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); + + { + SelectionIntersection best; + LineLoop_BestPoint( local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best ); + selector.addSelectable( best, &m_selectable_screen ); + } // { // SelectionIntersection best; // Circle_BestPoint( local2view, eClipCullCW, m_circle_sphere.m_vertices.data(), m_circle_sphere.m_vertices.size(), best ); // selector.addSelectable( best, &m_selectable_sphere ); // } - } + } - m_axis_screen = m_pivot.m_axis_screen; + m_axis_screen = m_pivot.m_axis_screen; - if ( !selector.failed() ) { - ( *selector.begin() ).second->setSelected( true ); - if( m_selectable_prev_ptr != ( *selector.begin() ).second ){ - m_selectable_prev_ptr = ( *selector.begin() ).second; - SceneChangeNotify(); + if ( !selector.failed() ) { + ( *selector.begin() ).second->setSelected( true ); + if( m_selectable_prev_ptr != ( *selector.begin() ).second ){ + m_selectable_prev_ptr = ( *selector.begin() ).second; + SceneChangeNotify(); + } + } + else{ + m_selectable_sphere.setSelected( true ); + if( m_selectable_prev_ptr != &m_selectable_sphere ){ + m_selectable_prev_ptr = &m_selectable_sphere; + SceneChangeNotify(); + } } } - else{ - m_selectable_sphere.setSelected( true ); - if( m_selectable_prev_ptr != &m_selectable_sphere ){ - m_selectable_prev_ptr = &m_selectable_sphere; - SceneChangeNotify(); + + Manipulatable* GetManipulatable(){ + if ( m_selectable_x.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_x ); + return &m_axis; + } + else if ( m_selectable_y.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_y ); + return &m_axis; + } + else if ( m_selectable_z.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_z ); + return &m_axis; + } + else if ( m_selectable_screen.isSelected() ) { + m_axis.SetAxis( m_axis_screen ); + return &m_axis; + } + else{ + return &m_free; } } -} -Manipulatable* GetManipulatable(){ - if ( m_selectable_x.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_x ); - return &m_axis; + void setSelected( bool select ){ + m_selectable_x.setSelected( select ); + m_selectable_y.setSelected( select ); + m_selectable_z.setSelected( select ); + m_selectable_screen.setSelected( select ); + m_selectable_sphere.setSelected( select ); } - else if ( m_selectable_y.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_y ); - return &m_axis; + bool isSelected() const { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected() + | m_selectable_sphere.isSelected(); } - else if ( m_selectable_z.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_z ); - return &m_axis; - } - else if ( m_selectable_screen.isSelected() ) { - m_axis.SetAxis( m_axis_screen ); - return &m_axis; - } - else{ - return &m_free; - } -} - -void setSelected( bool select ){ - m_selectable_x.setSelected( select ); - m_selectable_y.setSelected( select ); - m_selectable_z.setSelected( select ); - m_selectable_screen.setSelected( select ); - m_selectable_sphere.setSelected( select ); -} -bool isSelected() const { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected() - | m_selectable_sphere.isSelected(); -} }; Shader* RotateManipulator::m_state_outer; @@ -1878,45 +1886,45 @@ template class TripleRemapXYZ { public: -static float& x( Triple& triple ){ - return triple.x(); -} -static float& y( Triple& triple ){ - return triple.y(); -} -static float& z( Triple& triple ){ - return triple.z(); -} + static float& x( Triple& triple ){ + return triple.x(); + } + static float& y( Triple& triple ){ + return triple.y(); + } + static float& z( Triple& triple ){ + return triple.z(); + } }; template class TripleRemapYZX { public: -static float& x( Triple& triple ){ - return triple.y(); -} -static float& y( Triple& triple ){ - return triple.z(); -} -static float& z( Triple& triple ){ - return triple.x(); -} + static float& x( Triple& triple ){ + return triple.y(); + } + static float& y( Triple& triple ){ + return triple.z(); + } + static float& z( Triple& triple ){ + return triple.x(); + } }; template class TripleRemapZXY { public: -static float& x( Triple& triple ){ - return triple.z(); -} -static float& y( Triple& triple ){ - return triple.x(); -} -static float& z( Triple& triple ){ - return triple.y(); -} + static float& x( Triple& triple ){ + return triple.z(); + } + static float& y( Triple& triple ){ + return triple.x(); + } + static float& z( Triple& triple ){ + return triple.y(); + } }; class ManipulatorSelectionChangeable @@ -1944,239 +1952,239 @@ public: class TranslateManipulator : public Manipulator, public ManipulatorSelectionChangeable { -struct RenderableArrowLine : public OpenGLRenderable -{ - PointVertex m_line[2]; - - RenderableArrowLine(){ - } - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex ); - glDrawArrays( GL_LINES, 0, 2 ); - } - void setColour( const Colour4b& colour ){ - m_line[0].colour = colour; - m_line[1].colour = colour; - } -}; -struct RenderableArrowHead : public OpenGLRenderable -{ - Array m_vertices; - - RenderableArrowHead( std::size_t size ) - : m_vertices( size ){ - } - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( FlatShadedVertex ), &m_vertices.data()->colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->vertex ); - glNormalPointer( GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->normal ); - glDrawArrays( GL_TRIANGLES, 0, GLsizei( m_vertices.size() ) ); - } - void setColour( const Colour4b& colour ){ - for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) - { - ( *i ).colour = colour; - } - } -}; -struct RenderableQuad : public OpenGLRenderable -{ - PointVertex m_quad[4]; - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex ); - glDrawArrays( GL_LINE_LOOP, 0, 4 ); - } - void setColour( const Colour4b& colour ){ - m_quad[0].colour = colour; - m_quad[1].colour = colour; - m_quad[2].colour = colour; - m_quad[3].colour = colour; - } -}; - -TranslateFree m_free; -TranslateAxis m_axis; -RenderableArrowLine m_arrow_x; -RenderableArrowLine m_arrow_y; -RenderableArrowLine m_arrow_z; -RenderableArrowHead m_arrow_head_x; -RenderableArrowHead m_arrow_head_y; -RenderableArrowHead m_arrow_head_z; -RenderableQuad m_quad_screen; -SelectableBool m_selectable_x; -SelectableBool m_selectable_y; -SelectableBool m_selectable_z; -SelectableBool m_selectable_screen; -Pivot2World m_pivot; -public: -static Shader* m_state_wire; -static Shader* m_state_fill; - -TranslateManipulator( Translatable& translatable, std::size_t segments, float length ) : - m_free( translatable ), - m_axis( translatable ), - m_arrow_head_x( 3 * 2 * ( segments << 3 ) ), - m_arrow_head_y( 3 * 2 * ( segments << 3 ) ), - m_arrow_head_z( 3 * 2 * ( segments << 3 ) ){ - draw_arrowline( length, m_arrow_x.m_line, 0 ); - draw_arrowhead( segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ(), TripleRemapXYZ() ); - draw_arrowline( length, m_arrow_y.m_line, 1 ); - draw_arrowhead( segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX(), TripleRemapYZX() ); - draw_arrowline( length, m_arrow_z.m_line, 2 ); - draw_arrowhead( segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY(), TripleRemapZXY() ); - - draw_quad( 16, m_quad_screen.m_quad ); -} - -void UpdateColours(){ - m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); - m_arrow_head_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); - m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); - m_arrow_head_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); - m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); - m_arrow_head_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); - m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); -} - -bool manipulator_show_axis( const Pivot2World& pivot, const Vector3& axis ){ - return fabs( vector3_dot( pivot.m_axis_screen, axis ) ) < 0.95; -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - - // temp hack - UpdateColours(); - - Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) ); - bool show_x = manipulator_show_axis( m_pivot, x ); - - Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) ); - bool show_y = manipulator_show_axis( m_pivot, y ); - - Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) ); - bool show_z = manipulator_show_axis( m_pivot, z ); - - renderer.SetState( m_state_wire, Renderer::eWireframeOnly ); - renderer.SetState( m_state_wire, Renderer::eFullMaterials ); - - if ( show_x ) { - renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace ); - } - if ( show_y ) { - renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace ); - } - if ( show_z ) { - renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace ); - } - - renderer.addRenderable( m_quad_screen, m_pivot.m_viewplaneSpace ); - - renderer.SetState( m_state_fill, Renderer::eWireframeOnly ); - renderer.SetState( m_state_fill, Renderer::eFullMaterials ); - - if ( show_x ) { - renderer.addRenderable( m_arrow_head_x, m_pivot.m_worldSpace ); - } - if ( show_y ) { - renderer.addRenderable( m_arrow_head_y, m_pivot.m_worldSpace ); - } - if ( show_z ) { - renderer.addRenderable( m_arrow_head_z, m_pivot.m_worldSpace ); - } -} -void testSelect( const View& view, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - - SelectionPool selector; - - Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) ); - bool show_x = manipulator_show_axis( m_pivot, x ); - - Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) ); - bool show_y = manipulator_show_axis( m_pivot, y ); - - Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) ); - bool show_z = manipulator_show_axis( m_pivot, z ); - + struct RenderableArrowLine : public OpenGLRenderable { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); + PointVertex m_line[2]; - { - SelectionIntersection best; - Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best ); - if ( best.valid() ) { - best = SelectionIntersection( 0, 0 ); - selector.addSelectable( best, &m_selectable_screen ); + RenderableArrowLine(){ + } + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex ); + glDrawArrays( GL_LINES, 0, 2 ); + } + void setColour( const Colour4b& colour ){ + m_line[0].colour = colour; + m_line[1].colour = colour; + } + }; + struct RenderableArrowHead : public OpenGLRenderable + { + Array m_vertices; + + RenderableArrowHead( std::size_t size ) + : m_vertices( size ){ + } + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( FlatShadedVertex ), &m_vertices.data()->colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->vertex ); + glNormalPointer( GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->normal ); + glDrawArrays( GL_TRIANGLES, 0, GLsizei( m_vertices.size() ) ); + } + void setColour( const Colour4b& colour ){ + for ( Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i ) + { + ( *i ).colour = colour; } } + }; + struct RenderableQuad : public OpenGLRenderable + { + PointVertex m_quad[4]; + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex ); + glDrawArrays( GL_LINE_LOOP, 0, 4 ); + } + void setColour( const Colour4b& colour ){ + m_quad[0].colour = colour; + m_quad[1].colour = colour; + m_quad[2].colour = colour; + m_quad[3].colour = colour; + } + }; + + TranslateFree m_free; + TranslateAxis m_axis; + RenderableArrowLine m_arrow_x; + RenderableArrowLine m_arrow_y; + RenderableArrowLine m_arrow_z; + RenderableArrowHead m_arrow_head_x; + RenderableArrowHead m_arrow_head_y; + RenderableArrowHead m_arrow_head_z; + RenderableQuad m_quad_screen; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + Pivot2World m_pivot; +public: + static Shader* m_state_wire; + static Shader* m_state_fill; + + TranslateManipulator( Translatable& translatable, std::size_t segments, float length ) : + m_free( translatable ), + m_axis( translatable ), + m_arrow_head_x( 3 * 2 * ( segments << 3 ) ), + m_arrow_head_y( 3 * 2 * ( segments << 3 ) ), + m_arrow_head_z( 3 * 2 * ( segments << 3 ) ){ + draw_arrowline( length, m_arrow_x.m_line, 0 ); + draw_arrowhead( segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ(), TripleRemapXYZ() ); + draw_arrowline( length, m_arrow_y.m_line, 1 ); + draw_arrowhead( segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX(), TripleRemapYZX() ); + draw_arrowline( length, m_arrow_z.m_line, 2 ); + draw_arrowhead( segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY(), TripleRemapZXY() ); + + draw_quad( 16, m_quad_screen.m_quad ); } - { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) ); + void UpdateColours(){ + m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); + m_arrow_head_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); + m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); + m_arrow_head_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); + m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); + m_arrow_head_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); + m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); + } -#if defined( DEBUG_SELECTION ) - g_render_clipped.construct( view.GetViewMatrix() ); -#endif + bool manipulator_show_axis( const Pivot2World& pivot, const Vector3& axis ){ + return fabs( vector3_dot( pivot.m_axis_screen, axis ) ) < 0.95; + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); + + // temp hack + UpdateColours(); + + Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) ); + bool show_x = manipulator_show_axis( m_pivot, x ); + + Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) ); + bool show_y = manipulator_show_axis( m_pivot, y ); + + Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) ); + bool show_z = manipulator_show_axis( m_pivot, z ); + + renderer.SetState( m_state_wire, Renderer::eWireframeOnly ); + renderer.SetState( m_state_wire, Renderer::eFullMaterials ); if ( show_x ) { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_x.m_line, best ); - Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best ); - selector.addSelectable( best, &m_selectable_x ); + renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace ); } - if ( show_y ) { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_y.m_line, best ); - Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best ); - selector.addSelectable( best, &m_selectable_y ); + renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace ); } - if ( show_z ) { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_z.m_line, best ); - Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best ); - selector.addSelectable( best, &m_selectable_z ); + renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace ); + } + + renderer.addRenderable( m_quad_screen, m_pivot.m_viewplaneSpace ); + + renderer.SetState( m_state_fill, Renderer::eWireframeOnly ); + renderer.SetState( m_state_fill, Renderer::eFullMaterials ); + + if ( show_x ) { + renderer.addRenderable( m_arrow_head_x, m_pivot.m_worldSpace ); + } + if ( show_y ) { + renderer.addRenderable( m_arrow_head_y, m_pivot.m_worldSpace ); + } + if ( show_z ) { + renderer.addRenderable( m_arrow_head_z, m_pivot.m_worldSpace ); + } + } + void testSelect( const View& view, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + + SelectionPool selector; + + Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) ); + bool show_x = manipulator_show_axis( m_pivot, x ); + + Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) ); + bool show_y = manipulator_show_axis( m_pivot, y ); + + Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) ); + bool show_z = manipulator_show_axis( m_pivot, z ); + + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); + + { + SelectionIntersection best; + Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best ); + if ( best.valid() ) { + best = SelectionIntersection( 0, 0 ); + selector.addSelectable( best, &m_selectable_screen ); + } + } + } + + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) ); + +#if defined( DEBUG_SELECTION ) + g_render_clipped.construct( view.GetViewMatrix() ); +#endif + + if ( show_x ) { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_x.m_line, best ); + Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best ); + selector.addSelectable( best, &m_selectable_x ); + } + + if ( show_y ) { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_y.m_line, best ); + Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best ); + selector.addSelectable( best, &m_selectable_y ); + } + + if ( show_z ) { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_z.m_line, best ); + Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best ); + selector.addSelectable( best, &m_selectable_z ); + } + } + + selectionChange( selector ); + } + + Manipulatable* GetManipulatable(){ + if ( m_selectable_x.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_x ); + return &m_axis; + } + else if ( m_selectable_y.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_y ); + return &m_axis; + } + else if ( m_selectable_z.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_z ); + return &m_axis; + } + else + { + return &m_free; } } - selectionChange( selector ); -} - -Manipulatable* GetManipulatable(){ - if ( m_selectable_x.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_x ); - return &m_axis; + void setSelected( bool select ){ + m_selectable_x.setSelected( select ); + m_selectable_y.setSelected( select ); + m_selectable_z.setSelected( select ); + m_selectable_screen.setSelected( select ); } - else if ( m_selectable_y.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_y ); - return &m_axis; + bool isSelected() const { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected(); } - else if ( m_selectable_z.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_z ); - return &m_axis; - } - else - { - return &m_free; - } -} - -void setSelected( bool select ){ - m_selectable_x.setSelected( select ); - m_selectable_y.setSelected( select ); - m_selectable_z.setSelected( select ); - m_selectable_screen.setSelected( select ); -} -bool isSelected() const { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected(); -} }; Shader* TranslateManipulator::m_state_wire; @@ -2184,152 +2192,152 @@ Shader* TranslateManipulator::m_state_fill; class ScaleManipulator : public Manipulator, public ManipulatorSelectionChangeable { -struct RenderableArrow : public OpenGLRenderable -{ - PointVertex m_line[2]; - - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex ); - glDrawArrays( GL_LINES, 0, 2 ); - } - void setColour( const Colour4b& colour ){ - m_line[0].colour = colour; - m_line[1].colour = colour; - } -}; -struct RenderableQuad : public OpenGLRenderable -{ - PointVertex m_quad[4]; - void render( RenderStateFlags state ) const { - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex ); - glDrawArrays( GL_QUADS, 0, 4 ); - } - void setColour( const Colour4b& colour ){ - m_quad[0].colour = colour; - m_quad[1].colour = colour; - m_quad[2].colour = colour; - m_quad[3].colour = colour; - } -}; - -ScaleFree m_free; -ScaleAxis m_axis; -RenderableArrow m_arrow_x; -RenderableArrow m_arrow_y; -RenderableArrow m_arrow_z; -RenderableQuad m_quad_screen; -SelectableBool m_selectable_x; -SelectableBool m_selectable_y; -SelectableBool m_selectable_z; -SelectableBool m_selectable_screen; -Pivot2World m_pivot; -public: -ScaleManipulator( Scalable& scalable, std::size_t segments, float length ) : - m_free( scalable ), - m_axis( scalable ){ - draw_arrowline( length, m_arrow_x.m_line, 0 ); - draw_arrowline( length, m_arrow_y.m_line, 1 ); - draw_arrowline( length, m_arrow_z.m_line, 2 ); - - draw_quad( 16, m_quad_screen.m_quad ); -} - -void UpdateColours(){ - m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); - m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); - m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); - m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - - // temp hack - UpdateColours(); - - renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace ); - renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace ); - renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace ); - - renderer.addRenderable( m_quad_screen, m_pivot.m_viewpointSpace ); -} -void testSelect( const View& view, const Matrix4& pivot2world ){ - m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - - SelectionPool selector; - + struct RenderableArrow : public OpenGLRenderable { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) ); + PointVertex m_line[2]; + + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex ); + glDrawArrays( GL_LINES, 0, 2 ); + } + void setColour( const Colour4b& colour ){ + m_line[0].colour = colour; + m_line[1].colour = colour; + } + }; + struct RenderableQuad : public OpenGLRenderable + { + PointVertex m_quad[4]; + void render( RenderStateFlags state ) const { + glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour ); + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex ); + glDrawArrays( GL_QUADS, 0, 4 ); + } + void setColour( const Colour4b& colour ){ + m_quad[0].colour = colour; + m_quad[1].colour = colour; + m_quad[2].colour = colour; + m_quad[3].colour = colour; + } + }; + + ScaleFree m_free; + ScaleAxis m_axis; + RenderableArrow m_arrow_x; + RenderableArrow m_arrow_y; + RenderableArrow m_arrow_z; + RenderableQuad m_quad_screen; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + Pivot2World m_pivot; +public: + ScaleManipulator( Scalable& scalable, std::size_t segments, float length ) : + m_free( scalable ), + m_axis( scalable ){ + draw_arrowline( length, m_arrow_x.m_line, 0 ); + draw_arrowline( length, m_arrow_y.m_line, 1 ); + draw_arrowline( length, m_arrow_z.m_line, 2 ); + + draw_quad( 16, m_quad_screen.m_quad ); + } + + void UpdateColours(){ + m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) ); + m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) ); + m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) ); + m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) ); + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); + + // temp hack + UpdateColours(); + + renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace ); + renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace ); + renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace ); + + renderer.addRenderable( m_quad_screen, m_pivot.m_viewpointSpace ); + } + void testSelect( const View& view, const Matrix4& pivot2world ){ + m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + + SelectionPool selector; + + { + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) ); #if defined( DEBUG_SELECTION ) - g_render_clipped.construct( view.GetViewMatrix() ); + g_render_clipped.construct( view.GetViewMatrix() ); #endif - { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_x.m_line, best ); - selector.addSelectable( best, &m_selectable_x ); + { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_x.m_line, best ); + selector.addSelectable( best, &m_selectable_x ); + } + + { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_y.m_line, best ); + selector.addSelectable( best, &m_selectable_y ); + } + + { + SelectionIntersection best; + Line_BestPoint( local2view, m_arrow_z.m_line, best ); + selector.addSelectable( best, &m_selectable_z ); + } } { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_y.m_line, best ); - selector.addSelectable( best, &m_selectable_y ); + const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); + + { + SelectionIntersection best; + Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best ); + selector.addSelectable( best, &m_selectable_screen ); + } } - { - SelectionIntersection best; - Line_BestPoint( local2view, m_arrow_z.m_line, best ); - selector.addSelectable( best, &m_selectable_z ); + selectionChange( selector ); + } + + Manipulatable* GetManipulatable(){ + if ( m_selectable_x.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_x ); + return &m_axis; + } + else if ( m_selectable_y.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_y ); + return &m_axis; + } + else if ( m_selectable_z.isSelected() ) { + m_axis.SetAxis( g_vector3_axis_z ); + return &m_axis; + } + else{ + m_free.SetAxes( g_vector3_identity, g_vector3_identity ); + return &m_free; } } - { - const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) ); - - { - SelectionIntersection best; - Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best ); - selector.addSelectable( best, &m_selectable_screen ); - } + void setSelected( bool select ){ + m_selectable_x.setSelected( select ); + m_selectable_y.setSelected( select ); + m_selectable_z.setSelected( select ); + m_selectable_screen.setSelected( select ); } - - selectionChange( selector ); -} - -Manipulatable* GetManipulatable(){ - if ( m_selectable_x.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_x ); - return &m_axis; + bool isSelected() const { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected(); } - else if ( m_selectable_y.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_y ); - return &m_axis; - } - else if ( m_selectable_z.isSelected() ) { - m_axis.SetAxis( g_vector3_axis_z ); - return &m_axis; - } - else{ - m_free.SetAxes( g_vector3_identity, g_vector3_identity ); - return &m_free; - } -} - -void setSelected( bool select ){ - m_selectable_x.setSelected( select ); - m_selectable_y.setSelected( select ); - m_selectable_z.setSelected( select ); - m_selectable_screen.setSelected( select ); -} -bool isSelected() const { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected(); -} }; @@ -2676,9 +2684,9 @@ public: const int index = i * 8 + j * 4; if( vector3_dot( normal, closest_point - corners[indices[index]] ) > 0 - && vector3_dot( normal, closest_point - corners[indices[index + 1]] ) > 0 - && vector3_dot( normal, closest_point - corners[indices[index + 2]] ) > 0 - && vector3_dot( normal, closest_point - corners[indices[index + 3]] ) > 0 ) + && vector3_dot( normal, closest_point - corners[indices[index + 1]] ) > 0 + && vector3_dot( normal, closest_point - corners[indices[index + 2]] ) > 0 + && vector3_dot( normal, closest_point - corners[indices[index + 3]] ) > 0 ) { const double dot = fabs( vector3_dot( normal, viewdir ) ); const double diff = bestDot - dot; @@ -2772,7 +2780,7 @@ public: } for ( int i = 0; i < 3; ++i ) for ( int j = 0; j < 2; ++j ) - m_selectables_scale[i][j].setSelected( select ); + m_selectables_scale[i][j].setSelected( select ); } bool isSelected() const { bool selected = false; @@ -2784,7 +2792,7 @@ public: } for ( int i = 0; i < 3; ++i ) for ( int j = 0; j < 2; ++j ) - selected |= m_selectables_scale[i][j].isSelected(); + selected |= m_selectables_scale[i][j].isSelected(); return selected | m_selectable_translateFree.isSelected(); } }; @@ -2801,41 +2809,41 @@ inline PlaneSelectable* Instance_getPlaneSelectable( scene::Instance& instance ) class PlaneSelectableSelectPlanes : public scene::Graph::Walker { -Selector& m_selector; -SelectionTest& m_test; -PlaneCallback m_selectedPlaneCallback; + Selector& m_selector; + SelectionTest& m_test; + PlaneCallback m_selectedPlaneCallback; public: -PlaneSelectableSelectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ) - : m_selector( selector ), m_test( test ), m_selectedPlaneCallback( selectedPlaneCallback ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() && Instance_isSelected( instance ) ) { - PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); - if ( planeSelectable != 0 ) { - planeSelectable->selectPlanes( m_selector, m_test, m_selectedPlaneCallback ); - } + PlaneSelectableSelectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ) + : m_selector( selector ), m_test( test ), m_selectedPlaneCallback( selectedPlaneCallback ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() && Instance_isSelected( instance ) ) { + PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); + if ( planeSelectable != 0 ) { + planeSelectable->selectPlanes( m_selector, m_test, m_selectedPlaneCallback ); + } + } + return true; } - return true; -} }; class PlaneSelectableSelectReversedPlanes : public scene::Graph::Walker { -Selector& m_selector; -const SelectedPlanes& m_selectedPlanes; + Selector& m_selector; + const SelectedPlanes& m_selectedPlanes; public: -PlaneSelectableSelectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ) - : m_selector( selector ), m_selectedPlanes( selectedPlanes ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( path.top().get().visible() && Instance_isSelected( instance ) ) { - PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); - if ( planeSelectable != 0 ) { - planeSelectable->selectReversedPlanes( m_selector, m_selectedPlanes ); - } + PlaneSelectableSelectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ) + : m_selector( selector ), m_selectedPlanes( selectedPlanes ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( path.top().get().visible() && Instance_isSelected( instance ) ) { + PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); + if ( planeSelectable != 0 ) { + planeSelectable->selectReversedPlanes( m_selector, m_selectedPlanes ); + } + } + return true; } - return true; -} }; void Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ @@ -2850,37 +2858,37 @@ void Scene_forEachPlaneSelectable_selectReversedPlanes( scene::Graph& graph, Sel class PlaneLess { public: -bool operator()( const Plane3& plane, const Plane3& other ) const { - if ( plane.a < other.a ) { - return true; - } - if ( other.a < plane.a ) { + bool operator()( const Plane3& plane, const Plane3& other ) const { + if ( plane.a < other.a ) { + return true; + } + if ( other.a < plane.a ) { + return false; + } + + if ( plane.b < other.b ) { + return true; + } + if ( other.b < plane.b ) { + return false; + } + + if ( plane.c < other.c ) { + return true; + } + if ( other.c < plane.c ) { + return false; + } + + if ( plane.d < other.d ) { + return true; + } + if ( other.d < plane.d ) { + return false; + } + return false; } - - if ( plane.b < other.b ) { - return true; - } - if ( other.b < plane.b ) { - return false; - } - - if ( plane.c < other.c ) { - return true; - } - if ( other.c < plane.c ) { - return false; - } - - if ( plane.d < other.d ) { - return true; - } - if ( other.d < plane.d ) { - return false; - } - - return false; -} }; typedef std::set PlaneSet; @@ -2896,19 +2904,19 @@ inline bool PlaneSet_contains( const PlaneSet& self, const Plane3& plane ){ class SelectedPlaneSet : public SelectedPlanes { -PlaneSet m_selectedPlanes; + PlaneSet m_selectedPlanes; public: -bool empty() const { - return m_selectedPlanes.empty(); -} + bool empty() const { + return m_selectedPlanes.empty(); + } -void insert( const Plane3& plane ){ - PlaneSet_insert( m_selectedPlanes, plane ); -} -bool contains( const Plane3& plane ) const { - return PlaneSet_contains( m_selectedPlanes, plane ); -} -typedef MemberCaller1 InsertCaller; + void insert( const Plane3& plane ){ + PlaneSet_insert( m_selectedPlanes, plane ); + } + bool contains( const Plane3& plane ) const { + return PlaneSet_contains( m_selectedPlanes, plane ); + } + typedef MemberCaller1 InsertCaller; }; @@ -2927,17 +2935,17 @@ bool Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& s template class PlaneselectableVisibleSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -PlaneselectableVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); - if ( planeSelectable != 0 - && instance.path().top().get().visible() ) { - m_functor( *planeSelectable ); + PlaneselectableVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance ); + if ( planeSelectable != 0 + && instance.path().top().get().visible() ) { + m_functor( *planeSelectable ); + } } -} }; template @@ -3077,272 +3085,272 @@ void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode com class ResizeTranslatable : public Translatable { -void translate( const Vector3& translation ){ - Scene_Translate_Component_Selected( GlobalSceneGraph(), translation ); -} + void translate( const Vector3& translation ){ + Scene_Translate_Component_Selected( GlobalSceneGraph(), translation ); + } }; class SelectionVolume : public SelectionTest { -Matrix4 m_local2view; -const View& m_view; -clipcull_t m_cull; + Matrix4 m_local2view; + const View& m_view; + clipcull_t m_cull; #if 0 -Vector3 m_near; -Vector3 m_far; + Vector3 m_near; + Vector3 m_far; #endif -Matrix4 m_screen2world; + Matrix4 m_screen2world; public: -SelectionVolume( const View& view ) - : m_view( view ){ -} - -const VolumeTest& getVolume() const { - return m_view; -} -#if 0 -const Vector3& getNear() const { - return m_near; -} -const Vector3& getFar() const { - return m_far; -} -#endif -const Matrix4& getScreen2world() const { - return m_screen2world; -} - -void BeginMesh( const Matrix4& localToWorld, bool twoSided ){ - m_local2view = matrix4_multiplied_by_matrix4( m_view.GetViewMatrix(), localToWorld ); - - // Cull back-facing polygons based on winding being clockwise or counter-clockwise. - // Don't cull if the view is wireframe and the polygons are two-sided. - m_cull = twoSided && !m_view.fill() ? eClipCullNone : ( matrix4_handedness( localToWorld ) == MATRIX4_RIGHTHANDED ) ? eClipCullCW : eClipCullCCW; - - { - m_screen2world = matrix4_full_inverse( m_local2view ); -#if 0 - m_near = vector4_projected( - matrix4_transformed_vector4( - m_screen2world, - Vector4( 0, 0, -1, 1 ) - ) - ); - - m_far = vector4_projected( - matrix4_transformed_vector4( - m_screen2world, - Vector4( 0, 0, 1, 1 ) - ) - ); -#endif + SelectionVolume( const View& view ) + : m_view( view ){ } + const VolumeTest& getVolume() const { + return m_view; + } +#if 0 + const Vector3& getNear() const { + return m_near; + } + const Vector3& getFar() const { + return m_far; + } +#endif + const Matrix4& getScreen2world() const { + return m_screen2world; + } + + void BeginMesh( const Matrix4& localToWorld, bool twoSided ){ + m_local2view = matrix4_multiplied_by_matrix4( m_view.GetViewMatrix(), localToWorld ); + + // Cull back-facing polygons based on winding being clockwise or counter-clockwise. + // Don't cull if the view is wireframe and the polygons are two-sided. + m_cull = twoSided && !m_view.fill() ? eClipCullNone : ( matrix4_handedness( localToWorld ) == MATRIX4_RIGHTHANDED ) ? eClipCullCW : eClipCullCCW; + + { + m_screen2world = matrix4_full_inverse( m_local2view ); +#if 0 + m_near = vector4_projected( + matrix4_transformed_vector4( + m_screen2world, + Vector4( 0, 0, -1, 1 ) + ) + ); + + m_far = vector4_projected( + matrix4_transformed_vector4( + m_screen2world, + Vector4( 0, 0, 1, 1 ) + ) + ); +#endif + } + #if defined( DEBUG_SELECTION ) - g_render_clipped.construct( m_view.GetViewMatrix() ); + g_render_clipped.construct( m_view.GetViewMatrix() ); #endif -} -void TestPoint( const Vector3& point, SelectionIntersection& best ){ - Vector4 clipped; - if ( matrix4_clip_point( m_local2view, point, clipped ) == c_CLIP_PASS ) { - best = select_point_from_clipped( clipped ); } -} -void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best, const DoubleVector3 planepoints[3] ){ - DoubleVector3 pts[3]; - pts[0] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[0], 1 ) ) ); - pts[1] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[1], 1 ) ) ); - pts[2] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[2], 1 ) ) ); - const Plane3 planeTransformed( plane3_for_points( pts ) ); + void TestPoint( const Vector3& point, SelectionIntersection& best ){ + Vector4 clipped; + if ( matrix4_clip_point( m_local2view, point, clipped ) == c_CLIP_PASS ) { + best = select_point_from_clipped( clipped ); + } + } + void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best, const DoubleVector3 planepoints[3] ){ + DoubleVector3 pts[3]; + pts[0] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[0], 1 ) ) ); + pts[1] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[1], 1 ) ) ); + pts[2] = vector4_projected( matrix4_transformed_vector4( m_local2view, BasicVector4( planepoints[2], 1 ) ) ); + const Plane3 planeTransformed( plane3_for_points( pts ) ); - Vector4 clipped[9]; - for ( std::size_t i = 0; i + 2 < count; ++i ) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[0] ), - reinterpret_cast( vertices[i + 1] ), - reinterpret_cast( vertices[i + 2] ), - clipped - ), - clipped, - best, - m_cull, - &planeTransformed + Vector4 clipped[9]; + for ( std::size_t i = 0; i + 2 < count; ++i ) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[0] ), + reinterpret_cast( vertices[i + 1] ), + reinterpret_cast( vertices[i + 2] ), + clipped + ), + clipped, + best, + m_cull, + &planeTransformed ); + } } -} -void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ - if ( count == 0 ) { - return; - } - Vector4 clipped[9]; - for ( VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + ( count - 1 ); i != end; prev = i, ++i ) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast( ( *prev ) ), - reinterpret_cast( ( *i ) ), - clipped - ), - clipped, - best, - m_cull + void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ + if ( count == 0 ) { + return; + } + Vector4 clipped[9]; + for ( VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + ( count - 1 ); i != end; prev = i, ++i ) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast( ( *prev ) ), + reinterpret_cast( ( *i ) ), + clipped + ), + clipped, + best, + m_cull ); + } } -} -void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ - if ( count == 0 ) { - return; - } - Vector4 clipped[9]; - for ( VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next ) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast( ( *i ) ), - reinterpret_cast( ( *next ) ), - clipped - ), - clipped, - best, - m_cull + void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ + if ( count == 0 ) { + return; + } + Vector4 clipped[9]; + for ( VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next ) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast( ( *i ) ), + reinterpret_cast( ( *next ) ), + clipped + ), + clipped, + best, + m_cull ); + } } -} -void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ - if ( count == 0 ) { - return; + void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){ + if ( count == 0 ) { + return; + } + Vector4 clipped[9]; + for ( VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2 ) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast( ( *i ) ), + reinterpret_cast( ( *( i + 1 ) ) ), + clipped + ), + clipped, + best, + m_cull + ); + } } - Vector4 clipped[9]; - for ( VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2 ) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast( ( *i ) ), - reinterpret_cast( ( *( i + 1 ) ) ), - clipped - ), - clipped, - best, - m_cull + void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ + Vector4 clipped[9]; + for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 3 ) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[*i] ), + reinterpret_cast( vertices[*( i + 1 )] ), + reinterpret_cast( vertices[*( i + 2 )] ), + clipped + ), + clipped, + best, + m_cull ); + } } -} -void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ - Vector4 clipped[9]; - for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 3 ) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[*i] ), - reinterpret_cast( vertices[*( i + 1 )] ), - reinterpret_cast( vertices[*( i + 2 )] ), - clipped - ), - clipped, - best, - m_cull + void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ + Vector4 clipped[9]; + for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 4 ) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[*i] ), + reinterpret_cast( vertices[*( i + 1 )] ), + reinterpret_cast( vertices[*( i + 3 )] ), + clipped + ), + clipped, + best, + m_cull ); + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[*( i + 1 )] ), + reinterpret_cast( vertices[*( i + 2 )] ), + reinterpret_cast( vertices[*( i + 3 )] ), + clipped + ), + clipped, + best, + m_cull + ); + } } -} -void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ - Vector4 clipped[9]; - for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 4 ) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[*i] ), - reinterpret_cast( vertices[*( i + 1 )] ), - reinterpret_cast( vertices[*( i + 3 )] ), - clipped - ), - clipped, - best, - m_cull + void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ + Vector4 clipped[9]; + for ( IndexPointer::iterator i( indices.begin() ); i + 2 != indices.end(); i += 2 ) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[*i] ), + reinterpret_cast( vertices[*( i + 1 )] ), + reinterpret_cast( vertices[*( i + 2 )] ), + clipped + ), + clipped, + best, + m_cull ); - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[*( i + 1 )] ), - reinterpret_cast( vertices[*( i + 2 )] ), - reinterpret_cast( vertices[*( i + 3 )] ), - clipped - ), - clipped, - best, - m_cull + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast( vertices[*( i + 2 )] ), + reinterpret_cast( vertices[*( i + 1 )] ), + reinterpret_cast( vertices[*( i + 3 )] ), + clipped + ), + clipped, + best, + m_cull ); + } } -} -void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){ - Vector4 clipped[9]; - for ( IndexPointer::iterator i( indices.begin() ); i + 2 != indices.end(); i += 2 ) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[*i] ), - reinterpret_cast( vertices[*( i + 1 )] ), - reinterpret_cast( vertices[*( i + 2 )] ), - clipped - ), - clipped, - best, - m_cull - ); - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast( vertices[*( i + 2 )] ), - reinterpret_cast( vertices[*( i + 1 )] ), - reinterpret_cast( vertices[*( i + 3 )] ), - clipped - ), - clipped, - best, - m_cull - ); - } -} }; class SelectionCounter { public: -typedef const Selectable& first_argument_type; + typedef const Selectable& first_argument_type; -SelectionCounter( const SelectionChangeCallback& onchanged ) - : m_count( 0 ), m_onchanged( onchanged ){ -} -void operator()( const Selectable& selectable ){ - if ( selectable.isSelected() ) { - ++m_count; - } - else - { - ASSERT_MESSAGE( m_count != 0, "selection counter underflow" ); - --m_count; + SelectionCounter( const SelectionChangeCallback& onchanged ) + : m_count( 0 ), m_onchanged( onchanged ){ } + void operator()( const Selectable& selectable ){ + if ( selectable.isSelected() ) { + ++m_count; + } + else + { + ASSERT_MESSAGE( m_count != 0, "selection counter underflow" ); + --m_count; + } - m_onchanged( selectable ); -} -bool empty() const { - return m_count == 0; -} -std::size_t size() const { - return m_count; -} + m_onchanged( selectable ); + } + bool empty() const { + return m_count == 0; + } + std::size_t size() const { + return m_count; + } private: -std::size_t m_count; -SelectionChangeCallback m_onchanged; + std::size_t m_count; + SelectionChangeCallback m_onchanged; }; class SelectedStuffCounter @@ -3370,9 +3378,9 @@ public: --m_entitycount; } void get( std::size_t& brushes, std::size_t& patches, std::size_t& entities ) const { - brushes = m_brushcount; - patches = m_patchcount; - entities = m_entitycount; + brushes = m_brushcount; + patches = m_patchcount; + entities = m_entitycount; } }; @@ -3396,21 +3404,21 @@ inline const rect_t SelectionBoxForArea( const float device_point[2], const floa selection_box.max[0] = ( device_delta[0] > 0 ) ? ( device_point[0] + device_delta[0] ) : ( device_point[0] ); selection_box.max[1] = ( device_delta[1] > 0 ) ? ( device_point[1] + device_delta[1] ) : ( device_point[1] ); selection_box.modifier = device_delta[0] * device_delta[1] < 0? - rect_t::eToggle - : device_delta[0] < 0 ? - rect_t::eDeselect - : rect_t::eSelect; + rect_t::eToggle + : device_delta[0] < 0 ? + rect_t::eDeselect + : rect_t::eSelect; return selection_box; } #if 0 Quaternion construct_local_rotation( const Quaternion& world, const Quaternion& localToWorld ){ return quaternion_normalised( quaternion_multiplied_by_quaternion( - quaternion_normalised( quaternion_multiplied_by_quaternion( - quaternion_inverse( localToWorld ), - world - ) ), - localToWorld - ) ); + quaternion_normalised( quaternion_multiplied_by_quaternion( + quaternion_inverse( localToWorld ), + world + ) ), + localToWorld + ) ); } #endif inline void matrix4_assign_rotation( Matrix4& matrix, const Matrix4& other ){ @@ -3440,18 +3448,18 @@ void matrix4_assign_rotation_for_pivot( Matrix4& matrix, scene::Instance& instan class TranslateSelected : public SelectionSystem::Visitor { -const Vector3& m_translate; + const Vector3& m_translate; public: -TranslateSelected( const Vector3& translate ) - : m_translate( translate ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setTranslation( m_translate ); + TranslateSelected( const Vector3& translate ) + : m_translate( translate ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setTranslation( m_translate ); + } } -} }; void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation ){ @@ -3461,12 +3469,10 @@ void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation ) } Vector3 get_local_pivot( const Vector3& world_pivot, const Matrix4& localToWorld ){ - return Vector3( - matrix4_transformed_point( - matrix4_full_inverse( localToWorld ), - world_pivot - ) - ); + return matrix4_transformed_point( + matrix4_full_inverse( localToWorld ), + world_pivot + ); } void translation_for_pivoted_matrix_transform( Vector3& parent_translation, const Matrix4& local_transform, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){ @@ -3486,12 +3492,12 @@ void translation_for_pivoted_matrix_transform( Vector3& parent_translation, cons Vector3 local_pivot( get_local_pivot( world_pivot, localToWorld ) ); Vector3 local_translation( - vector3_subtracted( - local_pivot, - matrix4_transformed_point( - local_transform, - local_pivot - ) + vector3_subtracted( + local_pivot, + matrix4_transformed_point( + local_transform, + local_pivot + ) /* matrix4_transformed_point( matrix4_full_inverse(local_transform), @@ -3499,8 +3505,8 @@ void translation_for_pivoted_matrix_transform( Vector3& parent_translation, cons ), local_pivot */ - ) - ); + ) + ); parent_translation = translation_local2object( local_translation, localToParent ); @@ -3520,14 +3526,14 @@ void translation_for_pivoted_rotation( Vector3& parent_translation, const Quater void translation_for_pivoted_scale( Vector3& parent_translation, const Vector3& world_scale, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){ Matrix4 local_transform( - matrix4_multiplied_by_matrix4( - matrix4_full_inverse( localToWorld ), - matrix4_multiplied_by_matrix4( - matrix4_scale_for_vec3( world_scale ), - localToWorld - ) - ) - ); + matrix4_multiplied_by_matrix4( + matrix4_full_inverse( localToWorld ), + matrix4_multiplied_by_matrix4( + matrix4_scale_for_vec3( world_scale ), + localToWorld + ) + ) + ); local_transform.tx() = local_transform.ty() = local_transform.tz() = 0; // cancel translation parts translation_for_pivoted_matrix_transform( parent_translation, local_transform, world_pivot, localToWorld, localToParent ); } @@ -3540,47 +3546,47 @@ void translation_for_pivoted_skew( Vector3& parent_translation, const Skew& loca class rotate_selected : public SelectionSystem::Visitor { -const Quaternion& m_rotate; -const Vector3& m_world_pivot; + const Quaternion& m_rotate; + const Vector3& m_world_pivot; public: -rotate_selected( const Quaternion& rotation, const Vector3& world_pivot ) - : m_rotate( rotation ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); - if ( transformNode != 0 ) { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setScale( c_scale_identity ); - transform->setTranslation( c_translation_identity ); + rotate_selected( const Quaternion& rotation, const Vector3& world_pivot ) + : m_rotate( rotation ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); + if ( transformNode != 0 ) { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setScale( c_scale_identity ); + transform->setTranslation( c_translation_identity ); - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setRotation( m_rotate ); + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setRotation( m_rotate ); - { - Editable* editable = Node_getEditable( instance.path().top() ); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + { + Editable* editable = Node_getEditable( instance.path().top() ); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - Vector3 parent_translation; - translation_for_pivoted_rotation( - parent_translation, - m_rotate, - m_world_pivot, + Vector3 parent_translation; + translation_for_pivoted_rotation( + parent_translation, + m_rotate, + m_world_pivot, #ifdef SELECTIONSYSTEM_AXIAL_PIVOTS - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) #else - matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ), - matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot ) + matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ), + matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot ) #endif ); - transform->setTranslation( parent_translation ); + transform->setTranslation( parent_translation ); + } } } } -} }; void Scene_Rotate_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){ @@ -3591,41 +3597,41 @@ void Scene_Rotate_Selected( scene::Graph& graph, const Quaternion& rotation, con class scale_selected : public SelectionSystem::Visitor { -const Vector3& m_scale; -const Vector3& m_world_pivot; + const Vector3& m_scale; + const Vector3& m_world_pivot; public: -scale_selected( const Vector3& scaling, const Vector3& world_pivot ) - : m_scale( scaling ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); - if ( transformNode != 0 ) { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setScale( c_scale_identity ); - transform->setTranslation( c_translation_identity ); + scale_selected( const Vector3& scaling, const Vector3& world_pivot ) + : m_scale( scaling ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); + if ( transformNode != 0 ) { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setScale( c_scale_identity ); + transform->setTranslation( c_translation_identity ); - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setScale( m_scale ); - { - Editable* editable = Node_getEditable( instance.path().top() ); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setScale( m_scale ); + { + Editable* editable = Node_getEditable( instance.path().top() ); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - Vector3 parent_translation; - translation_for_pivoted_scale( - parent_translation, - m_scale, - m_world_pivot, - matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ), - matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot ) + Vector3 parent_translation; + translation_for_pivoted_scale( + parent_translation, + m_scale, + m_world_pivot, + matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ), + matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot ) ); - transform->setTranslation( parent_translation ); + transform->setTranslation( parent_translation ); + } } } } -} }; void Scene_Scale_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){ @@ -3636,41 +3642,41 @@ void Scene_Scale_Selected( scene::Graph& graph, const Vector3& scaling, const Ve class skew_selected : public SelectionSystem::Visitor { -const Skew& m_skew; -const Vector3& m_world_pivot; + const Skew& m_skew; + const Vector3& m_world_pivot; public: -skew_selected( const Skew& skew, const Vector3& world_pivot ) - : m_skew( skew ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); - if ( transformNode != 0 ) { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setScale( c_scale_identity ); - transform->setTranslation( c_translation_identity ); + skew_selected( const Skew& skew, const Vector3& world_pivot ) + : m_skew( skew ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); + if ( transformNode != 0 ) { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setScale( c_scale_identity ); + transform->setTranslation( c_translation_identity ); - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setSkew( m_skew ); - { - Editable* editable = Node_getEditable( instance.path().top() ); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setSkew( m_skew ); + { + Editable* editable = Node_getEditable( instance.path().top() ); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - Vector3 parent_translation; - translation_for_pivoted_skew( - parent_translation, - m_skew, - m_world_pivot, - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) + Vector3 parent_translation; + translation_for_pivoted_skew( + parent_translation, + m_skew, + m_world_pivot, + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) ); - transform->setTranslation( parent_translation ); + transform->setTranslation( parent_translation ); + } } } } -} }; void Scene_Skew_Selected( scene::Graph& graph, const Skew& skew, const Vector3& world_pivot ){ @@ -3683,98 +3689,98 @@ void Scene_Skew_Selected( scene::Graph& graph, const Skew& skew, const Vector3& class RepeatableTransforms { public: -Translation m_translation; -Rotation m_rotation; -Scale m_scale; -Skew m_skew; -/* next aren't used; TODO: think if unique origin per transform is needed, and how to implement this correctly for entities, having transform keys */ -Vector3 m_rotationOrigin; -Vector3 m_scaleOrigin; -Vector3 m_skewOrigin; + Translation m_translation; + Rotation m_rotation; + Scale m_scale; + Skew m_skew; + /* next aren't used; TODO: think if unique origin per transform is needed, and how to implement this correctly for entities, having transform keys */ + Vector3 m_rotationOrigin; + Vector3 m_scaleOrigin; + Vector3 m_skewOrigin; -bool m_rotationOriginSet; -bool m_scaleOriginSet; -bool m_skewOriginSet; + bool m_rotationOriginSet; + bool m_scaleOriginSet; + bool m_skewOriginSet; -RepeatableTransforms(){ - setIdentity(); -} + RepeatableTransforms(){ + setIdentity(); + } -bool isIdentity() const { - return m_translation == c_translation_identity - && m_rotation == c_rotation_identity - && m_scale == c_scale_identity - && m_skew == c_skew_identity; -} -void setIdentity(){ - m_translation = c_translation_identity; - m_rotation = c_quaternion_identity; - m_scale = c_scale_identity; - m_skew = c_skew_identity; + bool isIdentity() const { + return m_translation == c_translation_identity + && m_rotation == c_rotation_identity + && m_scale == c_scale_identity + && m_skew == c_skew_identity; + } + void setIdentity(){ + m_translation = c_translation_identity; + m_rotation = c_quaternion_identity; + m_scale = c_scale_identity; + m_skew = c_skew_identity; - m_rotationOrigin = - m_scaleOrigin = - m_skewOrigin = g_vector3_identity; + m_rotationOrigin = + m_scaleOrigin = + m_skewOrigin = g_vector3_identity; - m_rotationOriginSet = - m_scaleOriginSet = - m_skewOriginSet = false; -} + m_rotationOriginSet = + m_scaleOriginSet = + m_skewOriginSet = false; + } }; class transform_selected : public SelectionSystem::Visitor { -const RepeatableTransforms& m_transforms; -const Vector3& m_world_pivot; + const RepeatableTransforms& m_transforms; + const Vector3& m_world_pivot; public: -transform_selected( const RepeatableTransforms& transforms, const Vector3& world_pivot ) - : m_transforms( transforms ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); - if ( transformNode != 0 ) { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_PRIMITIVE ); - transform->setRotation( m_transforms.m_rotation ); - transform->setScale( m_transforms.m_scale ); - transform->setSkew( m_transforms.m_skew ); - { - Editable* editable = Node_getEditable( instance.path().top() ); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + transform_selected( const RepeatableTransforms& transforms, const Vector3& world_pivot ) + : m_transforms( transforms ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + TransformNode* transformNode = Node_getTransformNode( instance.path().top() ); + if ( transformNode != 0 ) { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_PRIMITIVE ); + transform->setRotation( m_transforms.m_rotation ); + transform->setScale( m_transforms.m_scale ); + transform->setSkew( m_transforms.m_skew ); + { + Editable* editable = Node_getEditable( instance.path().top() ); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - const Matrix4 local_transform = matrix4_transform_for_components( c_translation_identity, m_transforms.m_rotation, m_transforms.m_scale, m_transforms.m_skew ); - Vector3 parent_translation; - translation_for_pivoted_matrix_transform( - parent_translation, - local_transform, - m_world_pivot, - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), - matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) + const Matrix4 local_transform = matrix4_transform_for_components( c_translation_identity, m_transforms.m_rotation, m_transforms.m_scale, m_transforms.m_skew ); + Vector3 parent_translation; + translation_for_pivoted_matrix_transform( + parent_translation, + local_transform, + m_world_pivot, + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( instance.localToWorld() ) ), localPivot ), + matrix4_multiplied_by_matrix4( matrix4_translation_for_vec3( matrix4_get_translation_vec3( transformNode->localToParent() ) ), localPivot ) ); - transform->setTranslation( parent_translation + m_transforms.m_translation ); + transform->setTranslation( parent_translation + m_transforms.m_translation ); + } } } } -} }; class translate_component_selected : public SelectionSystem::Visitor { -const Vector3& m_translate; + const Vector3& m_translate; public: -translate_component_selected( const Vector3& translate ) - : m_translate( translate ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->setType( TRANSFORM_COMPONENT ); - transform->setTranslation( m_translate ); + translate_component_selected( const Vector3& translate ) + : m_translate( translate ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->setType( TRANSFORM_COMPONENT ); + transform->setTranslation( m_translate ); + } } -} }; void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& translation ){ @@ -3785,23 +3791,23 @@ void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& tra class rotate_component_selected : public SelectionSystem::Visitor { -const Quaternion& m_rotate; -const Vector3& m_world_pivot; + const Quaternion& m_rotate; + const Vector3& m_world_pivot; public: -rotate_component_selected( const Quaternion& rotation, const Vector3& world_pivot ) - : m_rotate( rotation ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - Vector3 parent_translation; - translation_for_pivoted_rotation( parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); - - transform->setType( TRANSFORM_COMPONENT ); - transform->setRotation( m_rotate ); - transform->setTranslation( parent_translation ); + rotate_component_selected( const Quaternion& rotation, const Vector3& world_pivot ) + : m_rotate( rotation ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + Vector3 parent_translation; + translation_for_pivoted_rotation( parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); + + transform->setType( TRANSFORM_COMPONENT ); + transform->setRotation( m_rotate ); + transform->setTranslation( parent_translation ); + } } -} }; void Scene_Rotate_Component_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){ @@ -3812,23 +3818,23 @@ void Scene_Rotate_Component_Selected( scene::Graph& graph, const Quaternion& rot class scale_component_selected : public SelectionSystem::Visitor { -const Vector3& m_scale; -const Vector3& m_world_pivot; + const Vector3& m_scale; + const Vector3& m_world_pivot; public: -scale_component_selected( const Vector3& scaling, const Vector3& world_pivot ) - : m_scale( scaling ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - Vector3 parent_translation; - translation_for_pivoted_scale( parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); - - transform->setType( TRANSFORM_COMPONENT ); - transform->setScale( m_scale ); - transform->setTranslation( parent_translation ); + scale_component_selected( const Vector3& scaling, const Vector3& world_pivot ) + : m_scale( scaling ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + Vector3 parent_translation; + translation_for_pivoted_scale( parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); + + transform->setType( TRANSFORM_COMPONENT ); + transform->setScale( m_scale ); + transform->setTranslation( parent_translation ); + } } -} }; void Scene_Scale_Component_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){ @@ -3839,23 +3845,23 @@ void Scene_Scale_Component_Selected( scene::Graph& graph, const Vector3& scaling class skew_component_selected : public SelectionSystem::Visitor { -const Skew& m_skew; -const Vector3& m_world_pivot; + const Skew& m_skew; + const Vector3& m_world_pivot; public: -skew_component_selected( const Skew& skew, const Vector3& world_pivot ) - : m_skew( skew ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - Vector3 parent_translation; - translation_for_pivoted_skew( parent_translation, m_skew, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); - - transform->setType( TRANSFORM_COMPONENT ); - transform->setSkew( m_skew ); - transform->setTranslation( parent_translation ); + skew_component_selected( const Skew& skew, const Vector3& world_pivot ) + : m_skew( skew ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + Vector3 parent_translation; + translation_for_pivoted_skew( parent_translation, m_skew, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); + + transform->setType( TRANSFORM_COMPONENT ); + transform->setSkew( m_skew ); + transform->setTranslation( parent_translation ); + } } -} }; void Scene_Skew_Component_Selected( scene::Graph& graph, const Skew& skew, const Vector3& world_pivot ){ @@ -3867,133 +3873,133 @@ void Scene_Skew_Component_Selected( scene::Graph& graph, const Skew& skew, const class transform_component_selected : public SelectionSystem::Visitor { -const RepeatableTransforms& m_transforms; -const Vector3& m_world_pivot; + const RepeatableTransforms& m_transforms; + const Vector3& m_world_pivot; public: -transform_component_selected( const RepeatableTransforms& transforms, const Vector3& world_pivot ) - : m_transforms( transforms ), m_world_pivot( world_pivot ){ -} -void visit( scene::Instance& instance ) const { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - const Matrix4 local_transform = matrix4_transform_for_components( c_translation_identity, m_transforms.m_rotation, m_transforms.m_scale, m_transforms.m_skew ); - Vector3 parent_translation; - translation_for_pivoted_matrix_transform( parent_translation, local_transform, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); - - transform->setType( TRANSFORM_COMPONENT ); - transform->setRotation( m_transforms.m_rotation ); - transform->setScale( m_transforms.m_scale ); - transform->setSkew( m_transforms.m_skew ); - transform->setTranslation( parent_translation + m_transforms.m_translation ); + transform_component_selected( const RepeatableTransforms& transforms, const Vector3& world_pivot ) + : m_transforms( transforms ), m_world_pivot( world_pivot ){ + } + void visit( scene::Instance& instance ) const { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + const Matrix4 local_transform = matrix4_transform_for_components( c_translation_identity, m_transforms.m_rotation, m_transforms.m_scale, m_transforms.m_skew ); + Vector3 parent_translation; + translation_for_pivoted_matrix_transform( parent_translation, local_transform, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() ); + + transform->setType( TRANSFORM_COMPONENT ); + transform->setRotation( m_transforms.m_rotation ); + transform->setScale( m_transforms.m_scale ); + transform->setSkew( m_transforms.m_skew ); + transform->setTranslation( parent_translation + m_transforms.m_translation ); + } } -} }; class BooleanSelector : public Selector { -SelectionIntersection m_bestIntersection; -Selectable* m_selectable; + SelectionIntersection m_bestIntersection; + Selectable* m_selectable; public: -BooleanSelector() : m_bestIntersection( SelectionIntersection() ){ -} - -void pushSelectable( Selectable& selectable ){ - m_selectable = &selectable; -} -void popSelectable(){ -} -void addIntersection( const SelectionIntersection& intersection ){ - if ( m_selectable->isSelected() ) { - assign_if_closer( m_bestIntersection, intersection ); + BooleanSelector() : m_bestIntersection( SelectionIntersection() ){ } -} -bool isSelected(){ - return m_bestIntersection.valid(); -} -const SelectionIntersection& bestIntersection() const { - return m_bestIntersection; -} + void pushSelectable( Selectable& selectable ){ + m_selectable = &selectable; + } + void popSelectable(){ + } + void addIntersection( const SelectionIntersection& intersection ){ + if ( m_selectable->isSelected() ) { + assign_if_closer( m_bestIntersection, intersection ); + } + } + + bool isSelected(){ + return m_bestIntersection.valid(); + } + const SelectionIntersection& bestIntersection() const { + return m_bestIntersection; + } }; class BestSelector : public Selector { protected: -SelectionIntersection m_intersection; -Selectable* m_selectable; -SelectionIntersection m_bestIntersection; -std::list m_bestSelectable; + SelectionIntersection m_intersection; + Selectable* m_selectable; + SelectionIntersection m_bestIntersection; + std::list m_bestSelectable; public: -BestSelector() : m_bestIntersection( SelectionIntersection() ), m_bestSelectable( 0 ){ -} - -void pushSelectable( Selectable& selectable ){ - m_intersection = SelectionIntersection(); - m_selectable = &selectable; -} -void popSelectable(){ - if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 2e-6f ) ) { - m_bestSelectable.push_back( m_selectable ); - m_bestIntersection = m_intersection; + BestSelector() : m_bestIntersection( SelectionIntersection() ), m_bestSelectable( 0 ){ } - else if ( m_intersection < m_bestIntersection ) { - m_bestSelectable.clear(); - m_bestSelectable.push_back( m_selectable ); - m_bestIntersection = m_intersection; - } - m_intersection = SelectionIntersection(); -} -void addIntersection( const SelectionIntersection& intersection ){ - assign_if_closer( m_intersection, intersection ); -} -std::list& best(){ - return m_bestSelectable; -} -const SelectionIntersection& bestIntersection() const { - return m_bestIntersection; -} + void pushSelectable( Selectable& selectable ){ + m_intersection = SelectionIntersection(); + m_selectable = &selectable; + } + void popSelectable(){ + if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 2e-6f ) ) { + m_bestSelectable.push_back( m_selectable ); + m_bestIntersection = m_intersection; + } + else if ( m_intersection < m_bestIntersection ) { + m_bestSelectable.clear(); + m_bestSelectable.push_back( m_selectable ); + m_bestIntersection = m_intersection; + } + m_intersection = SelectionIntersection(); + } + void addIntersection( const SelectionIntersection& intersection ){ + assign_if_closer( m_intersection, intersection ); + } + + std::list& best(){ + return m_bestSelectable; + } + const SelectionIntersection& bestIntersection() const { + return m_bestIntersection; + } }; class DeepBestSelector : public BestSelector // copy of class BestSelector with 2.f depthEpsilon { public: -void popSelectable(){ - if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 2.f ) ) { - m_bestSelectable.push_back( m_selectable ); - m_bestIntersection = m_intersection; + void popSelectable(){ + if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 2.f ) ) { + m_bestSelectable.push_back( m_selectable ); + m_bestIntersection = m_intersection; + } + else if ( m_intersection < m_bestIntersection ) { + m_bestSelectable.clear(); + m_bestSelectable.push_back( m_selectable ); + m_bestIntersection = m_intersection; + } + m_intersection = SelectionIntersection(); } - else if ( m_intersection < m_bestIntersection ) { - m_bestSelectable.clear(); - m_bestSelectable.push_back( m_selectable ); - m_bestIntersection = m_intersection; - } - m_intersection = SelectionIntersection(); -} }; class BestPointSelector : public Selector { -SelectionIntersection m_bestIntersection; + SelectionIntersection m_bestIntersection; public: -BestPointSelector() : m_bestIntersection( SelectionIntersection() ){ -} + BestPointSelector() : m_bestIntersection( SelectionIntersection() ){ + } -void pushSelectable( Selectable& selectable ){ -} -void popSelectable(){ -} -void addIntersection( const SelectionIntersection& intersection ){ - assign_if_closer( m_bestIntersection, intersection ); -} + void pushSelectable( Selectable& selectable ){ + } + void popSelectable(){ + } + void addIntersection( const SelectionIntersection& intersection ){ + assign_if_closer( m_bestIntersection, intersection ); + } -bool isSelected(){ - return m_bestIntersection.valid(); -} -const SelectionIntersection& best() const { - return m_bestIntersection; -} + bool isSelected(){ + return m_bestIntersection.valid(); + } + const SelectionIntersection& best() const { + return m_bestIntersection; + } }; @@ -4094,14 +4100,14 @@ Vector3 testSelected_scene_snapped_point( const SelectionVolume& test, ClipperSe float bestDist = FLT_MAX; Vector3 wannabePoint; for ( Winding::const_iterator prev = face.getWinding().end() - 1, curr = face.getWinding().begin(); curr != face.getWinding().end(); prev = curr, ++curr ){ - { /* try vertices */ + { /* try vertices */ const float dist = vector3_length_squared( ( *curr ).vertex - point ); if( dist < bestDist ){ wannabePoint = ( *curr ).vertex; bestDist = dist; } } - { /* try edges */ + { /* try edges */ Vector3 edgePoint = line_closest_point( Line( ( *prev ).vertex, ( *curr ).vertex ), point ); if( edgePoint != ( *prev ).vertex && edgePoint != ( *curr ).vertex ){ const Vector3 edgedir = vector3_normalised( ( *curr ).vertex - ( *prev ).vertex ); @@ -4122,8 +4128,8 @@ Vector3 testSelected_scene_snapped_point( const SelectionVolume& test, ClipperSe Vector3 planePoint( vector3_snapped( point, GetSnapGridSize() ) ); // face.plane3().normal().dot( point snapped ) = face.plane3().dist() planePoint[maxi] = ( face.plane3().dist() - - face.plane3().normal()[( maxi + 1 ) % 3] * planePoint[( maxi + 1 ) % 3] - - face.plane3().normal()[( maxi + 2 ) % 3] * planePoint[( maxi + 2 ) % 3] ) / face.plane3().normal()[maxi]; + - face.plane3().normal()[( maxi + 1 ) % 3] * planePoint[( maxi + 1 ) % 3] + - face.plane3().normal()[( maxi + 2 ) % 3] * planePoint[( maxi + 2 ) % 3] ) / face.plane3().normal()[maxi]; const float dist = vector3_length_squared( planePoint - point ); if( dist < bestDist ){ wannabePoint = planePoint; @@ -4195,7 +4201,7 @@ bool scene_insert_brush_vertices( const View& view, TranslateFreeXY_Z& freeDragX } bool selection_selectVerticesOrFaceVertices( SelectionTest& test ){ - { /* try to hit vertices */ + { /* try to hit vertices */ DeepBestSelector deepSelector; Scene_TestSelect_Component_Selected( deepSelector, test, test.getVolume(), SelectionSystem::eVertex ); if( !deepSelector.best().empty() ){ @@ -4223,17 +4229,17 @@ bool selection_selectVerticesOrFaceVertices( SelectionTest& test ){ template class ComponentSelectionTestableVisibleSelectedVisitor : public SelectionSystem::Visitor { -const Functor& m_functor; + const Functor& m_functor; public: -ComponentSelectionTestableVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ -} -void visit( scene::Instance& instance ) const { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); - if ( componentSelectionTestable != 0 - && instance.path().top().get().visible() ) { - m_functor( *componentSelectionTestable ); + ComponentSelectionTestableVisibleSelectedVisitor( const Functor& functor ) : m_functor( functor ){ + } + void visit( scene::Instance& instance ) const { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); + if ( componentSelectionTestable != 0 + && instance.path().top().get().visible() ) { + m_functor( *componentSelectionTestable ); + } } -} }; template @@ -4249,249 +4255,249 @@ static bool g_bTmpComponentMode = false; class DragManipulator : public Manipulator { -TranslateFree m_freeResize; -TranslateAxis2 m_axisResize; -TranslateFreeXY_Z m_freeDragXY_Z; -ResizeTranslatable m_resize; -DragNewBrush m_dragNewBrush; -DragExtrudeFaces m_dragExtrudeFaces; -bool m_dragSelected; //drag selected primitives or components -bool m_selected; //components selected temporally for drag -bool m_selected2; //planeselectables in cam with alt -bool m_newBrush; -bool m_extrudeFaces; + TranslateFree m_freeResize; + TranslateAxis2 m_axisResize; + TranslateFreeXY_Z m_freeDragXY_Z; + ResizeTranslatable m_resize; + DragNewBrush m_dragNewBrush; + DragExtrudeFaces m_dragExtrudeFaces; + bool m_dragSelected; //drag selected primitives or components + bool m_selected; //components selected temporally for drag + bool m_selected2; //planeselectables in cam with alt + bool m_newBrush; + bool m_extrudeFaces; public: -static Shader* m_state_wire; + static Shader* m_state_wire; -DragManipulator( Translatable& translatable ) : m_freeResize( m_resize ), m_axisResize( m_resize ), m_freeDragXY_Z( translatable ), m_renderCircle( 2 << 3 ){ - setSelected( false ); - draw_circle( m_renderCircle.m_vertices.size() >> 3, 5, m_renderCircle.m_vertices.data(), RemapXYZ() ); -} - -Manipulatable* GetManipulatable(){ - if( m_newBrush ) - return &m_dragNewBrush; - else if( m_extrudeFaces ) - return &m_dragExtrudeFaces; - else if( m_selected ) - return &m_freeResize; - else if( m_selected2 ) - return &m_axisResize; - else - return &m_freeDragXY_Z; -} - -void testSelect( const View& view, const Matrix4& pivot2world ){ - SelectionPool selector; - SelectionVolume test( view ); - - if( g_modifiers == ( c_modifierAlt | c_modifierControl ) - && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive - && ( GlobalSelectionSystem().countSelected() != 0 || !g_SelectedFaceInstances.empty() ) ){ // extrude - m_extrudeFaces = Scene_forEachBrush_setupExtrude( test, m_dragExtrudeFaces ); + DragManipulator( Translatable& translatable ) : m_freeResize( m_resize ), m_axisResize( m_resize ), m_freeDragXY_Z( translatable ), m_renderCircle( 2 << 3 ){ + setSelected( false ); + draw_circle( m_renderCircle.m_vertices.size() >> 3, 5, m_renderCircle.m_vertices.data(), RemapXYZ() ); } - else if( GlobalSelectionSystem().countSelected() != 0 ){ - if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ - if( g_modifiers == c_modifierAlt ){ - if( view.fill() ){ // alt resize - m_selected2 = Scene_forEachPlaneSelectable_selectPlanes2( test, m_axisResize ); - } - else{ // alt vertices drag - m_selected = selection_selectVerticesOrFaceVertices( test ); - } - } - else{ - BooleanSelector booleanSelector; - Scene_TestSelect_Primitive( booleanSelector, test, view ); - if ( booleanSelector.isSelected() ) { /* hit a primitive */ - m_dragSelected = true; /* drag a primitive */ - test.BeginMesh( g_matrix4_identity, true ); - m_freeDragXY_Z.set0( vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, booleanSelector.bestIntersection().depth(), 1 ) ) ) ); - } - else{ /* haven't hit a primitive */ - m_selected = Scene_forEachPlaneSelectable_selectPlanes( GlobalSceneGraph(), selector, test ); /* select faces on planeSelectables */ - } - } - } - else{ // components - BestSelector bestSelector; - Scene_TestSelect_Component_Selected( bestSelector, test, view, GlobalSelectionSystem().ComponentMode() ); /* drag components */ - for ( Selectable* s : bestSelector.best() ){ - if ( !s->isSelected() ) - GlobalSelectionSystem().setSelectedAllComponents( false ); - selector.addSelectable( SelectionIntersection( 0, 0 ), s ); - m_dragSelected = true; - } - if( bestSelector.bestIntersection().valid() ){ - test.BeginMesh( g_matrix4_identity, true ); - m_freeDragXY_Z.set0( vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, bestSelector.bestIntersection().depth(), 1 ) ) ) ); - } - else{ - if( GlobalSelectionSystem().countSelectedComponents() != 0 ){ /* drag, even if hit nothing, but got selected */ - m_dragSelected = true; - m_freeDragXY_Z.set0( g_vector3_identity ); - } - else if( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ){ /* otherwise insert */ - m_dragSelected = g_bTmpComponentMode = scene_insert_brush_vertices( view, m_freeDragXY_Z ); //hack: indicating not a tmp mode - return; - } - } - } - - for ( SelectableSortedSet::value_type& value : selector ) - value.second->setSelected( true ); - g_bTmpComponentMode = m_selected | m_selected2; + Manipulatable* GetManipulatable(){ + if( m_newBrush ) + return &m_dragNewBrush; + else if( m_extrudeFaces ) + return &m_dragExtrudeFaces; + else if( m_selected ) + return &m_freeResize; + else if( m_selected2 ) + return &m_axisResize; + else + return &m_freeDragXY_Z; } - else if( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ - m_newBrush = true; - BestPointSelector bestPointSelector; - Scene_TestSelect_Primitive( bestPointSelector, test, view ); - Vector3 start; - test.BeginMesh( g_matrix4_identity, true ); - if( bestPointSelector.isSelected() ){ - start = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, bestPointSelector.best().depth(), 1 ) ) ); - } - else{ - const Vector3 near = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, -1, 1 ) ) ); - const Vector3 far = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, 1, 1 ) ) ); - start = vector3_normalised( far - near ) * ( 256.f + GetGridSize() * sqrt( 3.0 ) ) + near; - } - vector3_snap( start, GetSnapGridSize() ); - m_dragNewBrush.set0( start ); - } -} -void setSelected( bool select ){ - m_dragSelected = select; - m_selected = select; - m_selected2 = select; - m_newBrush = select; - m_extrudeFaces = select; -} -bool isSelected() const { - return m_dragSelected || m_selected || m_selected2 || m_newBrush || m_extrudeFaces; -} + void testSelect( const View& view, const Matrix4& pivot2world ){ + SelectionPool selector; + SelectionVolume test( view ); -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ - if( !m_polygons.empty() ){ - renderer.SetState( m_state_wire, Renderer::eWireframeOnly ); - renderer.SetState( m_state_wire, Renderer::eFullMaterials ); - if( m_polygons.back().size() == 1 ){ - Pivot2World_viewplaneSpace( m_renderCircle.m_viewplaneSpace, matrix4_translation_for_vec3( m_polygons.back()[0] ), volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - renderer.addRenderable( m_renderCircle, m_renderCircle.m_viewplaneSpace ); + if( g_modifiers == ( c_modifierAlt | c_modifierControl ) + && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive + && ( GlobalSelectionSystem().countSelected() != 0 || !g_SelectedFaceInstances.empty() ) ){ // extrude + m_extrudeFaces = Scene_forEachBrush_setupExtrude( test, m_dragExtrudeFaces ); } - else{ - renderer.addRenderable( m_renderPoly, g_matrix4_identity ); - } - } -} -void highlight( const View& view ){ - SelectionVolume test( view ); - std::vector> polygons; - /* conditions structure respects one in testSelect() */ - if( g_modifiers == ( c_modifierAlt | c_modifierControl ) - && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive - && ( GlobalSelectionSystem().countSelected() != 0 || !g_SelectedFaceInstances.empty() ) ){ // extrude - Plane3 plane( 0, 0, 0, 0 ); - Vector3 intersectionPoint( FLT_MAX, FLT_MAX, FLT_MAX ); - Scene_forEachBrush_bestPlane( test, plane, intersectionPoint ); - - if( plane3_valid( plane ) ){ - auto gatherPolygonsByPlane = [plane, &polygons]( BrushInstance& brushInstance ){ - if( brushInstance.isSelected() || brushInstance.isSelectedComponents() ) - brushInstance.gatherPolygonsByPlane( plane, polygons, false ); - }; - Scene_forEachVisibleBrush( GlobalSceneGraph(), gatherPolygonsByPlane ); - } - } - else if( GlobalSelectionSystem().countSelected() != 0 ){ - if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ - if( g_modifiers == c_modifierAlt ){ - if( view.fill() ){ // alt resize - Plane3 plane( 0, 0, 0, 0 ); - Vector3 intersectionPoint( FLT_MAX, FLT_MAX, FLT_MAX ); - Scene_forEachPlaneSelectable_bestPlane( test, plane, intersectionPoint ); - - if( plane3_valid( plane ) ){ - auto gatherPolygonsByPlane = [plane, &polygons]( PlaneSelectable& planeSelectable ){ - planeSelectable.gatherPolygonsByPlane( plane, polygons ); - }; - Scene_forEachVisibleSelectedPlaneselectable( gatherPolygonsByPlane ); + else if( GlobalSelectionSystem().countSelected() != 0 ){ + if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ + if( g_modifiers == c_modifierAlt ){ + if( view.fill() ){ // alt resize + m_selected2 = Scene_forEachPlaneSelectable_selectPlanes2( test, m_axisResize ); + } + else{ // alt vertices drag + m_selected = selection_selectVerticesOrFaceVertices( test ); } - } - else{ // alt vertices drag - SelectionIntersection intersection; - const SelectionSystem::EComponentMode mode = SelectionSystem::eVertex; - auto gatherComponentsHighlight = [&polygons, &intersection, &test, mode]( const ComponentSelectionTestable& componentSelectionTestable ){ - componentSelectionTestable.gatherComponentsHighlight( polygons, intersection, test, mode ); - }; - Scene_forEachVisibleSelectedComponentSelectionTestable( gatherComponentsHighlight ); + else{ + BooleanSelector booleanSelector; + Scene_TestSelect_Primitive( booleanSelector, test, view ); - if( polygons.empty() ){ + if ( booleanSelector.isSelected() ) { /* hit a primitive */ + m_dragSelected = true; /* drag a primitive */ + test.BeginMesh( g_matrix4_identity, true ); + m_freeDragXY_Z.set0( vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, booleanSelector.bestIntersection().depth(), 1 ) ) ) ); + } + else{ /* haven't hit a primitive */ + m_selected = Scene_forEachPlaneSelectable_selectPlanes( GlobalSceneGraph(), selector, test ); /* select faces on planeSelectables */ + } + } + } + else{ // components + BestSelector bestSelector; + Scene_TestSelect_Component_Selected( bestSelector, test, view, GlobalSelectionSystem().ComponentMode() ); /* drag components */ + for ( Selectable* s : bestSelector.best() ){ + if ( !s->isSelected() ) + GlobalSelectionSystem().setSelectedAllComponents( false ); + selector.addSelectable( SelectionIntersection( 0, 0 ), s ); + m_dragSelected = true; + } + if( bestSelector.bestIntersection().valid() ){ + test.BeginMesh( g_matrix4_identity, true ); + m_freeDragXY_Z.set0( vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, bestSelector.bestIntersection().depth(), 1 ) ) ) ); + } + else{ + if( GlobalSelectionSystem().countSelectedComponents() != 0 ){ /* drag, even if hit nothing, but got selected */ + m_dragSelected = true; + m_freeDragXY_Z.set0( g_vector3_identity ); + } + else if( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex ){ /* otherwise insert */ + m_dragSelected = g_bTmpComponentMode = scene_insert_brush_vertices( view, m_freeDragXY_Z ); //hack: indicating not a tmp mode + return; + } + } + } + + for ( SelectableSortedSet::value_type& value : selector ) + value.second->setSelected( true ); + g_bTmpComponentMode = m_selected | m_selected2; + } + else if( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ + m_newBrush = true; + BestPointSelector bestPointSelector; + Scene_TestSelect_Primitive( bestPointSelector, test, view ); + Vector3 start; + test.BeginMesh( g_matrix4_identity, true ); + if( bestPointSelector.isSelected() ){ + start = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, bestPointSelector.best().depth(), 1 ) ) ); + } + else{ + const Vector3 near = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, -1, 1 ) ) ); + const Vector3 far = vector4_projected( matrix4_transformed_vector4( test.getScreen2world(), Vector4( 0, 0, 1, 1 ) ) ); + start = vector3_normalised( far - near ) * ( 256.f + GetGridSize() * sqrt( 3.0 ) ) + near; + } + vector3_snap( start, GetSnapGridSize() ); + m_dragNewBrush.set0( start ); + } + } + + void setSelected( bool select ){ + m_dragSelected = select; + m_selected = select; + m_selected2 = select; + m_newBrush = select; + m_extrudeFaces = select; + } + bool isSelected() const { + return m_dragSelected || m_selected || m_selected2 || m_newBrush || m_extrudeFaces; + } + + void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){ + if( !m_polygons.empty() ){ + renderer.SetState( m_state_wire, Renderer::eWireframeOnly ); + renderer.SetState( m_state_wire, Renderer::eFullMaterials ); + if( m_polygons.back().size() == 1 ){ + Pivot2World_viewplaneSpace( m_renderCircle.m_viewplaneSpace, matrix4_translation_for_vec3( m_polygons.back()[0] ), volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); + renderer.addRenderable( m_renderCircle, m_renderCircle.m_viewplaneSpace ); + } + else{ + renderer.addRenderable( m_renderPoly, g_matrix4_identity ); + } + } + } + void highlight( const View& view ){ + SelectionVolume test( view ); + std::vector> polygons; + /* conditions structure respects one in testSelect() */ + if( g_modifiers == ( c_modifierAlt | c_modifierControl ) + && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive + && ( GlobalSelectionSystem().countSelected() != 0 || !g_SelectedFaceInstances.empty() ) ){ // extrude + Plane3 plane( 0, 0, 0, 0 ); + Vector3 intersectionPoint( FLT_MAX, FLT_MAX, FLT_MAX ); + Scene_forEachBrush_bestPlane( test, plane, intersectionPoint ); + + if( plane3_valid( plane ) ){ + auto gatherPolygonsByPlane = [plane, &polygons]( BrushInstance& brushInstance ){ + if( brushInstance.isSelected() || brushInstance.isSelectedComponents() ) + brushInstance.gatherPolygonsByPlane( plane, polygons, false ); + }; + Scene_forEachVisibleBrush( GlobalSceneGraph(), gatherPolygonsByPlane ); + } + } + else if( GlobalSelectionSystem().countSelected() != 0 ){ + if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ){ + if( g_modifiers == c_modifierAlt ){ + if( view.fill() ){ // alt resize Plane3 plane( 0, 0, 0, 0 ); Vector3 intersectionPoint( FLT_MAX, FLT_MAX, FLT_MAX ); - Scene_forEachSelectedBrush_bestPlane( test, plane, intersectionPoint ); + Scene_forEachPlaneSelectable_bestPlane( test, plane, intersectionPoint ); if( plane3_valid( plane ) ){ - auto gatherPolygonsByPlane = [plane, &polygons]( BrushInstance& brushInstance ){ - brushInstance.gatherPolygonsByPlane( plane, polygons ); + auto gatherPolygonsByPlane = [plane, &polygons]( PlaneSelectable& planeSelectable ){ + planeSelectable.gatherPolygonsByPlane( plane, polygons ); }; - Scene_forEachVisibleSelectedBrush( gatherPolygonsByPlane ); + Scene_forEachVisibleSelectedPlaneselectable( gatherPolygonsByPlane ); + } + + } + else{ // alt vertices drag + SelectionIntersection intersection; + const SelectionSystem::EComponentMode mode = SelectionSystem::eVertex; + auto gatherComponentsHighlight = [&polygons, &intersection, &test, mode]( const ComponentSelectionTestable& componentSelectionTestable ){ + componentSelectionTestable.gatherComponentsHighlight( polygons, intersection, test, mode ); + }; + Scene_forEachVisibleSelectedComponentSelectionTestable( gatherComponentsHighlight ); + + if( polygons.empty() ){ + Plane3 plane( 0, 0, 0, 0 ); + Vector3 intersectionPoint( FLT_MAX, FLT_MAX, FLT_MAX ); + Scene_forEachSelectedBrush_bestPlane( test, plane, intersectionPoint ); + + if( plane3_valid( plane ) ){ + auto gatherPolygonsByPlane = [plane, &polygons]( BrushInstance& brushInstance ){ + brushInstance.gatherPolygonsByPlane( plane, polygons ); + }; + Scene_forEachVisibleSelectedBrush( gatherPolygonsByPlane ); + } } } } } + else{ // components + SelectionIntersection intersection; + const SelectionSystem::EComponentMode mode = GlobalSelectionSystem().ComponentMode(); + auto gatherComponentsHighlight = [&polygons, &intersection, &test, mode]( const ComponentSelectionTestable& componentSelectionTestable ){ + componentSelectionTestable.gatherComponentsHighlight( polygons, intersection, test, mode ); + }; + Scene_forEachVisibleSelectedComponentSelectionTestable( gatherComponentsHighlight ); + } } - else{ // components - SelectionIntersection intersection; - const SelectionSystem::EComponentMode mode = GlobalSelectionSystem().ComponentMode(); - auto gatherComponentsHighlight = [&polygons, &intersection, &test, mode]( const ComponentSelectionTestable& componentSelectionTestable ){ - componentSelectionTestable.gatherComponentsHighlight( polygons, intersection, test, mode ); - }; - Scene_forEachVisibleSelectedComponentSelectionTestable( gatherComponentsHighlight ); - } - } - if( m_polygons != polygons ){ - m_polygons.swap( polygons ); - SceneChangeNotify(); + if( m_polygons != polygons ){ + m_polygons.swap( polygons ); + SceneChangeNotify(); + } } -} private: -std::vector> m_polygons; -struct RenderablePoly: public OpenGLRenderable -{ - const std::vector>& m_polygons; + std::vector> m_polygons; + struct RenderablePoly: public OpenGLRenderable + { + const std::vector>& m_polygons; - RenderablePoly( const std::vector>& polygons ) : m_polygons( polygons ){ - } - void render( RenderStateFlags state ) const { - glPolygonOffset( -2, -2 ); - for( const auto& poly : m_polygons ){ - glVertexPointer( 3, GL_FLOAT, sizeof( m_polygons[0][0] ), poly[0].data() ); - glDrawArrays( GL_POLYGON, 0, GLsizei( poly.size() ) ); + RenderablePoly( const std::vector>& polygons ) : m_polygons( polygons ){ } - glPolygonOffset( -1, 1 ); // restore default - } -}; -RenderablePoly m_renderPoly{ m_polygons }; -struct RenderableCircle : public OpenGLRenderable -{ - Array m_vertices; - Matrix4 m_viewplaneSpace; + void render( RenderStateFlags state ) const { + glPolygonOffset( -2, -2 ); + for( const auto& poly : m_polygons ){ + glVertexPointer( 3, GL_FLOAT, sizeof( m_polygons[0][0] ), poly[0].data() ); + glDrawArrays( GL_POLYGON, 0, GLsizei( poly.size() ) ); + } + glPolygonOffset( -1, 1 ); // restore default + } + }; + RenderablePoly m_renderPoly{ m_polygons }; + struct RenderableCircle : public OpenGLRenderable + { + Array m_vertices; + Matrix4 m_viewplaneSpace; - RenderableCircle( std::size_t size ) : m_vertices( size ){ - } - void render( RenderStateFlags state ) const { - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); - glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) ); - } -}; -RenderableCircle m_renderCircle; + RenderableCircle( std::size_t size ) : m_vertices( size ){ + } + void render( RenderStateFlags state ) const { + glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); + glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) ); + } + }; + RenderableCircle m_renderCircle; }; Shader* DragManipulator::m_state_wire; @@ -4568,7 +4574,7 @@ public: } void viewdir_fixup(){ if( fabs( vector3_length( m_points[1].m_point - m_points[0].m_point ) ) > 1e-3 //two non coincident points - && fabs( vector3_dot( m_viewdir, vector3_normalised( m_points[1].m_point - m_points[0].m_point ) ) ) > 0.999 ){ //on axis = m_viewdir + && fabs( vector3_dot( m_viewdir, vector3_normalised( m_points[1].m_point - m_points[0].m_point ) ) ) > 0.999 ){ //on axis = m_viewdir viewdir_set( m_view->getViewDir() ); if( fabs( vector3_dot( m_viewdir, vector3_normalised( m_points[1].m_point - m_points[0].m_point ) ) ) > 0.999 ){ const Matrix4 screen2world( matrix4_full_inverse( m_view->GetViewMatrix() ) ); @@ -4588,8 +4594,8 @@ public: void viewdir_make_cut_worthy( const Plane3& plane ){ const std::size_t maxi = vector3_max_abs_component_index( plane.normal() ); if( plane3_valid( plane ) - && aabb_valid( m_bounds ) - && fabs( plane.normal()[maxi] ) > 0.999 ){ //axial plane + && aabb_valid( m_bounds ) + && fabs( plane.normal()[maxi] ) > 0.999 ){ //axial plane const double anchor = plane.normal()[maxi] * plane.dist(); if( anchor > m_bounds.origin[maxi] ){ if( ( anchor - ( m_bounds.origin[maxi] + m_bounds.extents[maxi] ) ) > -0.1 ) @@ -4615,14 +4621,14 @@ public: Clipper_setPlanePoints( ClipperPoints( m_points[0].m_point, m_points[0].m_point, m_points[0].m_point, npoints ) ); break; case 2: - { - if( m_view->fill() ){ //3d - viewdir_fixup(); + { + if( m_view->fill() ){ //3d + viewdir_fixup(); + m_points[2].m_point = m_points[0].m_point - m_viewdir * vector3_length( m_points[0].m_point - m_points[1].m_point ); + viewdir_make_cut_worthy( plane3_for_points( m_points[0].m_point, m_points[1].m_point, m_points[2].m_point ) ); + } m_points[2].m_point = m_points[0].m_point - m_viewdir * vector3_length( m_points[0].m_point - m_points[1].m_point ); - viewdir_make_cut_worthy( plane3_for_points( m_points[0].m_point, m_points[1].m_point, m_points[2].m_point ) ); - } - m_points[2].m_point = m_points[0].m_point - m_viewdir * vector3_length( m_points[0].m_point - m_points[1].m_point ); - } // fall through + } // fall through case 3: Clipper_setPlanePoints( ClipperPoints( m_points[0].m_point, m_points[1].m_point, m_points[2].m_point, npoints ) ); break; @@ -5131,9 +5137,9 @@ private: } bool projection_valid() const { return !( !std::isfinite( m_local2tex[0] ) //nan - || fabs( vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) ) < 1e-6 //projected along face - || vector3_length_squared( vector4_to_vector3( m_tex2local.x() ) ) < .01 //srsly scaled down, limit at max 10 textures per world unit - || vector3_length_squared( vector4_to_vector3( m_tex2local.y() ) ) < .01 ); + || fabs( vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) ) < 1e-6 //projected along face + || vector3_length_squared( vector4_to_vector3( m_tex2local.x() ) ) < .01 //srsly scaled down, limit at max 10 textures per world unit + || vector3_length_squared( vector4_to_vector3( m_tex2local.y() ) ) < .01 ); } void UpdateFaceData( bool updateOrigin, bool updateLines = true ) { //!? todo fewer outer quads for large textures @@ -5160,7 +5166,7 @@ private: m_patchCtrl = m_patch->getControlPoints(); m_state_patch_raw = m_patch->getShader(); patchShaderConstruct(); - { //! todo force or deduce orthogonal uv axes for convenience + { //! todo force or deduce orthogonal uv axes for convenience Vector3 wDir, hDir; m_patch->Calculate_AvgAxes( wDir, hDir ); vector3_normalise( wDir ); @@ -5218,8 +5224,8 @@ private: p1 = &m_patch->ctrlAt( m_patchHeight - 1, col ); p2 = distW0 > distW1? &m_patch->ctrlAt( row, 0 ) : &m_patch->ctrlAt( row, m_patchWidth - 1 ); v0 = m_patch->localAABB().origin - + hDir * vector3_dot( m_patch->localAABB().extents, Vector3( fabs( hDir.x() ), fabs( hDir.y() ), fabs( hDir.z() ) ) ) * 1.1 - + wDir * ( distW0 - wLength / 2 ); + + hDir * vector3_dot( m_patch->localAABB().extents, Vector3( fabs( hDir.x() ), fabs( hDir.y() ), fabs( hDir.z() ) ) ) * 1.1 + + wDir * ( distW0 - wLength / 2 ); v1 = v0 + hDir * hLength; v2 = v0 + hDir * distH0 + ( distW0 > distW1? ( wDir * -distW0 ) : ( wDir * distW1 ) ); } @@ -5228,8 +5234,8 @@ private: p1 = &m_patch->ctrlAt( row, m_patchWidth - 1 ); p2 = distH0 > distH1? &m_patch->ctrlAt( 0, col ) : &m_patch->ctrlAt( m_patchHeight - 1, col ); v0 = m_patch->localAABB().origin - + wDir * vector3_dot( m_patch->localAABB().extents, Vector3( fabs( wDir.x() ), fabs( wDir.y() ), fabs( wDir.z() ) ) ) * 1.1 - + hDir * ( distH0 - hLength / 2 ); + + wDir * vector3_dot( m_patch->localAABB().extents, Vector3( fabs( wDir.x() ), fabs( wDir.y() ), fabs( wDir.z() ) ) ) * 1.1 + + hDir * ( distH0 - hLength / 2 ); v1 = v0 + wDir * wLength; v2 = v0 + wDir * distW0 + ( distH0 > distH1? ( hDir * -distH0 ) : ( hDir * distH1 ) ); } @@ -5241,8 +5247,8 @@ private: } const DoubleVector3 vertices[3]{ v0, v1, v2 }; const DoubleVector3 sts[3]{ DoubleVector3( p0->m_texcoord ), - DoubleVector3( p1->m_texcoord ), - DoubleVector3( p2->m_texcoord ) }; + DoubleVector3( p1->m_texcoord ), + DoubleVector3( p2->m_texcoord ) }; Texdef_Construct_local2tex_from_ST( vertices, sts, m_local2tex ); m_tex2local = matrix4_affine_inverse( m_local2tex ); } @@ -5263,11 +5269,11 @@ private: vector4_to_vector3( m_faceTex2local.x() ) = plane3_project_point( Plane3( m_plane.normal(), 0 ), vector4_to_vector3( m_tex2local.x() ), vector4_to_vector3( m_tex2local.z() ) ); vector4_to_vector3( m_faceTex2local.y() ) = plane3_project_point( Plane3( m_plane.normal(), 0 ), vector4_to_vector3( m_tex2local.y() ), vector4_to_vector3( m_tex2local.z() ) ); m_faceTex2local = matrix4_multiplied_by_matrix4( // adjust to have UV's z = 0: move the plane along m_tex2local.z() so that plane.dist() = 0 - matrix4_translation_for_vec3( - vector4_to_vector3( m_tex2local.z() ) * ( m_plane.dist() - vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.t() ) ) ) - / vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) - ), - m_faceTex2local ); + matrix4_translation_for_vec3( + vector4_to_vector3( m_tex2local.z() ) * ( m_plane.dist() - vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.t() ) ) ) + / vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) + ), + m_faceTex2local ); m_faceLocal2tex = matrix4_affine_inverse( m_faceTex2local ); if( m_patch ){ @@ -5360,15 +5366,15 @@ private: const Vector3 uv_origin = matrix4_transformed_point( m_faceLocal2tex, m_origin ); - { // grid grain controls, on the polygon side of origin + { // grid grain controls, on the polygon side of origin m_gridSign.x() = max.y() - uv_origin.y() >= uv_origin.y() - min.y()? 1 : -1; m_gridSign.y() = max.x() - uv_origin.x() >= uv_origin.x() - min.x()? 1 : -1; m_gridPointU.m_point.vertex = Vertex3f( uv_origin.x(), - float_to_integer( uv_origin.y() + m_gridSign.x() * .25 ) + m_gridSign.x() * ( 1 - 1.0 / std::max( float( m_gridU ), 1.8f ) ), - 0 ); + float_to_integer( uv_origin.y() + m_gridSign.x() * .25 ) + m_gridSign.x() * ( 1 - 1.0 / std::max( float( m_gridU ), 1.8f ) ), + 0 ); m_gridPointV.m_point.vertex = Vertex3f( float_to_integer( uv_origin.x() + m_gridSign.y() * .25 ) + m_gridSign.y() * ( 1 - 1.0 / std::max( float( m_gridV ), 1.8f ) ), - uv_origin.y(), - 0 ); + uv_origin.y(), + 0 ); } m_pivot2world = m_tex2local; @@ -5436,11 +5442,11 @@ private: } } { - { // u pivot line + { // u pivot line m_pivotLines.m_lines[0].vertex = Vertex3f( min.x(), uv_origin.y(), 0 ); m_pivotLines.m_lines[1].vertex = Vertex3f( max.x(), uv_origin.y(), 0 ); } - { // v pivot line + { // v pivot line m_pivotLines.m_lines[2].vertex = Vertex3f( uv_origin.x(), min.y(), 0 ); m_pivotLines.m_lines[3].vertex = Vertex3f( uv_origin.x(), max.y(), 0 ); } @@ -5455,8 +5461,8 @@ private: UpdateFaceData( true ); } else if( memcmp( &m_projection, &m_face->getTexdef().m_projection, sizeof( TextureProjection ) ) != 0 - || m_width != m_face->getShader().width() - || m_height != m_face->getShader().height() ) { + || m_width != m_face->getShader().width() + || m_height != m_face->getShader().height() ) { UpdateFaceData( false ); } return projection_valid(); @@ -5470,9 +5476,9 @@ private: UpdateFaceData( true ); } else if( m_patchWidth != m_patch->getWidth() - || m_patchHeight != m_patch->getHeight() - || memcmp( m_patchCtrl.data(), m_patch->getControlPoints().data(), sizeof( *m_patchCtrl.data() ) * m_patchCtrl.size() ) != 0 - || m_state_patch_raw != m_patch->getShader() ){ + || m_patchHeight != m_patch->getHeight() + || memcmp( m_patchCtrl.data(), m_patch->getControlPoints().data(), sizeof( *m_patchCtrl.data() ) * m_patchCtrl.size() ) != 0 + || m_state_patch_raw != m_patch->getShader() ){ UpdateFaceData( false ); } return projection_valid(); @@ -5516,7 +5522,7 @@ public: } UVSelector selector; - { // try pivot point + { // try pivot point const Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot2world ) ); SelectionIntersection best; Point_BestPoint( local2view, m_pivotPoint.m_point.vertex, best ); @@ -5591,17 +5597,17 @@ V line center| - - tex U center - - // better picking of tex, only line for skew or scale with dense grid const Matrix4 screen2world( matrix4_full_inverse( view.GetViewMatrix() ) ); const DoubleRay ray = ray_for_points( vector4_projected( matrix4_transformed_vector4( screen2world, BasicVector4( 0, 0, -1, 1 ) ) ), - vector4_projected( matrix4_transformed_vector4( screen2world, BasicVector4( 0, 0, 1, 1 ) ) ) ); + vector4_projected( matrix4_transformed_vector4( screen2world, BasicVector4( 0, 0, 1, 1 ) ) ) ); const DoubleVector3 hit = ray_intersect_plane( ray, m_plane ); const Vector3 uvhit = matrix4_transformed_point( m_faceLocal2tex, hit ); if( fabs( vector3_dot( ray.direction, m_plane.normal() ) ) > 1e-6 - && !m_Ulines.m_lines.empty() - && !m_Vlines.m_lines.empty() - && matrix4_transformed_vector4( view.GetViewMatrix(), Vector4( hit, 1 ) ).w() > 0 ){ + && !m_Ulines.m_lines.empty() + && !m_Vlines.m_lines.empty() + && matrix4_transformed_vector4( view.GetViewMatrix(), Vector4( hit, 1 ) ).w() > 0 ){ PointVertex* closestU = &m_Ulines.m_lines[std::min( m_Ulines.m_lines.size() - 2, - static_cast( float_to_integer( std::max( 0.f, uvhit.y() - m_Ulines.m_lines.front().vertex.y() ) * m_gridU ) * 2 ) )]; + static_cast( float_to_integer( std::max( 0.f, uvhit.y() - m_Ulines.m_lines.front().vertex.y() ) * m_gridU ) * 2 ) )]; PointVertex* closestV = &m_Vlines.m_lines[std::min( m_Vlines.m_lines.size() - 2, - static_cast( float_to_integer( std::max( 0.f, uvhit.x() - m_Vlines.m_lines.front().vertex.x() ) * m_gridV ) * 2 ) )]; + static_cast( float_to_integer( std::max( 0.f, uvhit.x() - m_Vlines.m_lines.front().vertex.x() ) * m_gridV ) * 2 ) )]; const Vector2 sign( uvhit.y() > closestU->vertex.y()? 1 : -1, uvhit.x() > closestV->vertex.x()? 1 : -1 ); //hit in positive or negative part of lines u, v const PointVertex pCross( Vertex3f( closestV->vertex.x(), closestU->vertex.y(), 0 ) ); const PointVertex pUcenter( Vertex3f( closestV->vertex.x() + sign.y() / ( m_gridV * 2 ), closestU->vertex.y(), 0 ) ); @@ -5687,9 +5693,9 @@ V line center| - - tex U center - - private: void applySelection( EUVSelection selection, PointVertex* selectedU, PointVertex* selectedV, int selectedPatchIndex ){ if( m_selection != selection - || m_selectedU != selectedU - || m_selectedV != selectedV - || m_selectedPatchIndex != selectedPatchIndex ){ + || m_selectedU != selectedU + || m_selectedV != selectedV + || m_selectedPatchIndex != selectedPatchIndex ){ if( m_selection != selection ){ switch ( m_selection ) { @@ -6044,17 +6050,17 @@ public: Matrix4 rot = g_matrix4_identity; if( snap ){ matrix4_pivoted_rotate_by_axisangle( rot, - vector4_to_vector3( m_tex2local.z() ), - float_snapped( angle_for_axis( from, to, vector4_to_vector3( m_tex2local.z() ) ), static_cast( c_pi / 12.0 ) ), - m_origin ); + vector4_to_vector3( m_tex2local.z() ), + float_snapped( angle_for_axis( from, to, vector4_to_vector3( m_tex2local.z() ) ), static_cast( c_pi / 12.0 ) ), + m_origin ); } else{ matrix4_pivoted_rotate_by_axisangle( rot, - vector4_to_vector3( m_tex2local.z() ), - angle_for_axis( from, to, vector4_to_vector3( m_tex2local.z() ) ), - m_origin ); + vector4_to_vector3( m_tex2local.z() ), + angle_for_axis( from, to, vector4_to_vector3( m_tex2local.z() ) ), + m_origin ); } - { // snap + { // snap const Vector3 uvec = vector3_normalised( matrix4_transformed_direction( rot, vector4_to_vector3( m_tex2local.x() ) ) ); const Vector3 vvec = vector3_normalised( matrix4_transformed_direction( rot, vector4_to_vector3( m_tex2local.y() ) ) ); float bestDot = 0; @@ -6080,9 +6086,9 @@ public: const Vector3 bestFrom = vector3_normalised( vector4_to_vector3( V? m_tex2local.y() : m_tex2local.x() ) ); rot = g_matrix4_identity; matrix4_pivoted_rotate_by_axisangle( rot, - vector4_to_vector3( m_tex2local.z() ), - angle_for_axis( bestFrom, bestTo, vector4_to_vector3( m_tex2local.z() ) ), - m_origin ); + vector4_to_vector3( m_tex2local.z() ), + angle_for_axis( bestFrom, bestTo, vector4_to_vector3( m_tex2local.z() ) ), + m_origin ); } } @@ -6090,11 +6096,11 @@ public: vector4_to_vector3( faceTex2local.x() ) = plane3_project_point( Plane3( m_plane.normal(), 0 ), vector4_to_vector3( faceTex2local.x() ), vector4_to_vector3( m_tex2local.z() ) ); vector4_to_vector3( faceTex2local.y() ) = plane3_project_point( Plane3( m_plane.normal(), 0 ), vector4_to_vector3( faceTex2local.y() ), vector4_to_vector3( m_tex2local.z() ) ); faceTex2local = matrix4_multiplied_by_matrix4( // adjust to have UV's z = 0: move the plane along m_tex2local.z() so that plane.dist() = 0 - matrix4_translation_for_vec3( - vector4_to_vector3( m_tex2local.z() ) * ( m_plane.dist() - vector3_dot( m_plane.normal(), vector4_to_vector3( faceTex2local.t() ) ) ) - / vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) - ), - faceTex2local ); + matrix4_translation_for_vec3( + vector4_to_vector3( m_tex2local.z() ) * ( m_plane.dist() - vector3_dot( m_plane.normal(), vector4_to_vector3( faceTex2local.t() ) ) ) + / vector3_dot( m_plane.normal(), vector4_to_vector3( m_tex2local.z() ) ) + ), + faceTex2local ); m_lines2world = m_pivotLines2world = faceTex2local; m_pivot2world = matrix4_multiplied_by_matrix4( rot, m_pivot2world0 ); @@ -6187,8 +6193,8 @@ public: const Vector3 uv_origin = matrix4_transformed_point( m_local2tex, m_origin ); const Vector3 uv_start{ m_selectedV->vertex.x(), m_selectedU->vertex.y(), 0 } ; const Vector3 uv_current{ ( m_selectedV->vertex + matrix4_transformed_point( m_local2tex, current ) - matrix4_transformed_point( m_local2tex, m_start ) ).x(), - ( m_selectedU->vertex + matrix4_transformed_point( m_local2tex, current ) - matrix4_transformed_point( m_local2tex, m_start ) ).y(), - 0 }; + ( m_selectedU->vertex + matrix4_transformed_point( m_local2tex, current ) - matrix4_transformed_point( m_local2tex, m_start ) ).y(), + 0 }; float bestDistU = FLT_MAX; float snapToU = 0; float bestDistV = FLT_MAX; @@ -6224,7 +6230,7 @@ public: /* prevent scaling to 0, limit at max 10 textures per world unit */ if( vector3_length_squared( vector4_to_vector3( m_tex2local.x() ) * result.x() ) < .01 || - vector3_length_squared( vector4_to_vector3( m_tex2local.y() ) * result.y() ) < .01 ) + vector3_length_squared( vector4_to_vector3( m_tex2local.y() ) * result.y() ) < .01 ) return; Matrix4 scale = g_matrix4_identity; @@ -6248,21 +6254,21 @@ public: skew[4] = uv_move.x() / ( m_selectedU->vertex - uv_origin ).y(); Matrix4 scale = matrix4_scale_for_vec3( // scale snap measurement space so that x/y = 1 - Vector3( vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) / vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ), - 1, 1 ) ); + Vector3( vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) / vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ), + 1, 1 ) ); const Vector3 skewed = vector3_normalised( matrix4_transformed_direction( matrix4_multiplied_by_matrix4( scale, skew ), g_vector3_axis_y ) ); matrix4_multiply_by_matrix4( scale, m_faceLocal2tex ); float bestDot = 0; Vector3 bestTo; forEachEdge( [&]( const Vector3& point0, const Vector3& point1 ){ const Vector3 vec( vector3_normalised( matrix4_transformed_point( scale, point1 ) - - matrix4_transformed_point( scale, point0 ) ) ); + matrix4_transformed_point( scale, point0 ) ) ); const float dot = fabs( vector3_dot( skewed, vec ) ); if( dot > bestDot - && fabs( vector3_dot( vec, g_vector3_axis_x ) ) < 0.99999 ){ // don't snap so, that one axis = the other + && fabs( vector3_dot( vec, g_vector3_axis_x ) ) < 0.99999 ){ // don't snap so, that one axis = the other bestDot = dot; const Vector3 vecTo( vector3_normalised( matrix4_transformed_point( m_faceLocal2tex, point1 ) - - matrix4_transformed_point( m_faceLocal2tex, point0 ) ) ); + matrix4_transformed_point( m_faceLocal2tex, point0 ) ) ); bestTo = vector3_dot( skewed, vec ) > 0? vecTo : -vecTo; } } ); @@ -6294,21 +6300,21 @@ public: skew[1] = uv_move.y() / ( m_selectedV->vertex - uv_origin ).x(); Matrix4 scale = matrix4_scale_for_vec3( // scale snap measurement space so that x/y = 1 - Vector3( vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) / vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ), - 1, 1 ) ); + Vector3( vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) / vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ), + 1, 1 ) ); const Vector3 skewed = vector3_normalised( matrix4_transformed_direction( matrix4_multiplied_by_matrix4( scale, skew ), g_vector3_axis_x ) ); matrix4_multiply_by_matrix4( scale, m_faceLocal2tex ); float bestDot = 0; Vector3 bestTo; forEachEdge( [&]( const Vector3& point0, const Vector3& point1 ){ const Vector3 vec( vector3_normalised( matrix4_transformed_point( scale, point1 ) - - matrix4_transformed_point( scale, point0 ) ) ); + matrix4_transformed_point( scale, point0 ) ) ); const float dot = fabs( vector3_dot( skewed, vec ) ); if( dot > bestDot - && fabs( vector3_dot( vec, g_vector3_axis_y ) ) < 0.99999 ){ // don't snap so, that one axis = the other + && fabs( vector3_dot( vec, g_vector3_axis_y ) ) < 0.99999 ){ // don't snap so, that one axis = the other bestDot = dot; const Vector3 vecTo( vector3_normalised( matrix4_transformed_point( m_faceLocal2tex, point1 ) - - matrix4_transformed_point( m_faceLocal2tex, point0 ) ) ); + matrix4_transformed_point( m_faceLocal2tex, point0 ) ) ); bestTo = vector3_dot( skewed, vec ) > 0? vecTo : -vecTo; } } ); @@ -6371,7 +6377,7 @@ public: if( snap ){ auto& smaller = fabs( uvmove.x() * vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) ) < - fabs( uvmove.y() * vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ) )? result.x() : result.y(); + fabs( uvmove.y() * vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ) )? result.x() : result.y(); smaller = 0; } @@ -6448,7 +6454,7 @@ public: if( snap ){ auto& smaller = fabs( uvmove.x() * vector3_length( vector4_to_vector3( m_faceTex2local.x() ) ) ) < - fabs( uvmove.y() * vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ) )? result.x() : result.y(); + fabs( uvmove.y() * vector3_length( vector4_to_vector3( m_faceTex2local.y() ) ) )? result.x() : result.y(); smaller = 0; } @@ -6488,15 +6494,15 @@ public: void freezeTransform(){ if( m_selection == eCircle - || m_selection == eU - || m_selection == eV - || m_selection == eUV - || m_selection == eSkewU - || m_selection == eSkewV - || m_selection == eTex - || m_selection == ePatchPoint - || m_selection == ePatchRow - || m_selection == ePatchColumn ) + || m_selection == eU + || m_selection == eV + || m_selection == eUV + || m_selection == eSkewU + || m_selection == eSkewV + || m_selection == eTex + || m_selection == ePatchPoint + || m_selection == ePatchRow + || m_selection == ePatchColumn ) { if( m_face ) m_face->freezeTransform(); @@ -6526,47 +6532,47 @@ Shader* UVManipulator::m_state_point; class TransformOriginTranslatable { public: -virtual void transformOriginTranslate( const Vector3& translation, const bool set[3] ) = 0; + virtual void transformOriginTranslate( const Vector3& translation, const bool set[3] ) = 0; }; class TransformOriginTranslate : public Manipulatable { private: -Vector3 m_start; -TransformOriginTranslatable& m_transformOriginTranslatable; + Vector3 m_start; + TransformOriginTranslatable& m_transformOriginTranslatable; public: -TransformOriginTranslate( TransformOriginTranslatable& transformOriginTranslatable ) - : m_transformOriginTranslatable( transformOriginTranslatable ){ -} -void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ - m_start = point_on_plane( device2manip, x, y ); -} -void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ - Vector3 current = point_on_plane( device2manip, x, y ); - current = vector3_subtracted( current, m_start ); + TransformOriginTranslate( TransformOriginTranslatable& transformOriginTranslatable ) + : m_transformOriginTranslatable( transformOriginTranslatable ){ + } + void Construct( const Matrix4& device2manip, const float x, const float y, const AABB& bounds, const Vector3& transform_origin ){ + m_start = point_on_plane( device2manip, x, y ); + } + void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox, const bool alt ){ + Vector3 current = point_on_plane( device2manip, x, y ); + current = vector3_subtracted( current, m_start ); - if( snap ){ + if( snap ){ + for ( std::size_t i = 0; i < 3 ; ++i ){ + if( fabs( current[i] ) >= fabs( current[(i + 1) % 3] ) ){ + current[(i + 1) % 3] = 0.f; + } + else{ + current[i] = 0.f; + } + } + } + + bool set[3] = { true, true, true }; for ( std::size_t i = 0; i < 3 ; ++i ){ - if( fabs( current[i] ) >= fabs( current[(i + 1) % 3] ) ){ - current[(i + 1) % 3] = 0.f; - } - else{ - current[i] = 0.f; + if( fabs( current[i] ) < 1e-3f ){ + set[i] = false; } } + + current = translation_local2object( current, manip2object ); + + m_transformOriginTranslatable.transformOriginTranslate( current, set ); } - - bool set[3] = { true, true, true }; - for ( std::size_t i = 0; i < 3 ; ++i ){ - if( fabs( current[i] ) < 1e-3f ){ - set[i] = false; - } - } - - current = translation_local2object( current, manip2object ); - - m_transformOriginTranslatable.transformOriginTranslate( current, set ); -} }; class TransformOriginManipulator : public Manipulator, public ManipulatorSelectionChangeable @@ -6656,35 +6662,35 @@ Shader* TransformOriginManipulator::m_state; class select_all : public scene::Graph::Walker { -bool m_select; + bool m_select; public: -select_all( bool select ) - : m_select( select ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable != 0 ) { - selectable->setSelected( m_select ); + select_all( bool select ) + : m_select( select ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable != 0 ) { + selectable->setSelected( m_select ); + } + return true; } - return true; -} }; class select_all_component : public scene::Graph::Walker { -bool m_select; -SelectionSystem::EComponentMode m_mode; + bool m_select; + SelectionSystem::EComponentMode m_mode; public: -select_all_component( bool select, SelectionSystem::EComponentMode mode ) - : m_select( select ), m_mode( mode ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); - if ( componentSelectionTestable ) { - componentSelectionTestable->setSelectedComponents( m_select, m_mode ); + select_all_component( bool select, SelectionSystem::EComponentMode mode ) + : m_select( select ), m_mode( mode ){ + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); + if ( componentSelectionTestable ) { + componentSelectionTestable->setSelectedComponents( m_select, m_mode ); + } + return true; } - return true; -} }; void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode componentMode ){ @@ -6722,811 +6728,811 @@ class RadiantSelectionSystem final : public TransformOriginTranslatable, public Renderable { -mutable Matrix4 m_pivot2world; -mutable AABB m_bounds; -mutable LazyBounds m_lazy_bounds; -Matrix4 m_pivot2world_start; -Matrix4 m_manip2pivot_start; -Translation m_translation; -Rotation m_rotation; -Scale m_scale; -Skew m_skew; + mutable Matrix4 m_pivot2world; + mutable AABB m_bounds; + mutable LazyBounds m_lazy_bounds; + Matrix4 m_pivot2world_start; + Matrix4 m_manip2pivot_start; + Translation m_translation; + Rotation m_rotation; + Scale m_scale; + Skew m_skew; public: -static Shader* m_state; -bool m_bPreferPointEntsIn2D; + static Shader* m_state; + bool m_bPreferPointEntsIn2D; private: -EManipulatorMode m_manipulator_mode; -Manipulator* m_manipulator; + EManipulatorMode m_manipulator_mode; + Manipulator* m_manipulator; // state -bool m_undo_begun; -EMode m_mode; -EComponentMode m_componentmode; + bool m_undo_begun; + EMode m_mode; + EComponentMode m_componentmode; -SelectionCounter m_count_primitive; -SelectionCounter m_count_component; -SelectedStuffCounter m_count_stuff; + SelectionCounter m_count_primitive; + SelectionCounter m_count_component; + SelectedStuffCounter m_count_stuff; -TranslateManipulator m_translate_manipulator; -RotateManipulator m_rotate_manipulator; -ScaleManipulator m_scale_manipulator; -SkewManipulator m_skew_manipulator; -DragManipulator m_drag_manipulator; -ClipManipulator m_clip_manipulator; -BuildManipulator m_build_manipulator; -UVManipulator m_uv_manipulator; -mutable TransformOriginManipulator m_transformOrigin_manipulator; + TranslateManipulator m_translate_manipulator; + RotateManipulator m_rotate_manipulator; + ScaleManipulator m_scale_manipulator; + SkewManipulator m_skew_manipulator; + DragManipulator m_drag_manipulator; + ClipManipulator m_clip_manipulator; + BuildManipulator m_build_manipulator; + UVManipulator m_uv_manipulator; + mutable TransformOriginManipulator m_transformOrigin_manipulator; -typedef SelectionList selection_t; -selection_t m_selection; -selection_t m_component_selection; + typedef SelectionList selection_t; + selection_t m_selection; + selection_t m_component_selection; -Signal1 m_selectionChanged_callbacks; + Signal1 m_selectionChanged_callbacks; -void ConstructPivot() const; -void ConstructPivotRotation() const; -void setCustomTransformOrigin( const Vector3& origin, const bool set[3] ) const; -AABB getSelectionAABB() const; -mutable bool m_pivotChanged; -bool m_pivot_moving; -mutable bool m_pivotIsCustom; + void ConstructPivot() const; + void ConstructPivotRotation() const; + void setCustomTransformOrigin( const Vector3& origin, const bool set[3] ) const; + AABB getSelectionAABB() const; + mutable bool m_pivotChanged; + bool m_pivot_moving; + mutable bool m_pivotIsCustom; -void Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode ); + void Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode ); -bool nothingSelected() const { - return ( Mode() == eComponent && m_count_component.empty() ) - || ( Mode() == ePrimitive && m_count_primitive.empty() ); -} + bool nothingSelected() const { + return ( Mode() == eComponent && m_count_component.empty() ) + || ( Mode() == ePrimitive && m_count_primitive.empty() ); + } public: -enum EModifier -{ - eManipulator, - eReplace, - eCycle, - eSelect, - eDeselect, -}; + enum EModifier + { + eManipulator, + eReplace, + eCycle, + eSelect, + eDeselect, + }; -RadiantSelectionSystem() : - m_bPreferPointEntsIn2D( true ), - m_undo_begun( false ), - m_mode( ePrimitive ), - m_componentmode( eDefault ), - m_count_primitive( SelectionChangedCaller( *this ) ), - m_count_component( SelectionChangedCaller( *this ) ), - m_translate_manipulator( *this, 2, 64 ), - m_rotate_manipulator( *this, 8, 64 ), - m_scale_manipulator( *this, 0, 64 ), - m_skew_manipulator( *this, *this, *this, *this, m_bounds, m_pivot2world, m_pivotIsCustom ), - m_drag_manipulator( *this ), - m_clip_manipulator( m_pivot2world, m_bounds ), - m_transformOrigin_manipulator( *this, m_pivotIsCustom ), - m_pivotChanged( false ), - m_pivot_moving( false ), - m_pivotIsCustom( false ){ - SetManipulatorMode( eTranslate ); - pivotChanged(); - addSelectionChangeCallback( PivotChangedSelectionCaller( *this ) ); - AddGridChangeCallback( PivotChangedCaller( *this ) ); -} -void pivotChanged() const { - m_pivotChanged = true; - m_lazy_bounds.setInvalid(); - SceneChangeNotify(); -} -typedef ConstMemberCaller PivotChangedCaller; -void pivotChangedSelection( const Selectable& selectable ){ - pivotChanged(); -} -typedef MemberCaller1 PivotChangedSelectionCaller; - -const AABB& getBoundsSelected() const { - return m_lazy_bounds.getBounds(); -} - -void SetMode( EMode mode ){ - if ( m_mode != mode ) { - m_mode = mode; + RadiantSelectionSystem() : + m_bPreferPointEntsIn2D( true ), + m_undo_begun( false ), + m_mode( ePrimitive ), + m_componentmode( eDefault ), + m_count_primitive( SelectionChangedCaller( *this ) ), + m_count_component( SelectionChangedCaller( *this ) ), + m_translate_manipulator( *this, 2, 64 ), + m_rotate_manipulator( *this, 8, 64 ), + m_scale_manipulator( *this, 0, 64 ), + m_skew_manipulator( *this, *this, *this, *this, m_bounds, m_pivot2world, m_pivotIsCustom ), + m_drag_manipulator( *this ), + m_clip_manipulator( m_pivot2world, m_bounds ), + m_transformOrigin_manipulator( *this, m_pivotIsCustom ), + m_pivotChanged( false ), + m_pivot_moving( false ), + m_pivotIsCustom( false ){ + SetManipulatorMode( eTranslate ); + pivotChanged(); + addSelectionChangeCallback( PivotChangedSelectionCaller( *this ) ); + AddGridChangeCallback( PivotChangedCaller( *this ) ); + } + void pivotChanged() const { + m_pivotChanged = true; + m_lazy_bounds.setInvalid(); + SceneChangeNotify(); + } + typedef ConstMemberCaller PivotChangedCaller; + void pivotChangedSelection( const Selectable& selectable ){ pivotChanged(); } -} -EMode Mode() const { - return m_mode; -} -void SetComponentMode( EComponentMode mode ){ - m_componentmode = mode; -} -EComponentMode ComponentMode() const { - return m_componentmode; -} -void SetManipulatorMode( EManipulatorMode mode ){ - if( ( mode == eClip ) || ( ManipulatorMode() == eClip ) ){ - m_clip_manipulator.reset( ( mode == eClip ) && ( ManipulatorMode() != eClip ) ); - if( ( mode == eClip ) != ( ManipulatorMode() == eClip ) ) - Clipper_modeChanged( mode == eClip ); + typedef MemberCaller1 PivotChangedSelectionCaller; + + const AABB& getBoundsSelected() const { + return m_lazy_bounds.getBounds(); } - m_pivotIsCustom = false; - m_manipulator_mode = mode; - switch ( m_manipulator_mode ) - { - case eTranslate: m_manipulator = &m_translate_manipulator; break; - case eRotate: m_manipulator = &m_rotate_manipulator; break; - case eScale: m_manipulator = &m_scale_manipulator; break; - case eSkew: m_manipulator = &m_skew_manipulator; break; - case eDrag: m_manipulator = &m_drag_manipulator; break; - case eClip: m_manipulator = &m_clip_manipulator; m_repeatableTransforms.setIdentity(); break; - case eBuild: - { - m_build_manipulator.initialise(); - m_manipulator = &m_build_manipulator; break; + void SetMode( EMode mode ){ + if ( m_mode != mode ) { + m_mode = mode; + pivotChanged(); } - case eUV: m_manipulator = &m_uv_manipulator; break; } - pivotChanged(); -} -EManipulatorMode ManipulatorMode() const { - return m_manipulator_mode; -} + EMode Mode() const { + return m_mode; + } + void SetComponentMode( EComponentMode mode ){ + m_componentmode = mode; + } + EComponentMode ComponentMode() const { + return m_componentmode; + } + void SetManipulatorMode( EManipulatorMode mode ){ + if( ( mode == eClip ) || ( ManipulatorMode() == eClip ) ){ + m_clip_manipulator.reset( ( mode == eClip ) && ( ManipulatorMode() != eClip ) ); + if( ( mode == eClip ) != ( ManipulatorMode() == eClip ) ) + Clipper_modeChanged( mode == eClip ); + } -SelectionChangeCallback getObserver( EMode mode ){ - if ( mode == ePrimitive ) { - return makeCallback1( m_count_primitive ); + m_pivotIsCustom = false; + m_manipulator_mode = mode; + switch ( m_manipulator_mode ) + { + case eTranslate: m_manipulator = &m_translate_manipulator; break; + case eRotate: m_manipulator = &m_rotate_manipulator; break; + case eScale: m_manipulator = &m_scale_manipulator; break; + case eSkew: m_manipulator = &m_skew_manipulator; break; + case eDrag: m_manipulator = &m_drag_manipulator; break; + case eClip: m_manipulator = &m_clip_manipulator; m_repeatableTransforms.setIdentity(); break; + case eBuild: + { + m_build_manipulator.initialise(); + m_manipulator = &m_build_manipulator; break; + } + case eUV: m_manipulator = &m_uv_manipulator; break; + } + pivotChanged(); } - else - { - return makeCallback1( m_count_component ); - } -} -std::size_t countSelected() const { - return m_count_primitive.size(); -} -std::size_t countSelectedComponents() const { - return m_count_component.size(); -} -void countSelectedStuff( std::size_t& brushes, std::size_t& patches, std::size_t& entities ) const { - m_count_stuff.get( brushes, patches, entities ); -} -void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ){ - if ( selectable.isSelected() ) { - m_selection.append( instance ); - m_count_stuff.increment( instance.path().top() ); - } - else - { - m_selection.erase( instance ); - m_count_stuff.decrement( instance.path().top() ); + EManipulatorMode ManipulatorMode() const { + return m_manipulator_mode; } - ASSERT_MESSAGE( m_selection.size() == m_count_primitive.size(), "selection-tracking error" ); -} -void onComponentSelection( scene::Instance& instance, const Selectable& selectable ){ - if ( selectable.isSelected() ) { - m_component_selection.append( instance ); + SelectionChangeCallback getObserver( EMode mode ){ + if ( mode == ePrimitive ) { + return makeCallback1( m_count_primitive ); + } + else + { + return makeCallback1( m_count_component ); + } } - else - { - m_component_selection.erase( instance ); + std::size_t countSelected() const { + return m_count_primitive.size(); + } + std::size_t countSelectedComponents() const { + return m_count_component.size(); + } + void countSelectedStuff( std::size_t& brushes, std::size_t& patches, std::size_t& entities ) const { + m_count_stuff.get( brushes, patches, entities ); + } + void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ){ + if ( selectable.isSelected() ) { + m_selection.append( instance ); + m_count_stuff.increment( instance.path().top() ); + } + else + { + m_selection.erase( instance ); + m_count_stuff.decrement( instance.path().top() ); + } + + ASSERT_MESSAGE( m_selection.size() == m_count_primitive.size(), "selection-tracking error" ); + } + void onComponentSelection( scene::Instance& instance, const Selectable& selectable ){ + if ( selectable.isSelected() ) { + m_component_selection.append( instance ); + } + else + { + m_component_selection.erase( instance ); + } + + ASSERT_MESSAGE( m_component_selection.size() == m_count_component.size(), "selection-tracking error" ); + } + scene::Instance& firstSelected() const { + ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" ); + return **m_selection.begin(); + } + scene::Instance& ultimateSelected() const { + ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" ); + return m_selection.back(); + } + scene::Instance& penultimateSelected() const { + ASSERT_MESSAGE( m_selection.size() > 1, "only one instance selected" ); + return *( *( --( --m_selection.end() ) ) ); + } + void setSelectedAll( bool selected ){ + GlobalSceneGraph().traverse( select_all( selected ) ); + + m_manipulator->setSelected( selected ); + } + void setSelectedAllComponents( bool selected ){ + Scene_SelectAll_Component( selected, SelectionSystem::eVertex ); + Scene_SelectAll_Component( selected, SelectionSystem::eEdge ); + Scene_SelectAll_Component( selected, SelectionSystem::eFace ); + + m_manipulator->setSelected( selected ); } - ASSERT_MESSAGE( m_component_selection.size() == m_count_component.size(), "selection-tracking error" ); -} -scene::Instance& firstSelected() const { - ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" ); - return **m_selection.begin(); -} -scene::Instance& ultimateSelected() const { - ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" ); - return m_selection.back(); -} -scene::Instance& penultimateSelected() const { - ASSERT_MESSAGE( m_selection.size() > 1, "only one instance selected" ); - return *( *( --( --m_selection.end() ) ) ); -} -void setSelectedAll( bool selected ){ - GlobalSceneGraph().traverse( select_all( selected ) ); - - m_manipulator->setSelected( selected ); -} -void setSelectedAllComponents( bool selected ){ - Scene_SelectAll_Component( selected, SelectionSystem::eVertex ); - Scene_SelectAll_Component( selected, SelectionSystem::eEdge ); - Scene_SelectAll_Component( selected, SelectionSystem::eFace ); - - m_manipulator->setSelected( selected ); -} - -void foreachSelected( const Visitor& visitor ) const { - selection_t::const_iterator i = m_selection.begin(); - while ( i != m_selection.end() ) - { - visitor.visit( *( *( i++ ) ) ); + void foreachSelected( const Visitor& visitor ) const { + selection_t::const_iterator i = m_selection.begin(); + while ( i != m_selection.end() ) + { + visitor.visit( *( *( i++ ) ) ); + } } -} -void foreachSelectedComponent( const Visitor& visitor ) const { - selection_t::const_iterator i = m_component_selection.begin(); - while ( i != m_component_selection.end() ) - { - visitor.visit( *( *( i++ ) ) ); + void foreachSelectedComponent( const Visitor& visitor ) const { + selection_t::const_iterator i = m_component_selection.begin(); + while ( i != m_component_selection.end() ) + { + visitor.visit( *( *( i++ ) ) ); + } } -} -void addSelectionChangeCallback( const SelectionChangeHandler& handler ){ - m_selectionChanged_callbacks.connectLast( handler ); -} -void selectionChanged( const Selectable& selectable ){ - m_selectionChanged_callbacks( selectable ); -} -typedef MemberCaller1 SelectionChangedCaller; + void addSelectionChangeCallback( const SelectionChangeHandler& handler ){ + m_selectionChanged_callbacks.connectLast( handler ); + } + void selectionChanged( const Selectable& selectable ){ + m_selectionChanged_callbacks( selectable ); + } + typedef MemberCaller1 SelectionChangedCaller; -void startMove(){ - m_pivot2world_start = GetPivot2World(); -} + void startMove(){ + m_pivot2world_start = GetPivot2World(); + } -bool SelectManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){ - bool movingOrigin = false; + bool SelectManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){ + bool movingOrigin = false; - if ( !nothingSelected() || ManipulatorMode() == eDrag || ManipulatorMode() == eClip || ManipulatorMode() == eBuild || ManipulatorMode() == eUV ) { + if ( !nothingSelected() || ManipulatorMode() == eDrag || ManipulatorMode() == eClip || ManipulatorMode() == eBuild || ManipulatorMode() == eUV ) { #if defined ( DEBUG_SELECTION ) - g_render_clipped.destroy(); + g_render_clipped.destroy(); #endif + Manipulatable::assign_static( view, device_point, device_epsilon ); //this b4 m_manipulator calls! + + m_transformOrigin_manipulator.setSelected( false ); + m_manipulator->setSelected( false ); + + { + View scissored( view ); + ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); + + if( transformOrigin_isTranslatable() ){ + m_transformOrigin_manipulator.testSelect( scissored, GetPivot2World() ); + movingOrigin = m_transformOrigin_manipulator.isSelected(); + } + + if( !movingOrigin ) + m_manipulator->testSelect( scissored, GetPivot2World() ); + } + + startMove(); + + m_pivot_moving = m_manipulator->isSelected(); + + if ( m_pivot_moving || movingOrigin ) { + Pivot2World pivot; + pivot.update( GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport() ); + + m_manip2pivot_start = matrix4_multiplied_by_matrix4( matrix4_full_inverse( m_pivot2world_start ), pivot.m_worldSpace ); + + Matrix4 device2manip; + ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + if( m_pivot_moving ){ + m_manipulator->GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], m_bounds, vector4_to_vector3( GetPivot2World().t() ) ); + m_undo_begun = false; + } + else if( movingOrigin ){ + m_transformOrigin_manipulator.GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], m_bounds, vector4_to_vector3( GetPivot2World().t() ) ); + } + } + + SceneChangeNotify(); + } + + return m_pivot_moving || movingOrigin; + } + + void HighlightManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){ Manipulatable::assign_static( view, device_point, device_epsilon ); //this b4 m_manipulator calls! - m_transformOrigin_manipulator.setSelected( false ); - m_manipulator->setSelected( false ); + if ( ( !nothingSelected() && transformOrigin_isTranslatable() ) + || ManipulatorMode() == eClip + || ManipulatorMode() == eBuild + || ManipulatorMode() == eUV + || ManipulatorMode() == eDrag ) { +#if defined ( DEBUG_SELECTION ) + g_render_clipped.destroy(); +#endif + + m_transformOrigin_manipulator.setSelected( false ); + m_manipulator->setSelected( false ); - { View scissored( view ); ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); if( transformOrigin_isTranslatable() ){ m_transformOrigin_manipulator.testSelect( scissored, GetPivot2World() ); - movingOrigin = m_transformOrigin_manipulator.isSelected(); - } - if( !movingOrigin ) + if( !m_transformOrigin_manipulator.isSelected() ) + m_manipulator->testSelect( scissored, GetPivot2World() ); + } + else if( ManipulatorMode() == eClip ){ + m_clip_manipulator.testSelect_points( scissored ); + } + else if( ManipulatorMode() == eBuild ){ + m_build_manipulator.highlight( scissored ); + } + else if( ManipulatorMode() == eUV ){ m_manipulator->testSelect( scissored, GetPivot2World() ); - } - - startMove(); - - m_pivot_moving = m_manipulator->isSelected(); - - if ( m_pivot_moving || movingOrigin ) { - Pivot2World pivot; - pivot.update( GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport() ); - - m_manip2pivot_start = matrix4_multiplied_by_matrix4( matrix4_full_inverse( m_pivot2world_start ), pivot.m_worldSpace ); - - Matrix4 device2manip; - ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - if( m_pivot_moving ){ - m_manipulator->GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], m_bounds, vector4_to_vector3( GetPivot2World().t() ) ); - m_undo_begun = false; } - else if( movingOrigin ){ - m_transformOrigin_manipulator.GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], m_bounds, vector4_to_vector3( GetPivot2World().t() ) ); + else if( ManipulatorMode() == eDrag ){ + m_drag_manipulator.highlight( scissored ); } } - - SceneChangeNotify(); } - return m_pivot_moving || movingOrigin; -} - -void HighlightManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){ - Manipulatable::assign_static( view, device_point, device_epsilon ); //this b4 m_manipulator calls! - - if ( ( !nothingSelected() && transformOrigin_isTranslatable() ) - || ManipulatorMode() == eClip - || ManipulatorMode() == eBuild - || ManipulatorMode() == eUV - || ManipulatorMode() == eDrag ) { -#if defined ( DEBUG_SELECTION ) - g_render_clipped.destroy(); -#endif - - m_transformOrigin_manipulator.setSelected( false ); - m_manipulator->setSelected( false ); - - View scissored( view ); - ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); - - if( transformOrigin_isTranslatable() ){ - m_transformOrigin_manipulator.testSelect( scissored, GetPivot2World() ); - - if( !m_transformOrigin_manipulator.isSelected() ) - m_manipulator->testSelect( scissored, GetPivot2World() ); + void deselectAll(){ + if ( Mode() == eComponent ) { + setSelectedAllComponents( false ); } - else if( ManipulatorMode() == eClip ){ - m_clip_manipulator.testSelect_points( scissored ); - } - else if( ManipulatorMode() == eBuild ){ - m_build_manipulator.highlight( scissored ); - } - else if( ManipulatorMode() == eUV ){ - m_manipulator->testSelect( scissored, GetPivot2World() ); - } - else if( ManipulatorMode() == eDrag ){ - m_drag_manipulator.highlight( scissored ); + else + { + setSelectedAll( false ); } } -} -void deselectAll(){ - if ( Mode() == eComponent ) { - setSelectedAllComponents( false ); + void deselectComponentsOrAll( bool components ){ + if ( components ) { + setSelectedAllComponents( false ); + } + else + { + deselectAll(); + } } - else - { - setSelectedAll( false ); - } -} - -void deselectComponentsOrAll( bool components ){ - if ( components ) { - setSelectedAllComponents( false ); - } - else - { - deselectAll(); - } -} #define SELECT_MATCHING #define SELECT_MATCHING_DEPTH 1e-6f #define SELECT_MATCHING_DIST 1e-6f #define SELECT_MATCHING_COMPONENTS_DIST .25f -void SelectionPool_Select( SelectionPool& pool, bool select, float dist_epsilon ){ - SelectionPool::iterator best = pool.begin(); - if( ( *best ).second->isSelected() != select ){ - ( *best ).second->setSelected( select ); - } + void SelectionPool_Select( SelectionPool& pool, bool select, float dist_epsilon ){ + SelectionPool::iterator best = pool.begin(); + if( ( *best ).second->isSelected() != select ){ + ( *best ).second->setSelected( select ); + } #ifdef SELECT_MATCHING - SelectionPool::iterator i = best; - ++i; - while ( i != pool.end() ) - { - if( ( *i ).first.equalEpsilon( ( *best ).first, dist_epsilon, SELECT_MATCHING_DEPTH ) ){ - //if( ( *i ).second->isSelected() != select ){ - ( *i ).second->setSelected( select ); - //} - } - else{ - break; - } + SelectionPool::iterator i = best; ++i; - } -#endif // SELECT_MATCHING -} - -void SelectPoint( const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face ){ - //globalOutputStream() << device_point[0] << " " << device_point[1] << "\n"; - ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.f && fabs( device_point[1] ) <= 1.f, "point-selection error" ); - - if ( modifier == eReplace ) { - deselectComponentsOrAll( face ); - } -/* -//nothingSelected() doesn't consider faces, selected in non-component mode, m - if ( modifier == eCycle && nothingSelected() ){ - modifier = eReplace; - } -*/ - #if defined ( DEBUG_SELECTION ) - g_render_clipped.destroy(); - #endif - - { - View scissored( view ); - ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); - - SelectionVolume volume( scissored ); - SelectionPool selector; - SelectionPool selector_point_ents; - const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face - && ( modifier == RadiantSelectionSystem::eReplace || modifier == RadiantSelectionSystem::eSelect || modifier == RadiantSelectionSystem::eDeselect ); - - if( prefer_point_ents ){ - Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() ); - } - if( prefer_point_ents && !selector_point_ents.failed() ){ - switch ( modifier ) - { - // if cycle mode not enabled, enable it - case RadiantSelectionSystem::eReplace: - { - // select closest - ( *selector_point_ents.begin() ).second->setSelected( true ); - } - break; - case RadiantSelectionSystem::eSelect: - { - SelectionPool_Select( selector_point_ents, true, SELECT_MATCHING_DIST ); - } - break; - case RadiantSelectionSystem::eDeselect: - { - SelectionPool_Select( selector_point_ents, false, SELECT_MATCHING_DIST ); - } - break; - default: - break; - } - } - else{ - if ( face ){ - Scene_TestSelect_Component( selector, volume, scissored, eFace ); + while ( i != pool.end() ) + { + if( ( *i ).first.equalEpsilon( ( *best ).first, dist_epsilon, SELECT_MATCHING_DEPTH ) ){ + //if( ( *i ).second->isSelected() != select ){ + ( *i ).second->setSelected( select ); + //} } else{ - Scene_TestSelect( selector, volume, scissored, g_modifiers == c_modifierAlt? ePrimitive : Mode(), ComponentMode() ); + break; } + ++i; + } +#endif // SELECT_MATCHING + } - if ( !selector.failed() ) { + void SelectPoint( const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face ){ + //globalOutputStream() << device_point[0] << " " << device_point[1] << "\n"; + ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.f && fabs( device_point[1] ) <= 1.f, "point-selection error" ); + + if ( modifier == eReplace ) { + deselectComponentsOrAll( face ); + } + /* + //nothingSelected() doesn't consider faces, selected in non-component mode, m + if ( modifier == eCycle && nothingSelected() ){ + modifier = eReplace; + } + */ +#if defined ( DEBUG_SELECTION ) + g_render_clipped.destroy(); +#endif + + { + View scissored( view ); + ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); + + SelectionVolume volume( scissored ); + SelectionPool selector; + SelectionPool selector_point_ents; + const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face + && ( modifier == RadiantSelectionSystem::eReplace || modifier == RadiantSelectionSystem::eSelect || modifier == RadiantSelectionSystem::eDeselect ); + + if( prefer_point_ents ){ + Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() ); + } + if( prefer_point_ents && !selector_point_ents.failed() ){ switch ( modifier ) { // if cycle mode not enabled, enable it case RadiantSelectionSystem::eReplace: - { - // select closest - ( *selector.begin() ).second->setSelected( true ); - } - break; - // select the next object in the list from the one already selected - case RadiantSelectionSystem::eCycle: - { - bool cycleSelectionOccured = false; - SelectionPool::iterator i = selector.begin(); - while ( i != selector.end() ) { - if ( ( *i ).second->isSelected() ) { - deselectComponentsOrAll( face ); - ++i; - if ( i != selector.end() ) { - i->second->setSelected( true ); - } - else - { - selector.begin()->second->setSelected( true ); - } - cycleSelectionOccured = true; - break; - } - ++i; + // select closest + ( *selector_point_ents.begin() ).second->setSelected( true ); } - if( !cycleSelectionOccured ){ - deselectComponentsOrAll( face ); - ( *selector.begin() ).second->setSelected( true ); - } - } - break; + break; case RadiantSelectionSystem::eSelect: - { - SelectionPool_Select( selector, true, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); - } - break; + { + SelectionPool_Select( selector_point_ents, true, SELECT_MATCHING_DIST ); + } + break; case RadiantSelectionSystem::eDeselect: - { - SelectionPool_Select( selector, false, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); - } - break; + { + SelectionPool_Select( selector_point_ents, false, SELECT_MATCHING_DIST ); + } + break; default: break; } } - else if( modifier == eCycle ){ - deselectComponentsOrAll( face ); - } - } - } -} - -bool SelectPoint_InitPaint( const View& view, const float device_point[2], const float device_epsilon[2], bool face ){ - ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.f && fabs( device_point[1] ) <= 1.f, "point-selection error" ); - #if defined ( DEBUG_SELECTION ) - g_render_clipped.destroy(); - #endif - - { - View scissored( view ); - ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); - - SelectionVolume volume( scissored ); - SelectionPool selector; - SelectionPool selector_point_ents; - const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face; - - if( prefer_point_ents ){ - Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() ); - } - if( prefer_point_ents && !selector_point_ents.failed() ){ - const bool wasSelected = ( *selector_point_ents.begin() ).second->isSelected(); - SelectionPool_Select( selector_point_ents, !wasSelected, SELECT_MATCHING_DIST ); - return !wasSelected; - } - else{//do primitives, if ents failed - if ( face ){ - Scene_TestSelect_Component( selector, volume, scissored, eFace ); - } else{ - Scene_TestSelect( selector, volume, scissored, g_modifiers == c_modifierAlt? ePrimitive : Mode(), ComponentMode() ); - } - if ( !selector.failed() ){ - const bool wasSelected = ( *selector.begin() ).second->isSelected(); - SelectionPool_Select( selector, !wasSelected, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); - - #if 0 - SelectionPool::iterator best = selector.begin(); - SelectionPool::iterator i = best; - globalOutputStream() << "\n\n\n===========\n"; - while ( i != selector.end() ) - { - globalOutputStream() << "depth:" << ( *i ).first.m_depth << " dist:" << ( *i ).first.m_distance << " depth2:" << ( *i ).first.m_depth2 << "\n"; - globalOutputStream() << "depth - best depth:" << ( *i ).first.m_depth - ( *best ).first.m_depth << "\n"; - ++i; + if ( face ){ + Scene_TestSelect_Component( selector, volume, scissored, eFace ); + } + else{ + Scene_TestSelect( selector, volume, scissored, g_modifiers == c_modifierAlt? ePrimitive : Mode(), ComponentMode() ); } - #endif - return !wasSelected; - } - else{ - return true; + if ( !selector.failed() ) { + switch ( modifier ) + { + // if cycle mode not enabled, enable it + case RadiantSelectionSystem::eReplace: + { + // select closest + ( *selector.begin() ).second->setSelected( true ); + } + break; + // select the next object in the list from the one already selected + case RadiantSelectionSystem::eCycle: + { + bool cycleSelectionOccured = false; + SelectionPool::iterator i = selector.begin(); + while ( i != selector.end() ) + { + if ( ( *i ).second->isSelected() ) { + deselectComponentsOrAll( face ); + ++i; + if ( i != selector.end() ) { + i->second->setSelected( true ); + } + else + { + selector.begin()->second->setSelected( true ); + } + cycleSelectionOccured = true; + break; + } + ++i; + } + if( !cycleSelectionOccured ){ + deselectComponentsOrAll( face ); + ( *selector.begin() ).second->setSelected( true ); + } + } + break; + case RadiantSelectionSystem::eSelect: + { + SelectionPool_Select( selector, true, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); + } + break; + case RadiantSelectionSystem::eDeselect: + { + SelectionPool_Select( selector, false, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); + } + break; + default: + break; + } + } + else if( modifier == eCycle ){ + deselectComponentsOrAll( face ); + } } } } -} -void SelectArea( const View& view, const rect_t rect, bool face ){ - #if defined ( DEBUG_SELECTION ) - g_render_clipped.destroy(); - #endif - View scissored( view ); - ConstructSelectionTest( scissored, rect ); - - SelectionVolume volume( scissored ); - SelectionPool pool; - if ( face ) { - Scene_TestSelect_Component( pool, volume, scissored, eFace ); - } - else - { - Scene_TestSelect( pool, volume, scissored, Mode(), ComponentMode() ); - } - - for ( SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i ) - { - ( *i ).second->setSelected( rect.modifier == rect_t::eSelect? true : rect.modifier == rect_t::eDeselect? false : !( *i ).second->isSelected() ); - } -} - - -void translate( const Vector3& translation ){ - if ( !nothingSelected() ) { - //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); - - m_translation = translation; - m_repeatableTransforms.m_translation = translation; - - m_pivot2world = m_pivot2world_start; - matrix4_translate_by_vec3( m_pivot2world, translation ); - - if ( Mode() == eComponent ) { - Scene_Translate_Component_Selected( GlobalSceneGraph(), m_translation ); - } - else - { - Scene_Translate_Selected( GlobalSceneGraph(), m_translation ); - } - - SceneChangeNotify(); - } -} -void outputTranslation( TextOutputStream& ostream ){ - ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z(); -} -void rotate( const Quaternion& rotation ){ - if ( !nothingSelected() ) { - //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); - - m_rotation = rotation; - m_repeatableTransforms.m_rotation = rotation; - if( ( m_repeatableTransforms.m_rotationOriginSet = m_pivotIsCustom ) ) - m_repeatableTransforms.m_rotationOrigin = vector4_to_vector3( m_pivot2world.t() ); - - if ( Mode() == eComponent ) { - Scene_Rotate_Component_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) ); - - matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() ); - } - else - { - Scene_Rotate_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) ); - - matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() ); - } -#ifdef SELECTIONSYSTEM_AXIAL_PIVOTS - matrix4_assign_rotation( m_pivot2world, matrix4_rotation_for_quaternion_quantised( m_rotation ) ); + bool SelectPoint_InitPaint( const View& view, const float device_point[2], const float device_epsilon[2], bool face ){ + ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.f && fabs( device_point[1] ) <= 1.f, "point-selection error" ); +#if defined ( DEBUG_SELECTION ) + g_render_clipped.destroy(); #endif - SceneChangeNotify(); - } -} -void outputRotation( TextOutputStream& ostream ){ - ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z(); -} -void scale( const Vector3& scaling ){ - if ( !nothingSelected() ) { - m_scale = scaling; - m_repeatableTransforms.m_scale = scaling; - if( ( m_repeatableTransforms.m_scaleOriginSet = m_pivotIsCustom ) ) - m_repeatableTransforms.m_scaleOrigin = vector4_to_vector3( m_pivot2world.t() ); + { + View scissored( view ); + ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) ); - if ( Mode() == eComponent ) { - Scene_Scale_Component_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) ); + SelectionVolume volume( scissored ); + SelectionPool selector; + SelectionPool selector_point_ents; + const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face; + + if( prefer_point_ents ){ + Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() ); + } + if( prefer_point_ents && !selector_point_ents.failed() ){ + const bool wasSelected = ( *selector_point_ents.begin() ).second->isSelected(); + SelectionPool_Select( selector_point_ents, !wasSelected, SELECT_MATCHING_DIST ); + return !wasSelected; + } + else{//do primitives, if ents failed + if ( face ){ + Scene_TestSelect_Component( selector, volume, scissored, eFace ); + } + else{ + Scene_TestSelect( selector, volume, scissored, g_modifiers == c_modifierAlt? ePrimitive : Mode(), ComponentMode() ); + } + if ( !selector.failed() ){ + const bool wasSelected = ( *selector.begin() ).second->isSelected(); + SelectionPool_Select( selector, !wasSelected, ( Mode() == eComponent && g_modifiers != c_modifierAlt )? SELECT_MATCHING_COMPONENTS_DIST : SELECT_MATCHING_DIST ); + +#if 0 + SelectionPool::iterator best = selector.begin(); + SelectionPool::iterator i = best; + globalOutputStream() << "\n\n\n===========\n"; + while ( i != selector.end() ) + { + globalOutputStream() << "depth:" << ( *i ).first.m_depth << " dist:" << ( *i ).first.m_distance << " depth2:" << ( *i ).first.m_depth2 << "\n"; + globalOutputStream() << "depth - best depth:" << ( *i ).first.m_depth - ( *best ).first.m_depth << "\n"; + ++i; + } +#endif + + return !wasSelected; + } + else{ + return true; + } + } + } + } + + void SelectArea( const View& view, const rect_t rect, bool face ){ +#if defined ( DEBUG_SELECTION ) + g_render_clipped.destroy(); +#endif + View scissored( view ); + ConstructSelectionTest( scissored, rect ); + + SelectionVolume volume( scissored ); + SelectionPool pool; + if ( face ) { + Scene_TestSelect_Component( pool, volume, scissored, eFace ); } else { - Scene_Scale_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) ); + Scene_TestSelect( pool, volume, scissored, Mode(), ComponentMode() ); } - if( ManipulatorMode() == eSkew ){ - m_pivot2world[0] = scaling[0]; - m_pivot2world[5] = scaling[1]; - m_pivot2world[10] = scaling[2]; - } - - SceneChangeNotify(); - } -} -void outputScale( TextOutputStream& ostream ){ - ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z(); -} - -void skew( const Skew& skew ){ - if ( !nothingSelected() ) { - m_skew = skew; - m_repeatableTransforms.m_skew = skew; - if( ( m_repeatableTransforms.m_skewOriginSet = m_pivotIsCustom ) ) - m_repeatableTransforms.m_skewOrigin = vector4_to_vector3( m_pivot2world.t() ); - - if ( Mode() == eComponent ) { - Scene_Skew_Component_Selected( GlobalSceneGraph(), m_skew, vector4_to_vector3( m_pivot2world.t() ) ); - } - else + for ( SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i ) { - Scene_Skew_Selected( GlobalSceneGraph(), m_skew, vector4_to_vector3( m_pivot2world.t() ) ); + ( *i ).second->setSelected( rect.modifier == rect_t::eSelect? true : rect.modifier == rect_t::eDeselect? false : !( *i ).second->isSelected() ); } - m_pivot2world[skew.index] = skew.amount; - SceneChangeNotify(); } -} -void rotateSelected( const Quaternion& rotation, bool snapOrigin = false ){ - if( snapOrigin && !m_pivotIsCustom ) - vector3_snap( vector4_to_vector3( m_pivot2world.t() ), GetSnapGridSize() ); - startMove(); - rotate( rotation ); - freezeTransforms(); -} -void translateSelected( const Vector3& translation ){ - startMove(); - translate( translation ); - freezeTransforms(); -} -void scaleSelected( const Vector3& scaling, bool snapOrigin = false ){ - if( snapOrigin && !m_pivotIsCustom ) - vector3_snap( vector4_to_vector3( m_pivot2world.t() ), GetSnapGridSize() ); - startMove(); - scale( scaling ); - freezeTransforms(); -} -RepeatableTransforms m_repeatableTransforms; + void translate( const Vector3& translation ){ + if ( !nothingSelected() ) { + //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); -void repeatTransforms( const Callback& clone ){ - if ( countSelected() != 0 && !m_repeatableTransforms.isIdentity() ) { + m_translation = translation; + m_repeatableTransforms.m_translation = translation; + + m_pivot2world = m_pivot2world_start; + matrix4_translate_by_vec3( m_pivot2world, translation ); + + if ( Mode() == eComponent ) { + Scene_Translate_Component_Selected( GlobalSceneGraph(), m_translation ); + } + else + { + Scene_Translate_Selected( GlobalSceneGraph(), m_translation ); + } + + SceneChangeNotify(); + } + } + void outputTranslation( TextOutputStream& ostream ){ + ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z(); + } + void rotate( const Quaternion& rotation ){ + if ( !nothingSelected() ) { + //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); + + m_rotation = rotation; + m_repeatableTransforms.m_rotation = rotation; + if( ( m_repeatableTransforms.m_rotationOriginSet = m_pivotIsCustom ) ) + m_repeatableTransforms.m_rotationOrigin = vector4_to_vector3( m_pivot2world.t() ); + + if ( Mode() == eComponent ) { + Scene_Rotate_Component_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) ); + + matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() ); + } + else + { + Scene_Rotate_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) ); + + matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() ); + } +#ifdef SELECTIONSYSTEM_AXIAL_PIVOTS + matrix4_assign_rotation( m_pivot2world, matrix4_rotation_for_quaternion_quantised( m_rotation ) ); +#endif + + SceneChangeNotify(); + } + } + void outputRotation( TextOutputStream& ostream ){ + ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z(); + } + void scale( const Vector3& scaling ){ + if ( !nothingSelected() ) { + m_scale = scaling; + m_repeatableTransforms.m_scale = scaling; + if( ( m_repeatableTransforms.m_scaleOriginSet = m_pivotIsCustom ) ) + m_repeatableTransforms.m_scaleOrigin = vector4_to_vector3( m_pivot2world.t() ); + + if ( Mode() == eComponent ) { + Scene_Scale_Component_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) ); + } + else + { + Scene_Scale_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) ); + } + + if( ManipulatorMode() == eSkew ){ + m_pivot2world[0] = scaling[0]; + m_pivot2world[5] = scaling[1]; + m_pivot2world[10] = scaling[2]; + } + + SceneChangeNotify(); + } + } + void outputScale( TextOutputStream& ostream ){ + ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z(); + } + + void skew( const Skew& skew ){ + if ( !nothingSelected() ) { + m_skew = skew; + m_repeatableTransforms.m_skew = skew; + if( ( m_repeatableTransforms.m_skewOriginSet = m_pivotIsCustom ) ) + m_repeatableTransforms.m_skewOrigin = vector4_to_vector3( m_pivot2world.t() ); + + if ( Mode() == eComponent ) { + Scene_Skew_Component_Selected( GlobalSceneGraph(), m_skew, vector4_to_vector3( m_pivot2world.t() ) ); + } + else + { + Scene_Skew_Selected( GlobalSceneGraph(), m_skew, vector4_to_vector3( m_pivot2world.t() ) ); + } + m_pivot2world[skew.index] = skew.amount; + SceneChangeNotify(); + } + } + + void rotateSelected( const Quaternion& rotation, bool snapOrigin = false ){ + if( snapOrigin && !m_pivotIsCustom ) + vector3_snap( vector4_to_vector3( m_pivot2world.t() ), GetSnapGridSize() ); startMove(); - UndoableCommand undo( "repeatTransforms" ); - if( Mode() == ePrimitive ) - clone(); - if ( Mode() == eComponent ) { - GlobalSelectionSystem().foreachSelectedComponent( transform_component_selected( m_repeatableTransforms, vector4_to_vector3( m_pivot2world.t() ) ) ); - } - else - { - GlobalSelectionSystem().foreachSelected( transform_selected( m_repeatableTransforms, vector4_to_vector3( m_pivot2world.t() ) ) ); - } + rotate( rotation ); + freezeTransforms(); + } + void translateSelected( const Vector3& translation ){ + startMove(); + translate( translation ); + freezeTransforms(); + } + void scaleSelected( const Vector3& scaling, bool snapOrigin = false ){ + if( snapOrigin && !m_pivotIsCustom ) + vector3_snap( vector4_to_vector3( m_pivot2world.t() ), GetSnapGridSize() ); + startMove(); + scale( scaling ); freezeTransforms(); } -} -bool transformOrigin_isTranslatable() const{ - return ManipulatorMode() == eScale - || ManipulatorMode() == eSkew - || ManipulatorMode() == eRotate - || ManipulatorMode() == eTranslate; -} + RepeatableTransforms m_repeatableTransforms; -void transformOriginTranslate( const Vector3& translation, const bool set[3] ){ - m_pivot2world = m_pivot2world_start; - setCustomTransformOrigin( translation + vector4_to_vector3( m_pivot2world_start.t() ), set ); - SceneChangeNotify(); -} - -void MoveSelected( const View& view, const float device_point[2], bool snap, bool snapbbox, bool alt ){ - if ( m_manipulator->isSelected() ) { - if ( !m_undo_begun ) { - m_undo_begun = true; - GlobalUndoSystem().start(); + void repeatTransforms( const Callback& clone ){ + if ( countSelected() != 0 && !m_repeatableTransforms.isIdentity() ) { + startMove(); + UndoableCommand undo( "repeatTransforms" ); + if( Mode() == ePrimitive ) + clone(); + if ( Mode() == eComponent ) { + GlobalSelectionSystem().foreachSelectedComponent( transform_component_selected( m_repeatableTransforms, vector4_to_vector3( m_pivot2world.t() ) ) ); + } + else + { + GlobalSelectionSystem().foreachSelected( transform_selected( m_repeatableTransforms, vector4_to_vector3( m_pivot2world.t() ) ) ); + } + freezeTransforms(); } + } - Matrix4 device2manip; - ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - m_manipulator->GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox, alt ); + bool transformOrigin_isTranslatable() const{ + return ManipulatorMode() == eScale + || ManipulatorMode() == eSkew + || ManipulatorMode() == eRotate + || ManipulatorMode() == eTranslate; } - else if( m_transformOrigin_manipulator.isSelected() ){ - Matrix4 device2manip; - ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); - m_transformOrigin_manipulator.GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox, alt ); + + void transformOriginTranslate( const Vector3& translation, const bool set[3] ){ + m_pivot2world = m_pivot2world_start; + setCustomTransformOrigin( translation + vector4_to_vector3( m_pivot2world_start.t() ), set ); + SceneChangeNotify(); + } + + void MoveSelected( const View& view, const float device_point[2], bool snap, bool snapbbox, bool alt ){ + if ( m_manipulator->isSelected() ) { + if ( !m_undo_begun ) { + m_undo_begun = true; + GlobalUndoSystem().start(); + } + + Matrix4 device2manip; + ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + m_manipulator->GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox, alt ); + } + else if( m_transformOrigin_manipulator.isSelected() ){ + Matrix4 device2manip; + ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() ); + m_transformOrigin_manipulator.GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox, alt ); + } } -} /// \todo Support view-dependent nudge. -void NudgeManipulator( const Vector3& nudge, const Vector3& view ){ + void NudgeManipulator( const Vector3& nudge, const Vector3& view ){ // if ( ManipulatorMode() == eTranslate || ManipulatorMode() == eDrag ) { translateSelected( nudge ); // } -} + } -bool endMove(); -void freezeTransforms(); + bool endMove(); + void freezeTransforms(); -void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; -void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { - renderSolid( renderer, volume ); -} + void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; + void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); + } -const Matrix4& GetPivot2World() const { - ConstructPivot(); - return m_pivot2world; -} + const Matrix4& GetPivot2World() const { + ConstructPivot(); + return m_pivot2world; + } -static void constructStatic(){ - #if defined( DEBUG_SELECTION ) - g_state_clipped = GlobalShaderCache().capture( "$DEBUG_CLIPPED" ); - #endif - m_state = GlobalShaderCache().capture( "$POINT" ); - TranslateManipulator::m_state_wire = - RotateManipulator::m_state_outer = - SkewManipulator::m_state_wire = - BuildManipulator::m_state_line = GlobalShaderCache().capture( "$WIRE_OVERLAY" ); - TranslateManipulator::m_state_fill = - SkewManipulator::m_state_fill = GlobalShaderCache().capture( "$FLATSHADE_OVERLAY" ); - TransformOriginManipulator::m_state = - ClipManipulator::m_state = - SkewManipulator::m_state_point = - BuildManipulator::m_state_point = - UVManipulator::m_state_point = GlobalShaderCache().capture( "$BIGPOINT" ); - RenderablePivot::StaticShader::instance() = GlobalShaderCache().capture( "$PIVOT" ); - UVManipulator::m_state_line = GlobalShaderCache().capture( "$BLENDLINE" ); - DragManipulator::m_state_wire = GlobalShaderCache().capture( "$PLANE_WIRE_OVERLAY" ); -} + static void constructStatic(){ +#if defined( DEBUG_SELECTION ) + g_state_clipped = GlobalShaderCache().capture( "$DEBUG_CLIPPED" ); +#endif + m_state = GlobalShaderCache().capture( "$POINT" ); + TranslateManipulator::m_state_wire = + RotateManipulator::m_state_outer = + SkewManipulator::m_state_wire = + BuildManipulator::m_state_line = GlobalShaderCache().capture( "$WIRE_OVERLAY" ); + TranslateManipulator::m_state_fill = + SkewManipulator::m_state_fill = GlobalShaderCache().capture( "$FLATSHADE_OVERLAY" ); + TransformOriginManipulator::m_state = + ClipManipulator::m_state = + SkewManipulator::m_state_point = + BuildManipulator::m_state_point = + UVManipulator::m_state_point = GlobalShaderCache().capture( "$BIGPOINT" ); + RenderablePivot::StaticShader::instance() = GlobalShaderCache().capture( "$PIVOT" ); + UVManipulator::m_state_line = GlobalShaderCache().capture( "$BLENDLINE" ); + DragManipulator::m_state_wire = GlobalShaderCache().capture( "$PLANE_WIRE_OVERLAY" ); + } -static void destroyStatic(){ - #if defined( DEBUG_SELECTION ) - GlobalShaderCache().release( "$DEBUG_CLIPPED" ); - #endif - GlobalShaderCache().release( "$PLANE_WIRE_OVERLAY" ); - GlobalShaderCache().release( "$BLENDLINE" ); - GlobalShaderCache().release( "$PIVOT" ); - GlobalShaderCache().release( "$BIGPOINT" ); - GlobalShaderCache().release( "$FLATSHADE_OVERLAY" ); - GlobalShaderCache().release( "$WIRE_OVERLAY" ); - GlobalShaderCache().release( "$POINT" ); -} + static void destroyStatic(){ +#if defined( DEBUG_SELECTION ) + GlobalShaderCache().release( "$DEBUG_CLIPPED" ); +#endif + GlobalShaderCache().release( "$PLANE_WIRE_OVERLAY" ); + GlobalShaderCache().release( "$BLENDLINE" ); + GlobalShaderCache().release( "$PIVOT" ); + GlobalShaderCache().release( "$BIGPOINT" ); + GlobalShaderCache().release( "$FLATSHADE_OVERLAY" ); + GlobalShaderCache().release( "$WIRE_OVERLAY" ); + GlobalShaderCache().release( "$POINT" ); + } }; Shader* RadiantSelectionSystem::m_state = 0; @@ -7545,107 +7551,107 @@ inline RadiantSelectionSystem& getSelectionSystem(){ class testselect_entity_visible : public scene::Graph::Walker { -Selector& m_selector; -SelectionTest& m_test; + Selector& m_selector; + SelectionTest& m_test; public: -testselect_entity_visible( Selector& selector, SelectionTest& test ) - : m_selector( selector ), m_test( test ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if( path.top().get_pointer() == Map_GetWorldspawn( g_map ) || - node_is_group( path.top().get() ) ){ - return false; - } - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable != 0 - && Node_isEntity( path.top() ) ) { - m_selector.pushSelectable( *selectable ); + testselect_entity_visible( Selector& selector, SelectionTest& test ) + : m_selector( selector ), m_test( test ){ } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if( path.top().get_pointer() == Map_GetWorldspawn( g_map ) || + node_is_group( path.top().get() ) ){ + return false; + } + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable != 0 + && Node_isEntity( path.top() ) ) { + m_selector.pushSelectable( *selectable ); + } - SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); - if ( selectionTestable ) { - selectionTestable->testSelect( m_selector, m_test ); - } + SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); + if ( selectionTestable ) { + selectionTestable->testSelect( m_selector, m_test ); + } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable != 0 - && Node_isEntity( path.top() ) ) { - m_selector.popSelectable(); + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable != 0 + && Node_isEntity( path.top() ) ) { + m_selector.popSelectable(); + } } -} }; class testselect_primitive_visible : public scene::Graph::Walker { -Selector& m_selector; -SelectionTest& m_test; + Selector& m_selector; + SelectionTest& m_test; public: -testselect_primitive_visible( Selector& selector, SelectionTest& test ) - : m_selector( selector ), m_test( test ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable != 0 ) { - m_selector.pushSelectable( *selectable ); + testselect_primitive_visible( Selector& selector, SelectionTest& test ) + : m_selector( selector ), m_test( test ){ } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable != 0 ) { + m_selector.pushSelectable( *selectable ); + } - SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); - if ( selectionTestable ) { - selectionTestable->testSelect( m_selector, m_test ); - } + SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); + if ( selectionTestable ) { + selectionTestable->testSelect( m_selector, m_test ); + } - return true; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - Selectable* selectable = Instance_getSelectable( instance ); - if ( selectable != 0 ) { - m_selector.popSelectable(); + return true; + } + void post( const scene::Path& path, scene::Instance& instance ) const { + Selectable* selectable = Instance_getSelectable( instance ); + if ( selectable != 0 ) { + m_selector.popSelectable(); + } } -} }; class testselect_component_visible : public scene::Graph::Walker { -Selector& m_selector; -SelectionTest& m_test; -SelectionSystem::EComponentMode m_mode; + Selector& m_selector; + SelectionTest& m_test; + SelectionSystem::EComponentMode m_mode; public: -testselect_component_visible( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) - : m_selector( selector ), m_test( test ), m_mode( mode ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); - if ( componentSelectionTestable ) { - componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode ); + testselect_component_visible( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) + : m_selector( selector ), m_test( test ), m_mode( mode ){ } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); + if ( componentSelectionTestable ) { + componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode ); + } - return true; -} + return true; + } }; class testselect_component_visible_selected : public scene::Graph::Walker { -Selector& m_selector; -SelectionTest& m_test; -SelectionSystem::EComponentMode m_mode; + Selector& m_selector; + SelectionTest& m_test; + SelectionSystem::EComponentMode m_mode; public: -testselect_component_visible_selected( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) - : m_selector( selector ), m_test( test ), m_mode( mode ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); - if ( componentSelectionTestable ) { - componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode ); - } + testselect_component_visible_selected( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) + : m_selector( selector ), m_test( test ), m_mode( mode ){ } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance ); + if ( componentSelectionTestable ) { + componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode ); + } + } - return true; -} + return true; + } }; void Scene_TestSelect_Primitive( Selector& selector, SelectionTest& test, const VolumeTest& volume ){ @@ -7698,16 +7704,16 @@ void Scene_Intersect( const View& view, const float device_point[2], const float class FreezeTransforms : public scene::Graph::Walker { public: -bool pre( const scene::Path& path, scene::Instance& instance ) const { - TransformNode* transformNode = Node_getTransformNode( path.top() ); - if ( transformNode != 0 ) { - Transformable* transform = Instance_getTransformable( instance ); - if ( transform != 0 ) { - transform->freezeTransform(); + bool pre( const scene::Path& path, scene::Instance& instance ) const { + TransformNode* transformNode = Node_getTransformNode( path.top() ); + if ( transformNode != 0 ) { + Transformable* transform = Instance_getTransformable( instance ); + if ( transform != 0 ) { + transform->freezeTransform(); + } } + return true; } - return true; -} }; void RadiantSelectionSystem::freezeTransforms(){ @@ -7777,8 +7783,8 @@ bool RadiantSelectionSystem::endMove(){ inline AABB Instance_getPivotBounds( scene::Instance& instance ){ Entity* entity = Node_getEntity( instance.path().top() ); if ( entity != 0 - && ( entity->getEntityClass().fixedsize - || !node_is_group( instance.path().top() ) ) ) { + && ( entity->getEntityClass().fixedsize + || !node_is_group( instance.path().top() ) ) ) { Editable* editable = Node_getEditable( instance.path().top() ); if ( editable != 0 ) { return AABB( vector4_to_vector3( matrix4_multiplied_by_matrix4( instance.localToWorld(), editable->getLocalPivot() ).t() ), Vector3( 0, 0, 0 ) ); @@ -7794,37 +7800,37 @@ inline AABB Instance_getPivotBounds( scene::Instance& instance ){ class bounds_selected : public scene::Graph::Walker { -AABB& m_bounds; + AABB& m_bounds; public: -bounds_selected( AABB& bounds ) - : m_bounds( bounds ){ - m_bounds = AABB(); -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - aabb_extend_by_aabb_safe( m_bounds, Instance_getPivotBounds( instance ) ); + bounds_selected( AABB& bounds ) + : m_bounds( bounds ){ + m_bounds = AABB(); + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + aabb_extend_by_aabb_safe( m_bounds, Instance_getPivotBounds( instance ) ); + } + return true; } - return true; -} }; class bounds_selected_component : public scene::Graph::Walker { -AABB& m_bounds; + AABB& m_bounds; public: -bounds_selected_component( AABB& bounds ) - : m_bounds( bounds ){ - m_bounds = AABB(); -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( Instance_isSelected( instance ) ) { - ComponentEditable* componentEditable = Instance_getComponentEditable( instance ); - if ( componentEditable ) { - aabb_extend_by_aabb_safe( m_bounds, aabb_for_oriented_aabb_safe( componentEditable->getSelectedComponentsBounds(), instance.localToWorld() ) ); - } + bounds_selected_component( AABB& bounds ) + : m_bounds( bounds ){ + m_bounds = AABB(); + } + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( Instance_isSelected( instance ) ) { + ComponentEditable* componentEditable = Instance_getComponentEditable( instance ); + if ( componentEditable ) { + aabb_extend_by_aabb_safe( m_bounds, aabb_for_oriented_aabb_safe( componentEditable->getSelectedComponentsBounds(), instance.localToWorld() ) ); + } + } + return true; } - return true; -} }; void Scene_BoundsSelected( scene::Graph& graph, AABB& bounds ){ @@ -7839,7 +7845,7 @@ void Scene_BoundsSelectedComponent( scene::Graph& graph, AABB& bounds ){ inline void pivot_for_node( Matrix4& pivot, scene::Node& node, scene::Instance& instance ){ ComponentEditable* componentEditable = Instance_getComponentEditable( instance ); if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && componentEditable != 0 ) { + && componentEditable != 0 ) { pivot = matrix4_translation_for_vec3( componentEditable->getSelectedComponentsBounds().origin ); } else @@ -7962,10 +7968,10 @@ AABB RadiantSelectionSystem::getSelectionAABB() const { void RadiantSelectionSystem::renderSolid( Renderer& renderer, const VolumeTest& volume ) const { //if(view->TestPoint(m_object_pivot)) if ( !nothingSelected() - || ManipulatorMode() == eClip - || ManipulatorMode() == eBuild - || ManipulatorMode() == eUV - || ManipulatorMode() == eDrag ) { + || ManipulatorMode() == eClip + || ManipulatorMode() == eBuild + || ManipulatorMode() == eUV + || ManipulatorMode() == eDrag ) { renderer.Highlight( Renderer::ePrimitive, false ); renderer.Highlight( Renderer::eFace, false ); @@ -7997,11 +8003,11 @@ void SelectionSystem_constructPreferences( PreferencesPage& page ){ { const char* styles[] = { "XY plane + Z with Alt", "View plane + Forward with Alt", }; page.appendCombo( - "Move style in 3D", - STRING_ARRAY_RANGE( styles ), - IntImportCaller( TranslateFreeXY_Z::m_viewdependent ), - IntExportCaller( TranslateFreeXY_Z::m_viewdependent ) - ); + "Move style in 3D", + STRING_ARRAY_RANGE( styles ), + IntImportCaller( TranslateFreeXY_Z::m_viewdependent ), + IntExportCaller( TranslateFreeXY_Z::m_viewdependent ) + ); } } void SelectionSystem_constructPage( PreferenceGroup& group ){ @@ -8111,93 +8117,93 @@ const char* Scene_applyClosestTexture_getUndoName( bool shift, bool ctrl, bool a class TexManipulator_ { -const DeviceVector& m_epsilon; -const ModifierFlags& m_state; + const DeviceVector& m_epsilon; + const ModifierFlags& m_state; public: -const View* m_view; -bool m_undo_begun; + const View* m_view; + bool m_undo_begun; -TexManipulator_( const DeviceVector& epsilon, const ModifierFlags& state ) : + TexManipulator_( const DeviceVector& epsilon, const ModifierFlags& state ) : m_epsilon( epsilon ), m_state( state ), m_undo_begun( false ){ -} - -void mouseDown( DeviceVector position ){ - View scissored( *m_view ); - ConstructSelectionTest( scissored, SelectionBoxForPoint( &position[0], &m_epsilon[0] ) ); - SelectionVolume volume( scissored ); - - if( m_state == c_modifier_copy_texture ) { - Scene_copyClosestTexture( volume ); } - else{ - m_undo_begun = true; - GlobalUndoSystem().start(); - Scene_applyClosestTexture( volume, bitfield_enabled( m_state, c_modifierShift ), - bitfield_enabled( m_state, c_modifierControl ), - bitfield_enabled( m_state, c_modifierAlt ), true ); - } -} -void mouseMoved( DeviceVector position ){ - if( m_undo_begun ){ + void mouseDown( DeviceVector position ){ View scissored( *m_view ); - ConstructSelectionTest( scissored, SelectionBoxForPoint( &device_constrained( position )[0], &m_epsilon[0] ) ); + ConstructSelectionTest( scissored, SelectionBoxForPoint( &position[0], &m_epsilon[0] ) ); SelectionVolume volume( scissored ); - Scene_applyClosestTexture( volume, bitfield_enabled( m_state, c_modifierShift ), - bitfield_enabled( m_state, c_modifierControl ), - bitfield_enabled( m_state, c_modifierAlt ) ); + if( m_state == c_modifier_copy_texture ) { + Scene_copyClosestTexture( volume ); + } + else{ + m_undo_begun = true; + GlobalUndoSystem().start(); + Scene_applyClosestTexture( volume, bitfield_enabled( m_state, c_modifierShift ), + bitfield_enabled( m_state, c_modifierControl ), + bitfield_enabled( m_state, c_modifierAlt ), true ); + } } -} -typedef MemberCaller1 MouseMovedCaller; -void mouseUp( DeviceVector position ){ - if( m_undo_begun ){ - GlobalUndoSystem().finish( Scene_applyClosestTexture_getUndoName( bitfield_enabled( m_state, c_modifierShift ), - bitfield_enabled( m_state, c_modifierControl ), - bitfield_enabled( m_state, c_modifierAlt ) ) ); - m_undo_begun = false; + void mouseMoved( DeviceVector position ){ + if( m_undo_begun ){ + View scissored( *m_view ); + ConstructSelectionTest( scissored, SelectionBoxForPoint( &device_constrained( position )[0], &m_epsilon[0] ) ); + SelectionVolume volume( scissored ); + + Scene_applyClosestTexture( volume, bitfield_enabled( m_state, c_modifierShift ), + bitfield_enabled( m_state, c_modifierControl ), + bitfield_enabled( m_state, c_modifierAlt ) ); + } } - g_mouseMovedCallback.clear(); - g_mouseUpCallback.clear(); -} -typedef MemberCaller1 MouseUpCaller; + typedef MemberCaller1 MouseMovedCaller; + + void mouseUp( DeviceVector position ){ + if( m_undo_begun ){ + GlobalUndoSystem().finish( Scene_applyClosestTexture_getUndoName( bitfield_enabled( m_state, c_modifierShift ), + bitfield_enabled( m_state, c_modifierControl ), + bitfield_enabled( m_state, c_modifierAlt ) ) ); + m_undo_begun = false; + } + g_mouseMovedCallback.clear(); + g_mouseUpCallback.clear(); + } + typedef MemberCaller1 MouseUpCaller; }; class Selector_ { -RadiantSelectionSystem::EModifier modifier_for_state( ModifierFlags state ){ - if ( ( state == c_modifier_toggle || state == c_modifier_toggle_face || state == c_modifier_face ) - && m_mouse2 ) - return RadiantSelectionSystem::eReplace; - else - return RadiantSelectionSystem::eManipulator; -} + RadiantSelectionSystem::EModifier modifier_for_state( ModifierFlags state ){ + if ( ( state == c_modifier_toggle || state == c_modifier_toggle_face || state == c_modifier_face ) + && m_mouse2 ) + return RadiantSelectionSystem::eReplace; + else + return RadiantSelectionSystem::eManipulator; + } -rect_t getDeviceArea() const { - const DeviceVector delta( m_current - m_start ); - if ( m_mouseMovedWhilePressed && selecting() && delta.x() != 0 && delta.y() != 0 ) - return SelectionBoxForArea( &m_start[0], &delta[0] ); - else - return rect_t(); -} + rect_t getDeviceArea() const { + const DeviceVector delta( m_current - m_start ); + if ( m_mouseMovedWhilePressed && selecting() && delta.x() != 0 && delta.y() != 0 ) + return SelectionBoxForArea( &m_start[0], &delta[0] ); + else + return rect_t(); + } -const DeviceVector& m_epsilon; -ModifierFlags m_state; + const DeviceVector& m_epsilon; + ModifierFlags m_state; public: -DeviceVector m_start; -DeviceVector m_current; -bool m_mouse2; -bool m_mouseMoved; -bool m_mouseMovedWhilePressed; -bool m_paintSelect; -const View* m_view; -RectangleCallback m_window_update; + DeviceVector m_start; + DeviceVector m_current; + bool m_mouse2; + bool m_mouseMoved; + bool m_mouseMovedWhilePressed; + bool m_paintSelect; + const View* m_view; + RectangleCallback m_window_update; -Selector_( const DeviceVector& epsilon ) : + Selector_( const DeviceVector& epsilon ) : m_epsilon( epsilon ), m_state( c_modifierNone ), m_start( 0.f, 0.f ), @@ -8205,138 +8211,138 @@ Selector_( const DeviceVector& epsilon ) : m_mouse2( false ), m_mouseMoved( false ), m_mouseMovedWhilePressed( false ){ -} + } -void draw_area(){ - m_window_update( getDeviceArea() ); -} + void draw_area(){ + m_window_update( getDeviceArea() ); + } -void testSelect( DeviceVector position ){ - RadiantSelectionSystem::EModifier modifier = modifier_for_state( m_state ); - if ( modifier != RadiantSelectionSystem::eManipulator ) { - const DeviceVector delta( position - m_start ); - if ( m_mouseMovedWhilePressed && delta.x() != 0 && delta.y() != 0 ) { - getSelectionSystem().SelectArea( *m_view, SelectionBoxForArea( &m_start[0], &delta[0] ), ( m_state & c_modifier_face ) != c_modifierNone ); - } - else if( !m_mouseMovedWhilePressed ){ - if ( modifier == RadiantSelectionSystem::eReplace && !m_mouseMoved ) { - modifier = RadiantSelectionSystem::eCycle; + void testSelect( DeviceVector position ){ + RadiantSelectionSystem::EModifier modifier = modifier_for_state( m_state ); + if ( modifier != RadiantSelectionSystem::eManipulator ) { + const DeviceVector delta( position - m_start ); + if ( m_mouseMovedWhilePressed && delta.x() != 0 && delta.y() != 0 ) { + getSelectionSystem().SelectArea( *m_view, SelectionBoxForArea( &m_start[0], &delta[0] ), ( m_state & c_modifier_face ) != c_modifierNone ); } - getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone ); + else if( !m_mouseMovedWhilePressed ){ + if ( modifier == RadiantSelectionSystem::eReplace && !m_mouseMoved ) { + modifier = RadiantSelectionSystem::eCycle; + } + getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone ); + } + } + + m_start = m_current = DeviceVector( 0.f, 0.f ); + draw_area(); + } + + void testSelect_simpleM1( DeviceVector position ){ + if( g_bLeftMouseClickSelector ) + getSelectionSystem().SelectPoint( *m_view, &device_constrained( position )[0], &m_epsilon[0], m_mouseMoved ? RadiantSelectionSystem::eReplace : RadiantSelectionSystem::eCycle, false ); + } + + + bool selecting() const { + return m_state != c_modifier_manipulator && m_mouse2; + } + + void setState( ModifierFlags state ){ + const bool was_selecting = selecting(); + m_state = state; + if ( was_selecting ^ selecting() ) { + draw_area(); } } - m_start = m_current = DeviceVector( 0.f, 0.f ); - draw_area(); -} - -void testSelect_simpleM1( DeviceVector position ){ - if( g_bLeftMouseClickSelector ) - getSelectionSystem().SelectPoint( *m_view, &device_constrained( position )[0], &m_epsilon[0], m_mouseMoved ? RadiantSelectionSystem::eReplace : RadiantSelectionSystem::eCycle, false ); -} - - -bool selecting() const { - return m_state != c_modifier_manipulator && m_mouse2; -} - -void setState( ModifierFlags state ){ - const bool was_selecting = selecting(); - m_state = state; - if ( was_selecting ^ selecting() ) { - draw_area(); - } -} - -void mouseDown( DeviceVector position ){ - m_start = m_current = device_constrained( position ); - if( !m_mouse2 && m_state != c_modifierNone ){ - m_paintSelect = getSelectionSystem().SelectPoint_InitPaint( *m_view, &position[0], &m_epsilon[0], ( m_state & c_modifier_face ) != c_modifierNone ); - } -} - -void mouseMoved( DeviceVector position ){ - m_current = device_constrained( position ); - if( m_mouse2 ){ - draw_area(); - } - else if( m_state != c_modifier_manipulator ){ - getSelectionSystem().SelectPoint( *m_view, &m_current[0], &m_epsilon[0], - m_paintSelect ? RadiantSelectionSystem::eSelect : RadiantSelectionSystem::eDeselect, - ( m_state & c_modifier_face ) != c_modifierNone ); - } -} -typedef MemberCaller1 MouseMovedCaller; - -void mouseUp( DeviceVector position ){ - if( m_mouse2 ){ - testSelect( device_constrained( position ) ); - } - else{ - m_start = m_current = DeviceVector( 0.0f, 0.0f ); + void mouseDown( DeviceVector position ){ + m_start = m_current = device_constrained( position ); + if( !m_mouse2 && m_state != c_modifierNone ){ + m_paintSelect = getSelectionSystem().SelectPoint_InitPaint( *m_view, &position[0], &m_epsilon[0], ( m_state & c_modifier_face ) != c_modifierNone ); + } } - g_mouseMovedCallback.clear(); - g_mouseUpCallback.clear(); -} -typedef MemberCaller1 MouseUpCaller; + void mouseMoved( DeviceVector position ){ + m_current = device_constrained( position ); + if( m_mouse2 ){ + draw_area(); + } + else if( m_state != c_modifier_manipulator ){ + getSelectionSystem().SelectPoint( *m_view, &m_current[0], &m_epsilon[0], + m_paintSelect ? RadiantSelectionSystem::eSelect : RadiantSelectionSystem::eDeselect, + ( m_state & c_modifier_face ) != c_modifierNone ); + } + } + typedef MemberCaller1 MouseMovedCaller; + + void mouseUp( DeviceVector position ){ + if( m_mouse2 ){ + testSelect( device_constrained( position ) ); + } + else{ + m_start = m_current = DeviceVector( 0.0f, 0.0f ); + } + + g_mouseMovedCallback.clear(); + g_mouseUpCallback.clear(); + } + typedef MemberCaller1 MouseUpCaller; }; class Manipulator_ { -DeviceVector getEpsilon(){ - switch ( getSelectionSystem().ManipulatorMode() ) - { - case SelectionSystem::eClip: - return m_epsilon / g_SELECT_EPSILON * ( g_SELECT_EPSILON + 4 ); - case SelectionSystem::eDrag: - case SelectionSystem::eUV: - return m_epsilon; - default: //getSelectionSystem().transformOrigin_isTranslatable() - return m_epsilon / g_SELECT_EPSILON * 8; + DeviceVector getEpsilon(){ + switch ( getSelectionSystem().ManipulatorMode() ) + { + case SelectionSystem::eClip: + return m_epsilon / g_SELECT_EPSILON * ( g_SELECT_EPSILON + 4 ); + case SelectionSystem::eDrag: + case SelectionSystem::eUV: + return m_epsilon; + default: //getSelectionSystem().transformOrigin_isTranslatable() + return m_epsilon / g_SELECT_EPSILON * 8; + } } -} -const DeviceVector& m_epsilon; -const ModifierFlags& m_state; + const DeviceVector& m_epsilon; + const ModifierFlags& m_state; public: -const View* m_view; + const View* m_view; -bool m_moving_transformOrigin; -bool m_mouseMovedWhilePressed; + bool m_moving_transformOrigin; + bool m_mouseMovedWhilePressed; -Manipulator_( const DeviceVector& epsilon, const ModifierFlags& state ) : + Manipulator_( const DeviceVector& epsilon, const ModifierFlags& state ) : m_epsilon( epsilon ), m_state( state ), m_moving_transformOrigin( false ), m_mouseMovedWhilePressed( false ) { -} + } -bool mouseDown( DeviceVector position ){ - if( getSelectionSystem().ManipulatorMode() == SelectionSystem::eClip ) - Clipper_tryDoubleclick(); - return getSelectionSystem().SelectManipulator( *m_view, &position[0], &getEpsilon()[0] ); -} + bool mouseDown( DeviceVector position ){ + if( getSelectionSystem().ManipulatorMode() == SelectionSystem::eClip ) + Clipper_tryDoubleclick(); + return getSelectionSystem().SelectManipulator( *m_view, &position[0], &getEpsilon()[0] ); + } -void mouseMoved( DeviceVector position ){ - if( m_mouseMovedWhilePressed ) - getSelectionSystem().MoveSelected( *m_view, &position[0], bitfield_enabled( m_state, c_modifierShift ), - bitfield_enabled( m_state, c_modifierControl ), - bitfield_enabled( m_state, c_modifierAlt ) ); -} -typedef MemberCaller1 MouseMovedCaller; + void mouseMoved( DeviceVector position ){ + if( m_mouseMovedWhilePressed ) + getSelectionSystem().MoveSelected( *m_view, &position[0], bitfield_enabled( m_state, c_modifierShift ), + bitfield_enabled( m_state, c_modifierControl ), + bitfield_enabled( m_state, c_modifierAlt ) ); + } + typedef MemberCaller1 MouseMovedCaller; -void mouseUp( DeviceVector position ){ - m_moving_transformOrigin = getSelectionSystem().endMove(); - g_mouseMovedCallback.clear(); - g_mouseUpCallback.clear(); -} -typedef MemberCaller1 MouseUpCaller; + void mouseUp( DeviceVector position ){ + m_moving_transformOrigin = getSelectionSystem().endMove(); + g_mouseMovedCallback.clear(); + g_mouseUpCallback.clear(); + } + typedef MemberCaller1 MouseUpCaller; -void highlight( DeviceVector position ){ - getSelectionSystem().HighlightManipulator( *m_view, &position[0], &getEpsilon()[0] ); -} + void highlight( DeviceVector position ){ + getSelectionSystem().HighlightManipulator( *m_view, &position[0], &getEpsilon()[0] ); + } }; @@ -8344,151 +8350,151 @@ void highlight( DeviceVector position ){ class RadiantWindowObserver final : public SelectionSystemWindowObserver { -DeviceVector m_epsilon; -ModifierFlags m_state; + DeviceVector m_epsilon; + ModifierFlags m_state; -int m_width; -int m_height; + int m_width; + int m_height; -bool m_mouse_down; + bool m_mouse_down; -const float m_moveEpsilon; -float m_move; /* released move after m_moveEnd, for tunnel selector decision: eReplace or eCycle */ -float m_movePressed; /* pressed move after m_moveStart, for decision: m1 tunnel selector or manipulate and if to do tunnel selector at all */ -DeviceVector m_moveStart; -DeviceVector m_moveEnd; + const float m_moveEpsilon; + float m_move; /* released move after m_moveEnd, for tunnel selector decision: eReplace or eCycle */ + float m_movePressed; /* pressed move after m_moveStart, for decision: m1 tunnel selector or manipulate and if to do tunnel selector at all */ + DeviceVector m_moveStart; + DeviceVector m_moveEnd; -Selector_ m_selector; -Manipulator_ m_manipulator; -TexManipulator_ m_texmanipulator; + Selector_ m_selector; + Manipulator_ m_manipulator; + TexManipulator_ m_texmanipulator; public: -RadiantWindowObserver() : + RadiantWindowObserver() : m_state( c_modifierNone ), m_mouse_down( false ), m_moveEpsilon( .01f ), m_selector( m_epsilon ), m_manipulator( m_epsilon, m_state ), m_texmanipulator( m_epsilon, m_state ){ -} -void release(){ - delete this; -} -void setView( const View& view ){ - m_selector.m_view = &view; - m_manipulator.m_view = &view; - m_texmanipulator.m_view = &view; -} -void setRectangleDrawCallback( const RectangleCallback& callback ){ - m_selector.m_window_update = callback; -} -void updateEpsilon(){ - m_epsilon = DeviceVector( g_SELECT_EPSILON / static_cast( m_width ), g_SELECT_EPSILON / static_cast( m_height ) ); -} -void onSizeChanged( int width, int height ){ - m_width = width; - m_height = height; - updateEpsilon(); -} -void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){ - updateEpsilon(); /* could have changed, as it is user setting */ + } + void release(){ + delete this; + } + void setView( const View& view ){ + m_selector.m_view = &view; + m_manipulator.m_view = &view; + m_texmanipulator.m_view = &view; + } + void setRectangleDrawCallback( const RectangleCallback& callback ){ + m_selector.m_window_update = callback; + } + void updateEpsilon(){ + m_epsilon = DeviceVector( g_SELECT_EPSILON / static_cast( m_width ), g_SELECT_EPSILON / static_cast( m_height ) ); + } + void onSizeChanged( int width, int height ){ + m_width = width; + m_height = height; + updateEpsilon(); + } + void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){ + updateEpsilon(); /* could have changed, as it is user setting */ - const DeviceVector devicePosition( device( position ) ); + const DeviceVector devicePosition( device( position ) ); - if ( button == c_button_select || ( button == c_button_select2 && modifiers != c_modifierNone ) ) { - m_mouse_down = true; + if ( button == c_button_select || ( button == c_button_select2 && modifiers != c_modifierNone ) ) { + m_mouse_down = true; - const bool clipper2d( !m_manipulator.m_view->fill() && button == c_button_select && modifiers == c_modifierControl ); - if( clipper2d && getSelectionSystem().ManipulatorMode() != SelectionSystem::eClip ) - ClipperModeQuick(); + const bool clipper2d( !m_manipulator.m_view->fill() && button == c_button_select && modifiers == c_modifierControl ); + if( clipper2d && getSelectionSystem().ManipulatorMode() != SelectionSystem::eClip ) + ClipperModeQuick(); - if ( ( modifiers == c_modifier_manipulator - || clipper2d - || ( modifiers == c_modifierAlt && getSelectionSystem().Mode() == SelectionSystem::ePrimitive ) /* AltResize */ - || ( modifiers == ( c_modifierAlt | c_modifierControl ) && getSelectionSystem().Mode() == SelectionSystem::ePrimitive ) /* extrude */ - ) && m_manipulator.mouseDown( devicePosition ) ) { - g_mouseMovedCallback.insert( MouseEventCallback( Manipulator_::MouseMovedCaller( m_manipulator ) ) ); - g_mouseUpCallback.insert( MouseEventCallback( Manipulator_::MouseUpCaller( m_manipulator ) ) ); + if ( ( modifiers == c_modifier_manipulator + || clipper2d + || ( modifiers == c_modifierAlt && getSelectionSystem().Mode() == SelectionSystem::ePrimitive ) /* AltResize */ + || ( modifiers == ( c_modifierAlt | c_modifierControl ) && getSelectionSystem().Mode() == SelectionSystem::ePrimitive ) /* extrude */ + ) && m_manipulator.mouseDown( devicePosition ) ) { + g_mouseMovedCallback.insert( MouseEventCallback( Manipulator_::MouseMovedCaller( m_manipulator ) ) ); + g_mouseUpCallback.insert( MouseEventCallback( Manipulator_::MouseUpCaller( m_manipulator ) ) ); + } + else + { + m_selector.m_mouse2 = ( button != c_button_select ); + m_selector.mouseDown( devicePosition ); + g_mouseMovedCallback.insert( MouseEventCallback( Selector_::MouseMovedCaller( m_selector ) ) ); + g_mouseUpCallback.insert( MouseEventCallback( Selector_::MouseUpCaller( m_selector ) ) ); + } } - else - { - m_selector.m_mouse2 = ( button != c_button_select ); - m_selector.mouseDown( devicePosition ); - g_mouseMovedCallback.insert( MouseEventCallback( Selector_::MouseMovedCaller( m_selector ) ) ); - g_mouseUpCallback.insert( MouseEventCallback( Selector_::MouseUpCaller( m_selector ) ) ); + else if ( button == c_button_texture ) { + m_mouse_down = true; + m_texmanipulator.mouseDown( devicePosition ); + g_mouseMovedCallback.insert( MouseEventCallback( TexManipulator_::MouseMovedCaller( m_texmanipulator ) ) ); + g_mouseUpCallback.insert( MouseEventCallback( TexManipulator_::MouseUpCaller( m_texmanipulator ) ) ); + } + + m_moveStart = devicePosition; + m_movePressed = 0.f; + } + void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ){ + m_selector.m_mouseMoved = mouse_moved_epsilon( position, m_moveEnd, m_move ); + if ( m_mouse_down && !g_mouseMovedCallback.empty() ) { + m_manipulator.m_mouseMovedWhilePressed = m_selector.m_mouseMovedWhilePressed = mouse_moved_epsilon( position, m_moveStart, m_movePressed ); + g_mouseMovedCallback.get() ( device( position ) ); + } + else{ + m_manipulator.highlight( device( position ) ); } } - else if ( button == c_button_texture ) { - m_mouse_down = true; - m_texmanipulator.mouseDown( devicePosition ); - g_mouseMovedCallback.insert( MouseEventCallback( TexManipulator_::MouseMovedCaller( m_texmanipulator ) ) ); - g_mouseUpCallback.insert( MouseEventCallback( TexManipulator_::MouseUpCaller( m_texmanipulator ) ) ); - } + void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){ + if ( ( button == c_button_select || button == c_button_select2 || button == c_button_texture ) && !g_mouseUpCallback.empty() ) { + g_mouseUpCallback.get() ( device( position ) ); + m_mouse_down = false; + } + if( button == c_button_select /* L button w/o mouse moved = tunnel selection */ + && modifiers == c_modifierNone + && !m_selector.m_mouseMovedWhilePressed + && !m_manipulator.m_moving_transformOrigin + && !( getSelectionSystem().Mode() == SelectionSystem::eComponent && getSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag ) + && getSelectionSystem().ManipulatorMode() != SelectionSystem::eClip + && getSelectionSystem().ManipulatorMode() != SelectionSystem::eBuild ){ + m_selector.testSelect_simpleM1( device( position ) ); + } + if( getSelectionSystem().ManipulatorMode() == SelectionSystem::eClip ) + Clipper_tryDoubleclickedCut(); - m_moveStart = devicePosition; - m_movePressed = 0.f; -} -void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ){ - m_selector.m_mouseMoved = mouse_moved_epsilon( position, m_moveEnd, m_move ); - if ( m_mouse_down && !g_mouseMovedCallback.empty() ) { - m_manipulator.m_mouseMovedWhilePressed = m_selector.m_mouseMovedWhilePressed = mouse_moved_epsilon( position, m_moveStart, m_movePressed ); - g_mouseMovedCallback.get() ( device( position ) ); + m_manipulator.m_moving_transformOrigin = false; + m_selector.m_mouseMoved = false; + m_selector.m_mouseMovedWhilePressed = false; + m_manipulator.m_mouseMovedWhilePressed = false; + m_moveEnd = device( position ); + m_move = 0.f; } - else{ - m_manipulator.highlight( device( position ) ); + void onModifierDown( ModifierFlags type ){ + g_modifiers = m_state = bitfield_enable( m_state, type ); + m_selector.setState( m_state ); } -} -void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){ - if ( ( button == c_button_select || button == c_button_select2 || button == c_button_texture ) && !g_mouseUpCallback.empty() ) { - g_mouseUpCallback.get() ( device( position ) ); - m_mouse_down = false; + void onModifierUp( ModifierFlags type ){ + g_modifiers = m_state = bitfield_disable( m_state, type ); + m_selector.setState( m_state ); } - if( button == c_button_select /* L button w/o mouse moved = tunnel selection */ - && modifiers == c_modifierNone - && !m_selector.m_mouseMovedWhilePressed - && !m_manipulator.m_moving_transformOrigin - && !( getSelectionSystem().Mode() == SelectionSystem::eComponent && getSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag ) - && getSelectionSystem().ManipulatorMode() != SelectionSystem::eClip - && getSelectionSystem().ManipulatorMode() != SelectionSystem::eBuild ){ - m_selector.testSelect_simpleM1( device( position ) ); + DeviceVector device( WindowVector window ) const { + return window_to_normalised_device( window, m_width, m_height ); + } + bool mouse_moved_epsilon( const WindowVector& position, const DeviceVector& moveStart, float& move ){ + if( move > m_moveEpsilon ) + return true; + const DeviceVector devicePosition( device( position ) ); + const float currentMove = std::max( fabs( devicePosition.x() - moveStart.x() ), fabs( devicePosition.y() - moveStart.y() ) ); + move = std::max( move, currentMove ); + // globalOutputStream() << move << " move\n"; + return move > m_moveEpsilon; + } + /* support mouse_moved_epsilon with frozen pointer (camera freelook) */ + void incMouseMove( const WindowVector& delta ){ + const WindowVector normalized_delta( delta.x() * 2.f / m_width, delta.y() * 2.f / m_height ); + m_moveEnd -= normalized_delta; + if( m_mouse_down ) + m_moveStart -= normalized_delta; } - if( getSelectionSystem().ManipulatorMode() == SelectionSystem::eClip ) - Clipper_tryDoubleclickedCut(); - - m_manipulator.m_moving_transformOrigin = false; - m_selector.m_mouseMoved = false; - m_selector.m_mouseMovedWhilePressed = false; - m_manipulator.m_mouseMovedWhilePressed = false; - m_moveEnd = device( position ); - m_move = 0.f; -} -void onModifierDown( ModifierFlags type ){ - g_modifiers = m_state = bitfield_enable( m_state, type ); - m_selector.setState( m_state ); -} -void onModifierUp( ModifierFlags type ){ - g_modifiers = m_state = bitfield_disable( m_state, type ); - m_selector.setState( m_state ); -} -DeviceVector device( WindowVector window ) const { - return window_to_normalised_device( window, m_width, m_height ); -} -bool mouse_moved_epsilon( const WindowVector& position, const DeviceVector& moveStart, float& move ){ - if( move > m_moveEpsilon ) - return true; - const DeviceVector devicePosition( device( position ) ); - const float currentMove = std::max( fabs( devicePosition.x() - moveStart.x() ), fabs( devicePosition.y() - moveStart.y() ) ); - move = std::max( move, currentMove ); -// globalOutputStream() << move << " move\n"; - return move > m_moveEpsilon; -} -/* support mouse_moved_epsilon with frozen pointer (camera freelook) */ -void incMouseMove( const WindowVector& delta ){ - const WindowVector normalized_delta( delta.x() * 2.f / m_width, delta.y() * 2.f / m_height ); - m_moveEnd -= normalized_delta; - if( m_mouse_down ) - m_moveStart -= normalized_delta; -} }; @@ -8511,22 +8517,22 @@ class SelectionDependencies : class SelectionAPI : public TypeSystemRef { -SelectionSystem* m_selection; + SelectionSystem* m_selection; public: -typedef SelectionSystem Type; -STRING_CONSTANT( Name, "*" ); + typedef SelectionSystem Type; + STRING_CONSTANT( Name, "*" ); -SelectionAPI(){ - SelectionSystem_Construct(); + SelectionAPI(){ + SelectionSystem_Construct(); - m_selection = &getSelectionSystem(); -} -~SelectionAPI(){ - SelectionSystem_Destroy(); -} -SelectionSystem* getTable(){ - return m_selection; -} + m_selection = &getSelectionSystem(); + } + ~SelectionAPI(){ + SelectionSystem_Destroy(); + } + SelectionSystem* getTable(){ + return m_selection; + } }; typedef SingletonModule SelectionModule; diff --git a/radiant/selection.h b/radiant/selection.h index 4f8f8abe..d26ea618 100644 --- a/radiant/selection.h +++ b/radiant/selection.h @@ -33,9 +33,9 @@ class View; class SelectionSystemWindowObserver : public WindowObserver { public: -virtual void setView( const View& view ) = 0; -virtual void setRectangleDrawCallback( const RectangleCallback& callback ) = 0; -virtual void incMouseMove( const WindowVector& delta ) = 0; + virtual void setView( const View& view ) = 0; + virtual void setRectangleDrawCallback( const RectangleCallback& callback ) = 0; + virtual void incMouseMove( const WindowVector& delta ) = 0; }; SelectionSystemWindowObserver* NewWindowObserver(); diff --git a/radiant/server.cpp b/radiant/server.cpp index 1540f6a4..af38afa3 100644 --- a/radiant/server.cpp +++ b/radiant/server.cpp @@ -32,63 +32,63 @@ class RadiantModuleServer : public ModuleServer { -typedef std::pair ModuleType; -typedef std::pair ModuleKey; -typedef std::map Modules_; -Modules_ m_modules; -bool m_error; + typedef std::pair ModuleType; + typedef std::pair ModuleKey; + typedef std::map Modules_; + Modules_ m_modules; + bool m_error; public: -RadiantModuleServer() : m_error( false ){ -} - -void setError( bool error ){ - m_error = error; -} -bool getError() const { - return m_error; -} - -TextOutputStream& getOutputStream(){ - return globalOutputStream(); -} -TextOutputStream& getWarningStream(){ - return globalWarningStream(); -} -TextOutputStream& getErrorStream(){ - return globalErrorStream(); -} -DebugMessageHandler& getDebugMessageHandler(){ - return globalDebugMessageHandler(); -} - -void registerModule( const char* type, int version, const char* name, Module& module ){ - ASSERT_NOTNULL( (volatile intptr_t)&module ); - if ( !m_modules.insert( Modules_::value_type( ModuleKey( ModuleType( type, version ), name ), &module ) ).second ) { - globalErrorStream() << "module already registered: type=" << makeQuoted( type ) << " name=" << makeQuoted( name ) << "\n"; + RadiantModuleServer() : m_error( false ){ } - else - { - globalOutputStream() << "Module Registered: type=" << makeQuoted( type ) << " version=" << makeQuoted( version ) << " name=" << makeQuoted( name ) << "\n"; - } -} -Module* findModule( const char* type, int version, const char* name ) const { - Modules_::const_iterator i = m_modules.find( ModuleKey( ModuleType( type, version ), name ) ); - if ( i != m_modules.end() ) { - return ( *i ).second; + void setError( bool error ){ + m_error = error; + } + bool getError() const { + return m_error; } - return 0; -} -void foreachModule( const char* type, int version, const Visitor& visitor ){ - for ( Modules_::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - if ( string_equal( ( *i ).first.first.first.c_str(), type ) ) { - visitor.visit( ( *i ).first.second.c_str(), *( *i ).second ); + TextOutputStream& getOutputStream(){ + return globalOutputStream(); + } + TextOutputStream& getWarningStream(){ + return globalWarningStream(); + } + TextOutputStream& getErrorStream(){ + return globalErrorStream(); + } + DebugMessageHandler& getDebugMessageHandler(){ + return globalDebugMessageHandler(); + } + + void registerModule( const char* type, int version, const char* name, Module& module ){ + ASSERT_NOTNULL( (volatile intptr_t)&module ); + if ( !m_modules.insert( Modules_::value_type( ModuleKey( ModuleType( type, version ), name ), &module ) ).second ) { + globalErrorStream() << "module already registered: type=" << makeQuoted( type ) << " name=" << makeQuoted( name ) << "\n"; + } + else + { + globalOutputStream() << "Module Registered: type=" << makeQuoted( type ) << " version=" << makeQuoted( version ) << " name=" << makeQuoted( name ) << "\n"; + } + } + + Module* findModule( const char* type, int version, const char* name ) const { + Modules_::const_iterator i = m_modules.find( ModuleKey( ModuleType( type, version ), name ) ); + if ( i != m_modules.end() ) { + return ( *i ).second; + } + return 0; + } + + void foreachModule( const char* type, int version, const Visitor& visitor ){ + for ( Modules_::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + if ( string_equal( ( *i ).first.first.first.c_str(), type ) ) { + visitor.visit( ( *i ).first.second.c_str(), *( *i ).second ); + } } } -} }; @@ -100,47 +100,47 @@ void foreachModule( const char* type, int version, const Visitor& visitor ){ const char* FormatGetLastError(){ static char buf[FORMAT_BUFSIZE]; FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language - buf, - FORMAT_BUFSIZE, - NULL - ); + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + buf, + FORMAT_BUFSIZE, + NULL + ); return buf; } class DynamicLibrary { -HMODULE m_library; + HMODULE m_library; public: -typedef int ( __stdcall * FunctionPointer )(); + typedef int ( __stdcall * FunctionPointer )(); -DynamicLibrary( const char* filename ){ - m_library = LoadLibrary( filename ); - if ( m_library == 0 ) { - globalErrorStream() << "LoadLibrary failed: '" << filename << "'\n"; - globalErrorStream() << "GetLastError: " << FormatGetLastError(); + DynamicLibrary( const char* filename ){ + m_library = LoadLibrary( filename ); + if ( m_library == 0 ) { + globalErrorStream() << "LoadLibrary failed: '" << filename << "'\n"; + globalErrorStream() << "GetLastError: " << FormatGetLastError(); + } } -} -~DynamicLibrary(){ - if ( !failed() ) { - FreeLibrary( m_library ); + ~DynamicLibrary(){ + if ( !failed() ) { + FreeLibrary( m_library ); + } } -} -bool failed(){ - return m_library == 0; -} -FunctionPointer findSymbol( const char* symbol ){ - FunctionPointer address = (FunctionPointer) GetProcAddress( m_library, symbol ); - if ( address == 0 ) { - globalErrorStream() << "GetProcAddress failed: '" << symbol << "'\n"; - globalErrorStream() << "GetLastError: " << FormatGetLastError(); + bool failed(){ + return m_library == 0; + } + FunctionPointer findSymbol( const char* symbol ){ + FunctionPointer address = (FunctionPointer) GetProcAddress( m_library, symbol ); + if ( address == 0 ) { + globalErrorStream() << "GetProcAddress failed: '" << symbol << "'\n"; + globalErrorStream() << "GetLastError: " << FormatGetLastError(); + } + return address; } - return address; -} }; #elif defined( POSIX ) @@ -153,31 +153,31 @@ FunctionPointer findSymbol( const char* symbol ){ class DynamicLibrary { -void* m_library; + void* m_library; public: -typedef int ( *FunctionPointer )(); + typedef int ( *FunctionPointer )(); -DynamicLibrary( const char* filename ){ - m_library = dlopen( filename, RTLD_NOW | (RTLD_DEEPBIND + 0) ); -} -~DynamicLibrary(){ - if ( !failed() ) { - dlclose( m_library ); + DynamicLibrary( const char* filename ){ + m_library = dlopen( filename, RTLD_NOW | (RTLD_DEEPBIND + 0) ); } -} -bool failed(){ - return m_library == 0; -} -FunctionPointer findSymbol( const char* symbol ){ - FunctionPointer p = (FunctionPointer)dlsym( m_library, symbol ); - if ( p == 0 ) { - const char* error = reinterpret_cast( dlerror() ); - if ( error != 0 ) { - globalErrorStream() << error; + ~DynamicLibrary(){ + if ( !failed() ) { + dlclose( m_library ); } } - return p; -} + bool failed(){ + return m_library == 0; + } + FunctionPointer findSymbol( const char* symbol ){ + FunctionPointer p = (FunctionPointer)dlsym( m_library, symbol ); + if ( p == 0 ) { + const char* error = reinterpret_cast( dlerror() ); + if ( error != 0 ) { + globalErrorStream() << error; + } + } + return p; + } }; #else @@ -186,60 +186,60 @@ FunctionPointer findSymbol( const char* symbol ){ class DynamicLibraryModule { -typedef void ( RADIANT_DLLIMPORT * RegisterModulesFunc )( ModuleServer& server ); -DynamicLibrary m_library; -RegisterModulesFunc m_registerModule; + typedef void ( RADIANT_DLLIMPORT * RegisterModulesFunc )( ModuleServer& server ); + DynamicLibrary m_library; + RegisterModulesFunc m_registerModule; public: -DynamicLibraryModule( const char* filename ) - : m_library( filename ), m_registerModule( 0 ){ - if ( !m_library.failed() ) { - m_registerModule = reinterpret_cast( m_library.findSymbol( "Radiant_RegisterModules" ) ); + DynamicLibraryModule( const char* filename ) + : m_library( filename ), m_registerModule( 0 ){ + if ( !m_library.failed() ) { + m_registerModule = reinterpret_cast( m_library.findSymbol( "Radiant_RegisterModules" ) ); #if 0 - if ( !m_registerModule ) { - m_registerModule = reinterpret_cast( m_library.findSymbol( "Radiant_RegisterModules@4" ) ); - } + if ( !m_registerModule ) { + m_registerModule = reinterpret_cast( m_library.findSymbol( "Radiant_RegisterModules@4" ) ); + } #endif + } + } + bool failed(){ + return m_registerModule == 0; + } + void registerModules( ModuleServer& server ){ + m_registerModule( server ); } -} -bool failed(){ - return m_registerModule == 0; -} -void registerModules( ModuleServer& server ){ - m_registerModule( server ); -} }; class Libraries { -typedef std::vector libraries_t; -libraries_t m_libraries; + typedef std::vector libraries_t; + libraries_t m_libraries; public: -~Libraries(){ - release(); -} -void registerLibrary( const char* filename, ModuleServer& server ){ - DynamicLibraryModule* library = new DynamicLibraryModule( filename ); + ~Libraries(){ + release(); + } + void registerLibrary( const char* filename, ModuleServer& server ){ + DynamicLibraryModule* library = new DynamicLibraryModule( filename ); - if ( library->failed() ) { - delete library; + if ( library->failed() ) { + delete library; + } + else + { + m_libraries.push_back( library ); + library->registerModules( server ); + } } - else - { - m_libraries.push_back( library ); - library->registerModules( server ); + void release(){ + for ( libraries_t::iterator i = m_libraries.begin(); i != m_libraries.end(); ++i ) + { + delete *i; + } } -} -void release(){ - for ( libraries_t::iterator i = m_libraries.begin(); i != m_libraries.end(); ++i ) - { - delete *i; + void clear(){ + m_libraries.clear(); } -} -void clear(){ - m_libraries.clear(); -} }; diff --git a/radiant/stacktrace.cpp b/radiant/stacktrace.cpp index 51ef5038..d6944b92 100644 --- a/radiant/stacktrace.cpp +++ b/radiant/stacktrace.cpp @@ -57,9 +57,9 @@ void write_stack_trace( TextOutputStream& outputStream ){ class Address { public: -void* m_value; -Address( void* value ) : m_value( value ){ -} + void* m_value; + Address( void* value ) : m_value( value ){ + } }; /// \brief Writes an address \p p to \p ostream in hexadecimal form. @@ -74,9 +74,9 @@ inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const class Offset { public: -void* m_value; -Offset( void* value ) : m_value( value ){ -} + void* m_value; + Offset( void* value ) : m_value( value ){ + } }; /// \brief Writes an address \p p to \p ostream in hexadecimal form. @@ -112,16 +112,16 @@ void write_symbol( PSYMBOL_INFO pSym, STACKFRAME64& sf, TextOutputStream& output DWORD basicType; if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_BASETYPE, &basicType ) ) { + TI_GET_BASETYPE, &basicType ) ) { int bleh = 0; } else { DWORD typeId; if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_TYPEID, &typeId ) ) { + TI_GET_TYPEID, &typeId ) ) { if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_BASETYPE, &basicType ) ) { + TI_GET_BASETYPE, &basicType ) ) { int bleh = 0; } else @@ -132,7 +132,7 @@ void write_symbol( PSYMBOL_INFO pSym, STACKFRAME64& sf, TextOutputStream& output WCHAR* name; if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, typeId, - TI_GET_SYMNAME, &name ) ) { + TI_GET_SYMNAME, &name ) ) { outputStream << name << " "; LocalFree( name ); int bleh = 0; @@ -163,9 +163,9 @@ void write_symbol( PSYMBOL_INFO pSym, STACKFRAME64& sf, TextOutputStream& output BOOL CALLBACK EnumerateSymbolsCallback( - PSYMBOL_INFO pSymInfo, - ULONG SymbolSize, - PVOID UserContext ){ + PSYMBOL_INFO pSymInfo, + ULONG SymbolSize, + PVOID UserContext ){ write_symbol( pSymInfo, ( (EnumerateSymbolsContext*)UserContext )->sf, ( (EnumerateSymbolsContext*)UserContext )->outputStream, ( (EnumerateSymbolsContext*)UserContext )->count ); @@ -214,14 +214,14 @@ void write_stack_trace( PCONTEXT pContext, TextOutputStream& outputStream ){ { // Get the next stack frame if ( !StackWalk64( dwMachineType, - m_hProcess, - GetCurrentThread(), - &sf, - &context, - 0, - SymFunctionTableAccess64, - SymGetModuleBase64, - 0 ) ) { + m_hProcess, + GetCurrentThread(), + &sf, + &context, + 0, + SymFunctionTableAccess64, + SymGetModuleBase64, + 0 ) ) { break; } @@ -236,7 +236,7 @@ void write_stack_trace( PCONTEXT pContext, TextOutputStream& outputStream ){ pSymbol->MaxNameLen = max_sym_name; DWORD64 symDisplacement = 0; // Displacement of the input address, - // relative to the start of the symbol + // relative to the start of the symbol IMAGEHLP_MODULE64 module = { sizeof( IMAGEHLP_MODULE64 ) }; if ( SymGetModuleInfo64( m_hProcess, sf.AddrPC.Offset, &module ) ) { @@ -265,7 +265,7 @@ void write_stack_trace( PCONTEXT pContext, TextOutputStream& outputStream ){ IMAGEHLP_LINE64 lineInfo = { sizeof( IMAGEHLP_LINE64 ) }; DWORD dwLineDisplacement; if ( SymGetLineFromAddr64( m_hProcess, sf.AddrPC.Offset, - &dwLineDisplacement, &lineInfo ) ) { + &dwLineDisplacement, &lineInfo ) ) { outputStream << " " << lineInfo.FileName << " line " << Unsigned( lineInfo.LineNumber ); } } @@ -284,7 +284,10 @@ void write_stack_trace( PCONTEXT pContext, TextOutputStream& outputStream ){ } void write_stack_trace( TextOutputStream& outputStream ){ - __try { RaiseException( 0,0,0,0 ); } __except( write_stack_trace( ( GetExceptionInformation() )->ContextRecord, outputStream ), EXCEPTION_CONTINUE_EXECUTION ) { + __try { + RaiseException( 0,0,0,0 ); + } + __except( write_stack_trace( ( GetExceptionInformation() )->ContextRecord, outputStream ), EXCEPTION_CONTINUE_EXECUTION ) { } } diff --git a/radiant/surfacedialog.cpp b/radiant/surfacedialog.cpp index 48b95874..6d7530b3 100644 --- a/radiant/surfacedialog.cpp +++ b/radiant/surfacedialog.cpp @@ -118,127 +118,127 @@ inline void spin_button_set_step( GtkSpinButton* spin, gfloat step ){ class Increment { -float& m_f; + float& m_f; public: -GtkSpinButton* m_spin; -GtkEntry* m_entry; -Increment( float& f ) : m_f( f ), m_spin( 0 ), m_entry( 0 ){ -} -void cancel(){ - entry_set_float( m_entry, m_f ); -} -typedef MemberCaller CancelCaller; -void apply(){ - m_f = static_cast( entry_get_float( m_entry ) ); - spin_button_set_step( m_spin, m_f ); -} -typedef MemberCaller ApplyCaller; + GtkSpinButton* m_spin; + GtkEntry* m_entry; + Increment( float& f ) : m_f( f ), m_spin( 0 ), m_entry( 0 ){ + } + void cancel(){ + entry_set_float( m_entry, m_f ); + } + typedef MemberCaller CancelCaller; + void apply(){ + m_f = static_cast( entry_get_float( m_entry ) ); + spin_button_set_step( m_spin, m_f ); + } + typedef MemberCaller ApplyCaller; }; void SurfaceInspector_GridChange(); class SurfaceInspector : public Dialog { -GtkWindow* BuildDialog(); + GtkWindow* BuildDialog(); -NonModalEntry m_textureEntry; -NonModalSpinner m_hshiftSpinner; -NonModalEntry m_hshiftEntry; -NonModalSpinner m_vshiftSpinner; -NonModalEntry m_vshiftEntry; -NonModalSpinner m_hscaleSpinner; -NonModalEntry m_hscaleEntry; -NonModalSpinner m_vscaleSpinner; -NonModalEntry m_vscaleEntry; -NonModalSpinner m_rotateSpinner; -NonModalEntry m_rotateEntry; + NonModalEntry m_textureEntry; + NonModalSpinner m_hshiftSpinner; + NonModalEntry m_hshiftEntry; + NonModalSpinner m_vshiftSpinner; + NonModalEntry m_vshiftEntry; + NonModalSpinner m_hscaleSpinner; + NonModalEntry m_hscaleEntry; + NonModalSpinner m_vscaleSpinner; + NonModalEntry m_vscaleEntry; + NonModalSpinner m_rotateSpinner; + NonModalEntry m_rotateEntry; -IdleDraw m_idleDraw; + IdleDraw m_idleDraw; -GtkCheckButton* m_surfaceFlags[32]; -GtkCheckButton* m_contentFlags[32]; + GtkCheckButton* m_surfaceFlags[32]; + GtkCheckButton* m_contentFlags[32]; -NonModalEntry m_valueEntry; -GtkEntry* m_valueEntryWidget; + NonModalEntry m_valueEntry; + GtkEntry* m_valueEntryWidget; public: -WindowPositionTracker m_positionTracker; -WindowPositionTrackerImportStringCaller m_importPosition; -WindowPositionTrackerExportStringCaller m_exportPosition; + WindowPositionTracker m_positionTracker; + WindowPositionTrackerImportStringCaller m_importPosition; + WindowPositionTrackerExportStringCaller m_exportPosition; // Dialog Data -float m_fitHorizontal; -float m_fitVertical; + float m_fitHorizontal; + float m_fitVertical; -Increment m_hshiftIncrement; -Increment m_vshiftIncrement; -Increment m_hscaleIncrement; -Increment m_vscaleIncrement; -Increment m_rotateIncrement; -GtkEntry* m_texture; + Increment m_hshiftIncrement; + Increment m_vshiftIncrement; + Increment m_hscaleIncrement; + Increment m_vscaleIncrement; + Increment m_rotateIncrement; + GtkEntry* m_texture; -SurfaceInspector() : - m_textureEntry( ApplyShaderCaller( *this ), UpdateCaller( *this ) ), - m_hshiftSpinner( ApplyTexdef_HShiftCaller( *this ), UpdateCaller( *this ) ), - m_hshiftEntry( Increment::ApplyCaller( m_hshiftIncrement ), Increment::CancelCaller( m_hshiftIncrement ) ), - m_vshiftSpinner( ApplyTexdef_VShiftCaller( *this ), UpdateCaller( *this ) ), - m_vshiftEntry( Increment::ApplyCaller( m_vshiftIncrement ), Increment::CancelCaller( m_vshiftIncrement ) ), - m_hscaleSpinner( ApplyTexdef_HScaleCaller( *this ), UpdateCaller( *this ) ), - m_hscaleEntry( Increment::ApplyCaller( m_hscaleIncrement ), Increment::CancelCaller( m_hscaleIncrement ) ), - m_vscaleSpinner( ApplyTexdef_VScaleCaller( *this ), UpdateCaller( *this ) ), - m_vscaleEntry( Increment::ApplyCaller( m_vscaleIncrement ), Increment::CancelCaller( m_vscaleIncrement ) ), - m_rotateSpinner( ApplyTexdef_RotationCaller( *this ), UpdateCaller( *this ) ), - m_rotateEntry( Increment::ApplyCaller( m_rotateIncrement ), Increment::CancelCaller( m_rotateIncrement ) ), - m_idleDraw( UpdateCaller( *this ) ), - m_valueEntry( ApplyFlagsCaller( *this ), UpdateCaller( *this ) ), - m_importPosition( m_positionTracker ), - m_exportPosition( m_positionTracker ), - m_hshiftIncrement( g_si_globals.shift[0] ), - m_vshiftIncrement( g_si_globals.shift[1] ), - m_hscaleIncrement( g_si_globals.scale[0] ), - m_vscaleIncrement( g_si_globals.scale[1] ), - m_rotateIncrement( g_si_globals.rotate ){ - m_fitVertical = 1; - m_fitHorizontal = 1; - m_positionTracker.setPosition( WindowPosition( -1, -1, 300, 400 ) ); -} - -void constructWindow( GtkWindow* main_window ){ - m_parent = main_window; - Create(); - AddGridChangeCallback( FreeCaller() ); -} -void destroyWindow(){ - Destroy(); -} -bool visible() const { - return gtk_widget_get_visible( GTK_WIDGET( GetWidget() ) ); -} -void queueDraw(){ - if ( visible() ) { - m_idleDraw.queueDraw(); + SurfaceInspector() : + m_textureEntry( ApplyShaderCaller( *this ), UpdateCaller( *this ) ), + m_hshiftSpinner( ApplyTexdef_HShiftCaller( *this ), UpdateCaller( *this ) ), + m_hshiftEntry( Increment::ApplyCaller( m_hshiftIncrement ), Increment::CancelCaller( m_hshiftIncrement ) ), + m_vshiftSpinner( ApplyTexdef_VShiftCaller( *this ), UpdateCaller( *this ) ), + m_vshiftEntry( Increment::ApplyCaller( m_vshiftIncrement ), Increment::CancelCaller( m_vshiftIncrement ) ), + m_hscaleSpinner( ApplyTexdef_HScaleCaller( *this ), UpdateCaller( *this ) ), + m_hscaleEntry( Increment::ApplyCaller( m_hscaleIncrement ), Increment::CancelCaller( m_hscaleIncrement ) ), + m_vscaleSpinner( ApplyTexdef_VScaleCaller( *this ), UpdateCaller( *this ) ), + m_vscaleEntry( Increment::ApplyCaller( m_vscaleIncrement ), Increment::CancelCaller( m_vscaleIncrement ) ), + m_rotateSpinner( ApplyTexdef_RotationCaller( *this ), UpdateCaller( *this ) ), + m_rotateEntry( Increment::ApplyCaller( m_rotateIncrement ), Increment::CancelCaller( m_rotateIncrement ) ), + m_idleDraw( UpdateCaller( *this ) ), + m_valueEntry( ApplyFlagsCaller( *this ), UpdateCaller( *this ) ), + m_importPosition( m_positionTracker ), + m_exportPosition( m_positionTracker ), + m_hshiftIncrement( g_si_globals.shift[0] ), + m_vshiftIncrement( g_si_globals.shift[1] ), + m_hscaleIncrement( g_si_globals.scale[0] ), + m_vscaleIncrement( g_si_globals.scale[1] ), + m_rotateIncrement( g_si_globals.rotate ){ + m_fitVertical = 1; + m_fitHorizontal = 1; + m_positionTracker.setPosition( WindowPosition( -1, -1, 300, 400 ) ); } -} -void Update(); -typedef MemberCaller UpdateCaller; -void ApplyShader(); -typedef MemberCaller ApplyShaderCaller; + void constructWindow( GtkWindow* main_window ){ + m_parent = main_window; + Create(); + AddGridChangeCallback( FreeCaller() ); + } + void destroyWindow(){ + Destroy(); + } + bool visible() const { + return gtk_widget_get_visible( GTK_WIDGET( GetWidget() ) ); + } + void queueDraw(){ + if ( visible() ) { + m_idleDraw.queueDraw(); + } + } + + void Update(); + typedef MemberCaller UpdateCaller; + void ApplyShader(); + typedef MemberCaller ApplyShaderCaller; //void ApplyTexdef(); //typedef MemberCaller ApplyTexdefCaller; -void ApplyTexdef_HShift(); -typedef MemberCaller ApplyTexdef_HShiftCaller; -void ApplyTexdef_VShift(); -typedef MemberCaller ApplyTexdef_VShiftCaller; -void ApplyTexdef_HScale(); -typedef MemberCaller ApplyTexdef_HScaleCaller; -void ApplyTexdef_VScale(); -typedef MemberCaller ApplyTexdef_VScaleCaller; -void ApplyTexdef_Rotation(); -typedef MemberCaller ApplyTexdef_RotationCaller; + void ApplyTexdef_HShift(); + typedef MemberCaller ApplyTexdef_HShiftCaller; + void ApplyTexdef_VShift(); + typedef MemberCaller ApplyTexdef_VShiftCaller; + void ApplyTexdef_HScale(); + typedef MemberCaller ApplyTexdef_HScaleCaller; + void ApplyTexdef_VScale(); + typedef MemberCaller ApplyTexdef_VScaleCaller; + void ApplyTexdef_Rotation(); + typedef MemberCaller ApplyTexdef_RotationCaller; -void ApplyFlags(); -typedef MemberCaller ApplyFlagsCaller; + void ApplyFlags(); + typedef MemberCaller ApplyFlagsCaller; }; namespace @@ -757,8 +757,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 2 ) ); @@ -766,8 +766,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ m_hshiftSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 60, -1 ); } { @@ -775,15 +775,15 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); m_hshiftIncrement.m_entry = entry; m_hshiftEntry.connect( entry ); @@ -793,8 +793,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 2 ) ); @@ -802,8 +802,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ m_vshiftSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 60, -1 ); } { @@ -811,15 +811,15 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); m_vshiftIncrement.m_entry = entry; m_vshiftEntry.connect( entry ); @@ -829,8 +829,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 5 ) ); @@ -838,8 +838,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ m_hscaleSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 60, -1 ); } { @@ -847,15 +847,15 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 2, 3 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 2, 3 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 2, 3 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 2, 3 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); m_hscaleIncrement.m_entry = entry; m_hscaleEntry.connect( entry ); @@ -865,8 +865,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 5 ) ); @@ -874,8 +874,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ m_vscaleSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 60, -1 ); } { @@ -883,15 +883,15 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); m_vscaleIncrement.m_entry = entry; m_vscaleEntry.connect( entry ); @@ -901,8 +901,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 4, 5, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 45, 0 ) ), 0, 2 ) ); @@ -910,8 +910,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ m_rotateSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 4, 5, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( spin ), 60, -1 ); gtk_spin_button_set_wrap( spin, TRUE ); } @@ -920,15 +920,15 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 4, 5, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 4, 5, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( GTK_WIDGET( entry ), 50, -1 ); m_rotateIncrement.m_entry = entry; m_rotateEntry.connect( entry ); @@ -938,8 +938,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkWidget* button = gtk_button_new_with_label( "Match Grid" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 4, 5, 6, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnMatchGrid ), 0 ); } } @@ -959,25 +959,25 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkWidget* label = gtk_label_new( "Brush" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( "Patch" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 3, 4, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* button = gtk_button_new_with_label( "Width" ); gtk_widget_set_tooltip_text( button, "Fit texture width, scale height\nRightClick: fit width, keep height" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnFaceFitWidth ), 0 ); + G_CALLBACK( OnBtnFaceFitWidth ), 0 ); g_signal_connect( G_OBJECT( button ), "button_press_event", G_CALLBACK( OnBtnFaceFitWidthOnly ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } @@ -986,10 +986,10 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_set_tooltip_text( button, "Fit texture height, scale width\nRightClick: fit height, keep width" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 3, 4, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnFaceFitHeight ), 0 ); + G_CALLBACK( OnBtnFaceFitHeight ), 0 ); g_signal_connect( G_OBJECT( button ), "button_press_event", G_CALLBACK( OnBtnFaceFitHeightOnly ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } @@ -997,38 +997,38 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkWidget* button = gtk_button_new_with_label( "Reset" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnReset ), 0 ); + G_CALLBACK( OnBtnReset ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* button = gtk_button_new_with_label( "Fit" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 1, 2, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnFaceFit ), 0 ); + G_CALLBACK( OnBtnFaceFit ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* label = gtk_label_new( "Project:" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, - (GtkAttachOptions) ( GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* button = gtk_button_new_with_label( "Axial" ); gtk_widget_set_tooltip_text( button, "Axial projection (along nearest axis)" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 1, 2, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnProject ), (gpointer)eProjectAxial ); + G_CALLBACK( OnBtnProject ), (gpointer)eProjectAxial ); GtkRequisition req; gtk_widget_size_request( button, &req ); gtk_widget_set_size_request( button, 60, req.height * 3 / 4 ); @@ -1038,10 +1038,10 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_set_tooltip_text( button, "Project along active ortho view" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnProject ), (gpointer)eProjectOrtho ); + G_CALLBACK( OnBtnProject ), (gpointer)eProjectOrtho ); GtkRequisition req; gtk_widget_size_request( button, &req ); gtk_widget_set_size_request( button, 60, req.height * 3 / 4 ); @@ -1051,10 +1051,10 @@ GtkWindow* SurfaceInspector::BuildDialog(){ gtk_widget_set_tooltip_text( button, "Project along camera view direction" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 3, 4, 2, 3, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 5 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnProject ), (gpointer)eProjectCam ); + G_CALLBACK( OnBtnProject ), (gpointer)eProjectCam ); GtkRequisition req; gtk_widget_size_request( button, &req ); gtk_widget_set_size_request( button, 60, req.height * 3 / 4 ); @@ -1063,48 +1063,48 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkWidget* button = gtk_button_new_with_label( "CAP" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 4, 5, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnPatchCap ), 0 ); + G_CALLBACK( OnBtnPatchCap ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* button = gtk_button_new_with_label( "Set..." ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 1, 2, 4, 5, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnPatchFit ), 0 ); + G_CALLBACK( OnBtnPatchFit ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* button = gtk_button_new_with_label( "Natural" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 4, 5, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnPatchNatural ), 0 ); + G_CALLBACK( OnBtnPatchNatural ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* button = gtk_button_new_with_label( "Fit" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 3, 4, 4, 5, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", - G_CALLBACK( OnBtnPatchFit11 ), 0 ); + G_CALLBACK( OnBtnPatchFit11 ), 0 ); gtk_widget_set_size_request( button, 60, -1 ); } { GtkWidget* spin = gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 1, 0, 1 << 16, 1, 10, 0 ) ), 0, 3 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 2, 3, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); AddDialogData( *GTK_SPIN_BUTTON( spin ), m_fitHorizontal ); } @@ -1112,8 +1112,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkWidget* spin = gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 1, 0, 1 << 16, 1, 10, 0 ) ), 0, 3 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 3, 4, 1, 2, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_size_request( spin, 60, -1 ); AddDialogData( *GTK_SPIN_BUTTON( spin ), m_fitVertical ); } @@ -1145,8 +1145,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new_with_label( getSurfaceFlagName( c * 8 + r ) ) ); gtk_widget_show( GTK_WIDGET( check ) ); gtk_table_attach( table, GTK_WIDGET( check ), c, c + 1, r, r + 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); *p++ = check; guint handler_id = togglebutton_connect_toggled( GTK_TOGGLE_BUTTON( check ), ApplyFlagsCaller( *this ) ); g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler_id ) ); @@ -1181,8 +1181,8 @@ GtkWindow* SurfaceInspector::BuildDialog(){ GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new_with_label( getContentFlagName( c * 8 + r ) ) ); gtk_widget_show( GTK_WIDGET( check ) ); gtk_table_attach( table, GTK_WIDGET( check ), c, c + 1, r, r + 1, - (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions)( 0 ), 0, 0 ); + (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions)( 0 ), 0, 0 ); *p++ = check; guint handler_id = togglebutton_connect_toggled( GTK_TOGGLE_BUTTON( check ), ApplyFlagsCaller( *this ) ); g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler_id ) ); @@ -1637,7 +1637,7 @@ void Face_getClosest( Face& face, SelectionTest& test, SelectionIntersection& be SelectionIntersection intersection; face.testSelect( test, intersection ); if ( intersection.valid() - && SelectionIntersection_closer( intersection, bestIntersection ) ) { + && SelectionIntersection_closer( intersection, bestIntersection ) ) { bestIntersection = intersection; texturable.setTexture = makeCallback4( FaceSetTexture(), face ); texturable.getTexture = makeCallback2( FaceGetTexture(), face ); @@ -1647,71 +1647,71 @@ void Face_getClosest( Face& face, SelectionTest& test, SelectionIntersection& be class OccludeSelector : public Selector { -SelectionIntersection& m_bestIntersection; -bool& m_occluded; + SelectionIntersection& m_bestIntersection; + bool& m_occluded; public: -OccludeSelector( SelectionIntersection& bestIntersection, bool& occluded ) : m_bestIntersection( bestIntersection ), m_occluded( occluded ){ - m_occluded = false; -} -void pushSelectable( Selectable& selectable ){ -} -void popSelectable(){ -} -void addIntersection( const SelectionIntersection& intersection ){ - if ( SelectionIntersection_closer( intersection, m_bestIntersection ) ) { - m_bestIntersection = intersection; - m_occluded = true; + OccludeSelector( SelectionIntersection& bestIntersection, bool& occluded ) : m_bestIntersection( bestIntersection ), m_occluded( occluded ){ + m_occluded = false; + } + void pushSelectable( Selectable& selectable ){ + } + void popSelectable(){ + } + void addIntersection( const SelectionIntersection& intersection ){ + if ( SelectionIntersection_closer( intersection, m_bestIntersection ) ) { + m_bestIntersection = intersection; + m_occluded = true; + } } -} }; #include "eclasslib.h" class BrushGetClosestFaceVisibleWalker : public scene::Graph::Walker { -SelectionTest& m_test; -Texturable& m_texturable; -mutable SelectionIntersection m_bestIntersection; + SelectionTest& m_test; + Texturable& m_texturable; + mutable SelectionIntersection m_bestIntersection; public: -BrushGetClosestFaceVisibleWalker( SelectionTest& test, Texturable& texturable ) : m_test( test ), m_texturable( texturable ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( !path.top().get().visible() ) - return false; - BrushInstance* brush = Instance_getBrush( instance ); - if ( brush != 0 ) { - m_test.BeginMesh( brush->localToWorld() ); - - for ( Brush::const_iterator i = brush->getBrush().begin(); i != brush->getBrush().end(); ++i ) - { - Face_getClosest( *( *i ), m_test, m_bestIntersection, m_texturable ); - } + BrushGetClosestFaceVisibleWalker( SelectionTest& test, Texturable& texturable ) : m_test( test ), m_texturable( texturable ){ } - else - { - SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); - if ( selectionTestable ) { - bool occluded; - OccludeSelector selector( m_bestIntersection, occluded ); - selectionTestable->testSelect( selector, m_test ); - if ( occluded ) { - Patch* patch = Node_getPatch( path.top() ); - if ( patch != 0 ) { - m_texturable.setTexture = makeCallback4( PatchSetTexture(), *patch ); - m_texturable.getTexture = makeCallback2( PatchGetTexture(), *patch ); - return true; - } - Entity* entity = Node_getEntity( path.top() ); - if( entity != 0 && string_equal_n( entity->getEntityClass().name(), "light", 5 ) ){ - m_texturable.setTexture = makeCallback4( LightSetTexture(), *entity ); - m_texturable.getTexture = makeCallback2( LightGetTexture(), *entity ); - } - else{ - m_texturable = Texturable(); + bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( !path.top().get().visible() ) + return false; + BrushInstance* brush = Instance_getBrush( instance ); + if ( brush != 0 ) { + m_test.BeginMesh( brush->localToWorld() ); + + for ( Brush::const_iterator i = brush->getBrush().begin(); i != brush->getBrush().end(); ++i ) + { + Face_getClosest( *( *i ), m_test, m_bestIntersection, m_texturable ); + } + } + else + { + SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); + if ( selectionTestable ) { + bool occluded; + OccludeSelector selector( m_bestIntersection, occluded ); + selectionTestable->testSelect( selector, m_test ); + if ( occluded ) { + Patch* patch = Node_getPatch( path.top() ); + if ( patch != 0 ) { + m_texturable.setTexture = makeCallback4( PatchSetTexture(), *patch ); + m_texturable.getTexture = makeCallback2( PatchGetTexture(), *patch ); + return true; + } + Entity* entity = Node_getEntity( path.top() ); + if( entity != 0 && string_equal_n( entity->getEntityClass().name(), "light", 5 ) ){ + m_texturable.setTexture = makeCallback4( LightSetTexture(), *entity ); + m_texturable.getTexture = makeCallback2( LightGetTexture(), *entity ); + } + else{ + m_texturable = Texturable(); + } } } } + return true; } - return true; -} }; Texturable Scene_getClosestTexturable( scene::Graph& graph, SelectionTest& test ){ @@ -2206,7 +2206,7 @@ void focus(){ // << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; // TTimo: Apply a ratio to get the area we'll draw. center.x() = 0.5f * ( extents.minX + extents.maxX ), - center.y() = 0.5f * ( extents.minY + extents.maxY ); + center.y() = 0.5f * ( extents.minY + extents.maxY ); extents.minX = center.x() + VP_PADDING * ( extents.minX - center.x() ), extents.minY = center.y() + VP_PADDING * ( extents.minY - center.y() ), extents.maxX = center.x() + VP_PADDING * ( extents.maxX - center.x() ), @@ -2218,7 +2218,7 @@ void focus(){ // TTimo: Compute XY space / window size ratio. float SSize = extents.width(), TSize = extents.height(); float ratioX = textureSize.x() * extents.width() / windowSize.x(), - ratioY = textureSize.y() * extents.height() / windowSize.y(); + ratioY = textureSize.y() * extents.height() / windowSize.y(); //globalOutputStream() << "--> Texture size: " << textureSize.x() << ", " << textureSize.y() << "\n"; //globalOutputStream() << "--> Window size: " << windowSize.x() << ", " << windowSize.y() << "\n"; @@ -2437,8 +2437,7 @@ gboolean button_release( GtkWidget * win, GdkEventButton * e, gpointer ){ GlobalUndoSystem().finish( "textoolUnknown" ); } - rotating = translatingX = translatingY = scalingX = scalingY - = resizingX = resizingY = false; + rotating = translatingX = translatingY = scalingX = scalingY = resizingX = resizingY = false; queueDraw(); } @@ -2615,23 +2614,22 @@ gboolean motion( GtkWidget * win, GdkEventMotion * e, gpointer ){ ny = -ny; //Cool! It works! Now just need to do rotation... - rotating = translatingX = translatingY = scalingX = scalingY - = resizingX = resizingY = false; + rotating = translatingX = translatingY = scalingX = scalingY = resizingX = resizingY = false; if ( dist < ( gridRadius * 0.16f ) ) { translatingX = translatingY = true; } else if ( dist > ( gridRadius * 0.16f ) && dist < ( gridRadius * 1.10f ) - && fabs( ny ) < ( gridRadius * 0.05f ) && nx > 0 ) { + && fabs( ny ) < ( gridRadius * 0.05f ) && nx > 0 ) { translatingX = true; } else if ( dist > ( gridRadius * 0.16f ) && dist < ( gridRadius * 1.10f ) - && fabs( nx ) < ( gridRadius * 0.05f ) && ny > 0 ) { + && fabs( nx ) < ( gridRadius * 0.05f ) && ny > 0 ) { translatingY = true; } // Should tighten up the angle on this, or put this test after the axis tests... else if ( tran.x() > 0 && tran.y() > 0 - && ( dist > ( gridRadius * 0.82f ) && dist < ( gridRadius * 0.98f ) ) ) { + && ( dist > ( gridRadius * 0.82f ) && dist < ( gridRadius * 0.98f ) ) ) { rotating = true; } diff --git a/radiant/textureentry.h b/radiant/textureentry.h index c28fe8ae..1deccd70 100644 --- a/radiant/textureentry.h +++ b/radiant/textureentry.h @@ -36,79 +36,79 @@ template class EntryCompletion { -GtkListStore* m_store; -bool m_invalid; + GtkListStore* m_store; + bool m_invalid; public: -EntryCompletion() : m_store( 0 ), m_invalid( true ){ -} - -static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, EntryCompletion* self ){ - self->update(); - return FALSE; -} - -void connect( GtkEntry* entry ){ - if ( m_store == 0 ) { - m_store = gtk_list_store_new( 1, G_TYPE_STRING ); - - fill(); - - StringList().connect( InvalidateCaller( *this ) ); + EntryCompletion() : m_store( 0 ), m_invalid( true ){ } - GtkEntryCompletion* completion = gtk_entry_completion_new(); - gtk_entry_set_completion( entry, completion ); - gtk_entry_completion_set_model( completion, GTK_TREE_MODEL( m_store ) ); - gtk_entry_completion_set_text_column( completion, 0 ); - g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); -} - -void append( const char* string ){ - GtkTreeIter iter; - gtk_list_store_append( m_store, &iter ); - gtk_list_store_set( m_store, &iter, 0, string, -1 ); -} -typedef MemberCaller1 AppendCaller; - -void fill(){ - StringList().forEach( AppendCaller( *this ) ); - m_invalid = false; -} - -void clear(){ - gtk_list_store_clear( m_store ); -} - -void update(){ - if( m_invalid ){ - clear(); - fill(); + static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, EntryCompletion* self ){ + self->update(); + return FALSE; } -} -void invalidate(){ - m_invalid = true; -} -typedef MemberCaller InvalidateCaller; + void connect( GtkEntry* entry ){ + if ( m_store == 0 ) { + m_store = gtk_list_store_new( 1, G_TYPE_STRING ); + + fill(); + + StringList().connect( InvalidateCaller( *this ) ); + } + + GtkEntryCompletion* completion = gtk_entry_completion_new(); + gtk_entry_set_completion( entry, completion ); + gtk_entry_completion_set_model( completion, GTK_TREE_MODEL( m_store ) ); + gtk_entry_completion_set_text_column( completion, 0 ); + g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); + } + + void append( const char* string ){ + GtkTreeIter iter; + gtk_list_store_append( m_store, &iter ); + gtk_list_store_set( m_store, &iter, 0, string, -1 ); + } + typedef MemberCaller1 AppendCaller; + + void fill(){ + StringList().forEach( AppendCaller( *this ) ); + m_invalid = false; + } + + void clear(){ + gtk_list_store_clear( m_store ); + } + + void update(){ + if( m_invalid ){ + clear(); + fill(); + } + } + + void invalidate(){ + m_invalid = true; + } + typedef MemberCaller InvalidateCaller; }; /* loaded ( shaders + textures ) */ class TextureNameList { public: -void forEach( const ShaderNameCallback& callback ) const { - for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() ) - { - const IShader *shader = QERApp_ActiveShaders_IteratorCurrent(); + void forEach( const ShaderNameCallback& callback ) const { + for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() ) + { + const IShader *shader = QERApp_ActiveShaders_IteratorCurrent(); - if ( shader_equal_prefix( shader->getName(), "textures/" ) ) { - callback( shader->getName() + 9 ); + if ( shader_equal_prefix( shader->getName(), "textures/" ) ) { + callback( shader->getName() + 9 ); + } } } -} -void connect( const SignalHandler& update ) const { - TextureBrowser_addActiveShadersChangedCallback( update ); -} + void connect( const SignalHandler& update ) const { + TextureBrowser_addActiveShadersChangedCallback( update ); + } }; typedef Static< EntryCompletion > GlobalTextureEntryCompletion; @@ -117,12 +117,12 @@ typedef Static< EntryCompletion > GlobalTextureEntryCompletion; class AllShadersNameList { public: -void forEach( const ShaderNameCallback& callback ) const { - GlobalShaderSystem().foreachShaderName( callback ); -} -void connect( const SignalHandler& update ) const { - TextureBrowser_addActiveShadersChangedCallback( update ); -} + void forEach( const ShaderNameCallback& callback ) const { + GlobalShaderSystem().foreachShaderName( callback ); + } + void connect( const SignalHandler& update ) const { + TextureBrowser_addActiveShadersChangedCallback( update ); + } }; typedef Static< EntryCompletion > GlobalAllShadersEntryCompletion; @@ -131,12 +131,12 @@ typedef Static< EntryCompletion > GlobalAllShadersEntryCompl class ShaderList { public: -void forEach( const ShaderNameCallback& callback ) const { - GlobalShaderSystem().foreachShaderName( callback ); -} -void connect( const SignalHandler& update ) const { - TextureBrowser_addShadersRealiseCallback( update ); -} + void forEach( const ShaderNameCallback& callback ) const { + GlobalShaderSystem().foreachShaderName( callback ); + } + void connect( const SignalHandler& update ) const { + TextureBrowser_addShadersRealiseCallback( update ); + } }; typedef Static< EntryCompletion > GlobalShaderEntryCompletion; diff --git a/radiant/textures.cpp b/radiant/textures.cpp index e374bdbc..aa7dcb84 100644 --- a/radiant/textures.cpp +++ b/radiant/textures.cpp @@ -318,11 +318,11 @@ void Texture_InitPalette( byte *pal ){ class TestHashtable { public: -TestHashtable(){ - HashTable strings; - strings["Monkey"] = "bleh"; - strings["MonkeY"] = "blah"; -} + TestHashtable(){ + HashTable strings; + strings["Monkey"] = "bleh"; + strings["MonkeY"] = "blah"; + } }; const TestHashtable g_testhashtable; @@ -361,173 +361,173 @@ void qtexture_unrealise( qtexture_t& texture ){ class TextureKeyEqualNoCase { public: -bool operator()( const TextureKey& key, const TextureKey& other ) const { - return key.first == other.first && string_equal_nocase( key.second.c_str(), other.second.c_str() ); -} + bool operator()( const TextureKey& key, const TextureKey& other ) const { + return key.first == other.first && string_equal_nocase( key.second.c_str(), other.second.c_str() ); + } }; class TextureKeyHashNoCase { public: -typedef hash_t hash_type; -hash_t operator()( const TextureKey& key ) const { - return hash_combine( string_hash_nocase( key.second.c_str() ), pod_hash( key.first ) ); -} + typedef hash_t hash_type; + hash_t operator()( const TextureKey& key ) const { + return hash_combine( string_hash_nocase( key.second.c_str() ), pod_hash( key.first ) ); + } }; #define DEBUG_TEXTURES 0 class TexturesMap final : public TexturesCache { -class TextureConstructor -{ -TexturesMap* m_cache; -public: -explicit TextureConstructor( TexturesMap* cache ) - : m_cache( cache ){ -} -qtexture_t* construct( const TextureKey& key ){ - qtexture_t* texture = new qtexture_t( key.first, key.second.c_str() ); - if ( m_cache->realised() ) { - qtexture_realise( *texture, key ); - } - return texture; -} -void destroy( qtexture_t* texture ){ - if ( m_cache->realised() ) { - qtexture_unrealise( *texture ); - } - delete texture; -} -}; - -typedef HashedCache qtextures_t; -qtextures_t m_qtextures; -TexturesCacheObserver* m_observer; -std::size_t m_unrealised; - -public: -TexturesMap() : m_qtextures( TextureConstructor( this ) ), m_observer( 0 ), m_unrealised( 1 ){ -} -typedef qtextures_t::iterator iterator; - -iterator begin(){ - return m_qtextures.begin(); -} -iterator end(){ - return m_qtextures.end(); -} - -LoadImageCallback defaultLoader() const { - return LoadImageCallback( 0, QERApp_LoadImage ); -} -Image* loadImage( const char* name ){ - return defaultLoader().loadImage( name ); -} -qtexture_t* capture( const char* name ){ - return capture( defaultLoader(), name ); -} -qtexture_t* capture( const LoadImageCallback& loader, const char* name ){ -#if DEBUG_TEXTURES - globalOutputStream() << "textures capture: " << makeQuoted( name ) << '\n'; -#endif - return m_qtextures.capture( TextureKey( loader, name ) ).get(); -} -void release( qtexture_t* texture ){ -#if DEBUG_TEXTURES - globalOutputStream() << "textures release: " << makeQuoted( texture->name ) << '\n'; -#endif - m_qtextures.release( TextureKey( texture->load, texture->name ) ); -} -void attach( TexturesCacheObserver& observer ){ - ASSERT_MESSAGE( m_observer == 0, "TexturesMap::attach: cannot attach observer" ); - m_observer = &observer; -} -void detach( TexturesCacheObserver& observer ){ - ASSERT_MESSAGE( m_observer == &observer, "TexturesMap::detach: cannot detach observer" ); - m_observer = 0; -} -void realise(){ - if ( --m_unrealised == 0 ) { - g_texture_globals.bTextureCompressionSupported = false; - - if ( GlobalOpenGL().ARB_texture_compression() ) { - g_texture_globals.bTextureCompressionSupported = true; - g_texture_globals.m_bOpenGLCompressionSupported = true; + class TextureConstructor + { + TexturesMap* m_cache; + public: + explicit TextureConstructor( TexturesMap* cache ) + : m_cache( cache ){ } - - if ( GlobalOpenGL().EXT_texture_compression_s3tc() ) { - g_texture_globals.bTextureCompressionSupported = true; - g_texture_globals.m_bS3CompressionSupported = true; - } - - switch ( g_texture_globals.texture_components ) - { - case GL_RGBA: - break; - case GL_COMPRESSED_RGBA_ARB: - if ( !g_texture_globals.m_bOpenGLCompressionSupported ) { - globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n"; - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; - g_texture_globals.texture_components = GL_RGBA; + qtexture_t* construct( const TextureKey& key ){ + qtexture_t* texture = new qtexture_t( key.first, key.second.c_str() ); + if ( m_cache->realised() ) { + qtexture_realise( *texture, key ); } - break; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - if ( !g_texture_globals.m_bS3CompressionSupported ) { - globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n"; - if ( g_texture_globals.m_bOpenGLCompressionSupported ) { - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; - g_texture_globals.texture_components = GL_COMPRESSED_RGBA_ARB; - } - else - { + return texture; + } + void destroy( qtexture_t* texture ){ + if ( m_cache->realised() ) { + qtexture_unrealise( *texture ); + } + delete texture; + } + }; + + typedef HashedCache qtextures_t; + qtextures_t m_qtextures; + TexturesCacheObserver* m_observer; + std::size_t m_unrealised; + +public: + TexturesMap() : m_qtextures( TextureConstructor( this ) ), m_observer( 0 ), m_unrealised( 1 ){ + } + typedef qtextures_t::iterator iterator; + + iterator begin(){ + return m_qtextures.begin(); + } + iterator end(){ + return m_qtextures.end(); + } + + LoadImageCallback defaultLoader() const { + return LoadImageCallback( 0, QERApp_LoadImage ); + } + Image* loadImage( const char* name ){ + return defaultLoader().loadImage( name ); + } + qtexture_t* capture( const char* name ){ + return capture( defaultLoader(), name ); + } + qtexture_t* capture( const LoadImageCallback& loader, const char* name ){ +#if DEBUG_TEXTURES + globalOutputStream() << "textures capture: " << makeQuoted( name ) << '\n'; +#endif + return m_qtextures.capture( TextureKey( loader, name ) ).get(); + } + void release( qtexture_t* texture ){ +#if DEBUG_TEXTURES + globalOutputStream() << "textures release: " << makeQuoted( texture->name ) << '\n'; +#endif + m_qtextures.release( TextureKey( texture->load, texture->name ) ); + } + void attach( TexturesCacheObserver& observer ){ + ASSERT_MESSAGE( m_observer == 0, "TexturesMap::attach: cannot attach observer" ); + m_observer = &observer; + } + void detach( TexturesCacheObserver& observer ){ + ASSERT_MESSAGE( m_observer == &observer, "TexturesMap::detach: cannot detach observer" ); + m_observer = 0; + } + void realise(){ + if ( --m_unrealised == 0 ) { + g_texture_globals.bTextureCompressionSupported = false; + + if ( GlobalOpenGL().ARB_texture_compression() ) { + g_texture_globals.bTextureCompressionSupported = true; + g_texture_globals.m_bOpenGLCompressionSupported = true; + } + + if ( GlobalOpenGL().EXT_texture_compression_s3tc() ) { + g_texture_globals.bTextureCompressionSupported = true; + g_texture_globals.m_bS3CompressionSupported = true; + } + + switch ( g_texture_globals.texture_components ) + { + case GL_RGBA: + break; + case GL_COMPRESSED_RGBA_ARB: + if ( !g_texture_globals.m_bOpenGLCompressionSupported ) { + globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n"; g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; g_texture_globals.texture_components = GL_RGBA; } + break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + if ( !g_texture_globals.m_bS3CompressionSupported ) { + globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n"; + if ( g_texture_globals.m_bOpenGLCompressionSupported ) { + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; + g_texture_globals.texture_components = GL_COMPRESSED_RGBA_ARB; + } + else + { + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; + g_texture_globals.texture_components = GL_RGBA; + } + } + break; + default: + globalOutputStream() << "Unknown texture compression selected, reverting\n"; + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; + g_texture_globals.texture_components = GL_RGBA; + break; } - break; - default: - globalOutputStream() << "Unknown texture compression selected, reverting\n"; - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; - g_texture_globals.texture_components = GL_RGBA; - break; - } - glGetIntegerv( GL_MAX_TEXTURE_SIZE, &max_tex_size ); - if ( max_tex_size == 0 ) { - max_tex_size = 1024; - } - - for ( qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i ) - { - if ( !( *i ).value.empty() ) { - qtexture_realise( *( *i ).value, ( *i ).key ); + glGetIntegerv( GL_MAX_TEXTURE_SIZE, &max_tex_size ); + if ( max_tex_size == 0 ) { + max_tex_size = 1024; } - } - if ( m_observer != 0 ) { - m_observer->realise(); - } - } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - if ( m_observer != 0 ) { - m_observer->unrealise(); - } - for ( qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i ) - { - if ( !( *i ).value.empty() ) { - qtexture_unrealise( *( *i ).value ); + + for ( qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i ) + { + if ( !( *i ).value.empty() ) { + qtexture_realise( *( *i ).value, ( *i ).key ); + } + } + if ( m_observer != 0 ) { + m_observer->realise(); } } } -} -bool realised(){ - return m_unrealised == 0; -} + void unrealise(){ + if ( ++m_unrealised == 1 ) { + if ( m_observer != 0 ) { + m_observer->unrealise(); + } + for ( qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i ) + { + if ( !( *i ).value.empty() ) { + qtexture_unrealise( *( *i ).value ); + } + } + } + } + bool realised(){ + return m_unrealised == 0; + } }; TexturesMap* g_texturesmap; @@ -599,39 +599,29 @@ void Textures_UpdateTextureCompressionFormat(){ switch ( g_texture_globals.m_nTextureCompressionFormat ) { case ( TEXTURECOMPRESSION_NONE ): - { texture_components = GL_RGBA; break; - } case ( TEXTURECOMPRESSION_RGBA ): - { texture_components = GL_COMPRESSED_RGBA_ARB; break; - } case ( TEXTURECOMPRESSION_RGBA_S3TC_DXT1 ): - { texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; - } case ( TEXTURECOMPRESSION_RGBA_S3TC_DXT3 ): - { texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; - } case ( TEXTURECOMPRESSION_RGBA_S3TC_DXT5 ): - { texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; } - } Textures_setTextureComponents( texture_components ); } void TextureCompressionImport( TextureCompressionFormat& self, int value ){ if ( !g_texture_globals.m_bOpenGLCompressionSupported - && g_texture_globals.m_bS3CompressionSupported - && value >= 1 ) { + && g_texture_globals.m_bS3CompressionSupported + && value >= 1 ) { ++value; } switch ( value ) @@ -729,28 +719,28 @@ void Textures_constructPreferences( PreferencesPage& page ){ { const char* percentages[] = { "100%", "50%", "25%", "12.5%", }; page.appendRadio( - "Texture Quality", - STRING_ARRAY_RANGE( percentages ), - TextureMiplevelImportCaller( g_Textures_mipLevel ), - IntExportCaller( g_Textures_mipLevel ) - ); + "Texture Quality", + STRING_ARRAY_RANGE( percentages ), + TextureMiplevelImportCaller( g_Textures_mipLevel ), + IntExportCaller( g_Textures_mipLevel ) + ); } page.appendSpinner( - "Texture Gamma", - 1.0, - 0.0, - 5.0, - FloatImportCallback( TextureGammaImportCaller( g_texture_globals.fGamma ) ), - FloatExportCallback( FloatExportCaller( g_texture_globals.fGamma ) ) - ); + "Texture Gamma", + 1.0, + 0.0, + 5.0, + FloatImportCallback( TextureGammaImportCaller( g_texture_globals.fGamma ) ), + FloatExportCallback( FloatExportCaller( g_texture_globals.fGamma ) ) + ); { const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear" }; page.appendCombo( - "Texture Render Mode", - STRING_ARRAY_RANGE( texture_mode ), - IntImportCallback( TextureModeImportCaller( g_texture_mode ) ), - IntExportCallback( TextureModeExportCaller( g_texture_mode ) ) - ); + "Texture Render Mode", + STRING_ARRAY_RANGE( texture_mode ), + IntImportCallback( TextureModeImportCaller( g_texture_mode ) ), + IntExportCallback( TextureModeExportCaller( g_texture_mode ) ) + ); } { const char* compression_none[] = { "None" }; @@ -758,24 +748,24 @@ void Textures_constructPreferences( PreferencesPage& page ){ const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; StringArrayRange compression( - ( g_texture_globals.m_bOpenGLCompressionSupported ) - ? ( g_texture_globals.m_bS3CompressionSupported ) - ? STRING_ARRAY_RANGE( compression_opengl_s3tc ) - : STRING_ARRAY_RANGE( compression_opengl ) - : ( g_texture_globals.m_bS3CompressionSupported ) - ? STRING_ARRAY_RANGE( compression_s3tc ) - : STRING_ARRAY_RANGE( compression_none ) - ); + ( g_texture_globals.m_bOpenGLCompressionSupported ) + ? ( g_texture_globals.m_bS3CompressionSupported ) + ? STRING_ARRAY_RANGE( compression_opengl_s3tc ) + : STRING_ARRAY_RANGE( compression_opengl ) + : ( g_texture_globals.m_bS3CompressionSupported ) + ? STRING_ARRAY_RANGE( compression_s3tc ) + : STRING_ARRAY_RANGE( compression_none ) + ); page.appendCombo( - "Hardware Texture Compression", - compression, - TextureCompressionImportCaller( g_texture_globals.m_nTextureCompressionFormat ), - IntExportCaller( reinterpret_cast( g_texture_globals.m_nTextureCompressionFormat ) ) - ); + "Hardware Texture Compression", + compression, + TextureCompressionImportCaller( g_texture_globals.m_nTextureCompressionFormat ), + IntExportCaller( reinterpret_cast( g_texture_globals.m_nTextureCompressionFormat ) ) + ); } page.appendCheckBox( "", "Anisotropy", - FreeCaller1(), - BoolExportCaller( g_TextureAnisotropy ) ); + FreeCaller1(), + BoolExportCaller( g_TextureAnisotropy ) ); } void Textures_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Textures", "Texture Settings" ) ); @@ -819,34 +809,34 @@ class TexturesDependencies : public GlobalOpenGLModuleRef, public GlobalPreferenceSystemModuleRef { -ImageModulesRef m_image_modules; + ImageModulesRef m_image_modules; public: -TexturesDependencies() : - m_image_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "texturetypes" ) ){ -} -ImageModules& getImageModules(){ - return m_image_modules.get(); -} + TexturesDependencies() : + m_image_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "texturetypes" ) ){ + } + ImageModules& getImageModules(){ + return m_image_modules.get(); + } }; class TexturesAPI { -TexturesCache* m_textures; + TexturesCache* m_textures; public: -typedef TexturesCache Type; -STRING_CONSTANT( Name, "*" ); + typedef TexturesCache Type; + STRING_CONSTANT( Name, "*" ); -TexturesAPI(){ - Textures_Construct(); + TexturesAPI(){ + Textures_Construct(); - m_textures = &GetTexturesCache(); -} -~TexturesAPI(){ - Textures_Destroy(); -} -TexturesCache* getTable(){ - return m_textures; -} + m_textures = &GetTexturesCache(); + } + ~TexturesAPI(){ + Textures_Destroy(); + } + TexturesCache* getTable(){ + return m_textures; + } }; typedef SingletonModule TexturesModule; diff --git a/radiant/texwindow.cpp b/radiant/texwindow.cpp index e4dd03c9..deccce4a 100644 --- a/radiant/texwindow.cpp +++ b/radiant/texwindow.cpp @@ -176,138 +176,138 @@ typedef FreeCaller1 m_all_tags; -GtkListStore* m_all_tags_list; -std::vector m_copied_tags; -std::set m_found_shaders; + std::set m_all_tags; + GtkListStore* m_all_tags_list; + std::vector m_copied_tags; + std::set m_found_shaders; -ToggleItem m_hideunused_item; -ToggleItem m_showshaders_item; -ToggleItem m_showtextures_item; -ToggleItem m_showshaderlistonly_item; -ToggleItem m_fixedsize_item; -ToggleItem m_filternotex_item; -ToggleItem m_enablealpha_item; -ToggleItem m_filter_searchFromStart_item; + ToggleItem m_hideunused_item; + ToggleItem m_showshaders_item; + ToggleItem m_showtextures_item; + ToggleItem m_showshaderlistonly_item; + ToggleItem m_fixedsize_item; + ToggleItem m_filternotex_item; + ToggleItem m_enablealpha_item; + ToggleItem m_filter_searchFromStart_item; -guint m_sizeHandler; -guint m_exposeHandler; + guint m_sizeHandler; + guint m_exposeHandler; -bool m_heightChanged; -bool m_originInvalid; + bool m_heightChanged; + bool m_originInvalid; -DeferredAdjustment m_scrollAdjustment; -FreezePointer m_freezePointer; + DeferredAdjustment m_scrollAdjustment; + FreezePointer m_freezePointer; -Vector3 color_textureback; + Vector3 color_textureback; // the increment step we use against the wheel mouse -std::size_t m_mouseWheelScrollIncrement; -std::size_t m_textureScale; + std::size_t m_mouseWheelScrollIncrement; + std::size_t m_textureScale; // make the texture increments match the grid changes -bool m_showShaders; -bool m_showTextures; -bool m_showTextureScrollbar; -StartupShaders m_startupShaders; + bool m_showShaders; + bool m_showTextures; + bool m_showTextureScrollbar; + StartupShaders m_startupShaders; // if true, the texture window will only display in-use shaders // if false, all the shaders in memory are displayed -bool m_hideUnused; -bool m_rmbSelected; -bool m_searchedTags; -bool m_tags; -bool m_move_started; -int m_move_amount; -BasicVector2 m_move_start; + bool m_hideUnused; + bool m_rmbSelected; + bool m_searchedTags; + bool m_tags; + bool m_move_started; + int m_move_amount; + BasicVector2 m_move_start; // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true. -int m_uniformTextureSize; -int m_uniformTextureMinSize; + int m_uniformTextureSize; + int m_uniformTextureMinSize; -bool m_hideNonShadersInCommon; + bool m_hideNonShadersInCommon; -static bool wads; + static bool wads; // Return the display width of a texture in the texture browser -void getTextureWH( qtexture_t* tex, int &W, int &H ){ - // Don't use uniform size - W = std::max( std::size_t( 1 ), tex->width * m_textureScale / 100 ); - H = std::max( std::size_t( 1 ), tex->height * m_textureScale / 100 ); + void getTextureWH( qtexture_t* tex, int &W, int &H ){ + // Don't use uniform size + W = std::max( std::size_t( 1 ), tex->width * m_textureScale / 100 ); + H = std::max( std::size_t( 1 ), tex->height * m_textureScale / 100 ); - if ( g_TextureBrowser_fixedSize ){ - if ( W >= H ) { - // Texture is square, or wider than it is tall - if ( W >= m_uniformTextureSize ){ - H = m_uniformTextureSize * H / W; - W = m_uniformTextureSize; + if ( g_TextureBrowser_fixedSize ){ + if ( W >= H ) { + // Texture is square, or wider than it is tall + if ( W >= m_uniformTextureSize ){ + H = m_uniformTextureSize * H / W; + W = m_uniformTextureSize; + } + else if ( W <= m_uniformTextureMinSize ){ + H = m_uniformTextureMinSize * H / W; + W = m_uniformTextureMinSize; + } } - else if ( W <= m_uniformTextureMinSize ){ - H = m_uniformTextureMinSize * H / W; - W = m_uniformTextureMinSize; - } - } - else { - // Texture taller than it is wide - if ( H >= m_uniformTextureSize ){ - W = m_uniformTextureSize * W / H; - H = m_uniformTextureSize; - } - else if ( H <= m_uniformTextureMinSize ){ - W = m_uniformTextureMinSize * W / H; - H = m_uniformTextureMinSize; + else { + // Texture taller than it is wide + if ( H >= m_uniformTextureSize ){ + W = m_uniformTextureSize * W / H; + H = m_uniformTextureSize; + } + else if ( H <= m_uniformTextureMinSize ){ + W = m_uniformTextureMinSize * W / H; + H = m_uniformTextureMinSize; + } } } } -} -TextureBrowser() : - m_texture_scroll( 0 ), - m_hideunused_item( TextureBrowserHideUnusedExport() ), - m_showshaders_item( TextureBrowserShowShadersExport() ), - m_showtextures_item( TextureBrowserShowTexturesExport() ), - m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ), - m_fixedsize_item( TextureBrowserFixedSizeExport() ), - m_filternotex_item( TextureBrowserFilterNotexExport() ), - m_enablealpha_item( TextureBrowserEnableAlphaExport() ), - m_filter_searchFromStart_item( TextureBrowser_filter_searchFromStartExport() ), - m_heightChanged( true ), - m_originInvalid( true ), - m_scrollAdjustment( TextureBrowser_scrollChanged, this ), - color_textureback( 0.25f, 0.25f, 0.25f ), - m_mouseWheelScrollIncrement( 64 ), - m_textureScale( 50 ), - m_showShaders( true ), - m_showTextures( true ), - m_showTextureScrollbar( true ), - m_startupShaders( STARTUPSHADERS_NONE ), - m_hideUnused( false ), - m_rmbSelected( false ), - m_searchedTags( false ), - m_tags( false ), - m_move_started( false ), - m_uniformTextureSize( 160 ), - m_uniformTextureMinSize( 48 ), - m_hideNonShadersInCommon( true ){ -} + TextureBrowser() : + m_texture_scroll( 0 ), + m_hideunused_item( TextureBrowserHideUnusedExport() ), + m_showshaders_item( TextureBrowserShowShadersExport() ), + m_showtextures_item( TextureBrowserShowTexturesExport() ), + m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ), + m_fixedsize_item( TextureBrowserFixedSizeExport() ), + m_filternotex_item( TextureBrowserFilterNotexExport() ), + m_enablealpha_item( TextureBrowserEnableAlphaExport() ), + m_filter_searchFromStart_item( TextureBrowser_filter_searchFromStartExport() ), + m_heightChanged( true ), + m_originInvalid( true ), + m_scrollAdjustment( TextureBrowser_scrollChanged, this ), + color_textureback( 0.25f, 0.25f, 0.25f ), + m_mouseWheelScrollIncrement( 64 ), + m_textureScale( 50 ), + m_showShaders( true ), + m_showTextures( true ), + m_showTextureScrollbar( true ), + m_startupShaders( STARTUPSHADERS_NONE ), + m_hideUnused( false ), + m_rmbSelected( false ), + m_searchedTags( false ), + m_tags( false ), + m_move_started( false ), + m_uniformTextureSize( 160 ), + m_uniformTextureMinSize( 48 ), + m_hideNonShadersInCommon( true ){ + } }; bool TextureBrowser::wads = false; @@ -411,7 +411,7 @@ class TextureLayout public: // texture layout functions // TTimo: now based on shaders -int current_x, current_y, current_row; + int current_x, current_y, current_row; }; void Texture_StartPos( TextureLayout& layout ){ @@ -516,7 +516,7 @@ bool Texture_IsShown( IShader* shader, TextureBrowser& textureBrowser ){ } if( textureBrowser.m_hideNonShadersInCommon && shader->IsDefault() && !shader->IsInUse() //&& g_TextureBrowser_currentDirectory != "" - && shader_equal_prefix( shader_get_textureName( shader->getName() ), TextureBrowser_getCommonShadersDir() ) ){ + && shader_equal_prefix( shader_get_textureName( shader->getName() ), TextureBrowser_getCommonShadersDir() ) ){ return false; } @@ -608,16 +608,16 @@ void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handle class ShadersObserver : public ModuleObserver { -Signal0 m_realiseCallbacks; + Signal0 m_realiseCallbacks; public: -void realise(){ - m_realiseCallbacks(); -} -void unrealise(){ -} -void insert( const SignalHandler& handler ){ - m_realiseCallbacks.connectLast( handler ); -} + void realise(){ + m_realiseCallbacks(); + } + void unrealise(){ + } + void insert( const SignalHandler& handler ){ + m_realiseCallbacks.connectLast( handler ); + } }; namespace @@ -665,30 +665,30 @@ bool texture_name_ignore( const char* name ){ auto temp = StringOutputStream( 64 )( LowerCase( name ) ); return - string_equal_suffix( temp, ".specular" ) || - string_equal_suffix( temp, ".glow" ) || - string_equal_suffix( temp, ".bump" ) || - string_equal_suffix( temp, ".diffuse" ) || - string_equal_suffix( temp, ".blend" ) || - string_equal_suffix( temp, ".alpha" ) || - string_equal_suffix( temp, "_norm" ) || - string_equal_suffix( temp, "_bump" ) || - string_equal_suffix( temp, "_glow" ) || - string_equal_suffix( temp, "_gloss" ) || - string_equal_suffix( temp, "_pants" ) || - string_equal_suffix( temp, "_shirt" ) || - string_equal_suffix( temp, "_reflect" ) || - string_equal_suffix( temp, "_alpha" ) || - 0; + string_equal_suffix( temp, ".specular" ) || + string_equal_suffix( temp, ".glow" ) || + string_equal_suffix( temp, ".bump" ) || + string_equal_suffix( temp, ".diffuse" ) || + string_equal_suffix( temp, ".blend" ) || + string_equal_suffix( temp, ".alpha" ) || + string_equal_suffix( temp, "_norm" ) || + string_equal_suffix( temp, "_bump" ) || + string_equal_suffix( temp, "_glow" ) || + string_equal_suffix( temp, "_gloss" ) || + string_equal_suffix( temp, "_pants" ) || + string_equal_suffix( temp, "_shirt" ) || + string_equal_suffix( temp, "_reflect" ) || + string_equal_suffix( temp, "_alpha" ) || + 0; } class LoadShaderVisitor : public Archive::Visitor { public: -void visit( const char* name ){ - IShader* shader = QERApp_Shader_ForName( CopiedString( PathExtensionless( name ) ).c_str() ); - shader->DecRef(); -} + void visit( const char* name ){ + IShader* shader = QERApp_Shader_ForName( CopiedString( PathExtensionless( name ) ).c_str() ); + shader->DecRef(); + } }; void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ); @@ -708,25 +708,25 @@ void TextureBrowser_updateTitle(){ class TextureCategoryLoadShader { -const char* m_directory; -std::size_t& m_count; + const char* m_directory; + std::size_t& m_count; public: -typedef const char* first_argument_type; + typedef const char* first_argument_type; -TextureCategoryLoadShader( const char* directory, std::size_t& count ) - : m_directory( directory ), m_count( count ){ - m_count = 0; -} -void operator()( const char* name ) const { - if ( shader_equal_prefix( name, "textures/" ) - && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) { - ++m_count; - // request the shader, this will load the texture if needed - // this Shader_ForName call is a kind of hack - IShader *pFoo = QERApp_Shader_ForName( name ); - pFoo->DecRef(); + TextureCategoryLoadShader( const char* directory, std::size_t& count ) + : m_directory( directory ), m_count( count ){ + m_count = 0; + } + void operator()( const char* name ) const { + if ( shader_equal_prefix( name, "textures/" ) + && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) { + ++m_count; + // request the shader, this will load the texture if needed + // this Shader_ForName call is a kind of hack + IShader *pFoo = QERApp_Shader_ForName( name ); + pFoo->DecRef(); + } } -} }; void TextureDirectory_loadTexture( const char* directory, const char* texture ){ @@ -749,14 +749,14 @@ typedef ConstPointerCaller1 Tex class LoadTexturesByTypeVisitor : public ImageModules::Visitor { -const char* m_dirstring; + const char* m_dirstring; public: -LoadTexturesByTypeVisitor( const char* dirstring ) - : m_dirstring( dirstring ){ -} -void visit( const char* minor, const _QERPlugImageTable& table ) const { - GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) ); -} + LoadTexturesByTypeVisitor( const char* dirstring ) + : m_dirstring( dirstring ){ + } + void visit( const char* minor, const _QERPlugImageTable& table ) const { + GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) ); + } }; void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){ @@ -920,7 +920,7 @@ IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){ int nWidth, nHeight; textureBrowser.getTextureWH( q, nWidth, nHeight ); if ( mx > x && mx - x < nWidth - && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) { + && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) { return shader; } } @@ -1021,9 +1021,9 @@ void Texture_Draw( TextureBrowser& textureBrowser ){ const int originy = TextureBrowser_getOriginY( textureBrowser ); glClearColor( textureBrowser.color_textureback[0], - textureBrowser.color_textureback[1], - textureBrowser.color_textureback[2], - 0 ); + textureBrowser.color_textureback[1], + textureBrowser.color_textureback[2], + 0 ); glViewport( 0, 0, textureBrowser.width, textureBrowser.height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); @@ -1068,7 +1068,7 @@ void Texture_Draw( TextureBrowser& textureBrowser ){ // Is this texture visible? if ( ( y - nHeight - fontHeight < originy ) - && ( y > originy - textureBrowser.height ) ) { + && ( y > originy - textureBrowser.height ) ) { glLineWidth( 1 ); glDisable( GL_TEXTURE_2D ); const float xf = x; @@ -1121,7 +1121,7 @@ void Texture_Draw( TextureBrowser& textureBrowser ){ } // draw checkerboard for transparent textures - if ( g_TextureBrowser_enableAlpha ) + if ( g_TextureBrowser_enableAlpha ) { glBegin( GL_QUADS ); for ( int i = 0; i < nHeight; i += 8 ) @@ -1249,9 +1249,9 @@ void BuildStoreAssignedTags( GtkListStore* store, const char* shader, TextureBro } void BuildStoreAvailableTags( GtkListStore* storeAvailable, - GtkListStore* storeAssigned, - const std::set& allTags, - TextureBrowser* textureBrowser ){ + GtkListStore* storeAssigned, + const std::set& allTags, + TextureBrowser* textureBrowser ){ GtkTreeIter iterAssigned; GtkTreeIter iterAvailable; @@ -1446,10 +1446,10 @@ void TextureGroups_constructTreeModel( TextureGroups groups, GtkTreeStore* store TextureGroups::const_iterator next = i; ++next; if ( firstUnderscore != 0 - && next != groups.end() - && string_equal_start( ( *next ).c_str(), dirRoot ) ) { + && next != groups.end() + && string_equal_start( ( *next ).c_str(), dirRoot ) ) { gtk_tree_store_append( store, &iter, NULL ); - gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), 1 , "", -1 ); + gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), 1, "", -1 ); // keep going... while ( i != groups.end() && string_equal_start( ( *i ).c_str(), dirRoot ) ) @@ -1615,8 +1615,8 @@ void TextureBrowser_createContextMenu( GtkWidget *treeview, GdkEventButton *even gtk_widget_show_all( menu ); gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL, - ( event != NULL ) ? event->button : 0, - gdk_event_get_time( (GdkEvent*)event ) ); + ( event != NULL ) ? event->button : 0, + gdk_event_get_time( (GdkEvent*)event ) ); } void TextureBrowser_searchTags(); @@ -2059,7 +2059,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ GtkToolbar* toolbar; - { // menu bar + { // menu bar GtkMenu* menu_view = GTK_MENU( gtk_menu_new() ); TextureBrowser_constructViewMenu( menu_view ); gtk_menu_set_title( menu_view, "View" ); @@ -2080,7 +2080,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ button = toolbar_append_button( toolbar, "Flush & Reload Shaders", "texbro_refresh.png", "RefreshShaders" ); // gtk_widget_set_size_request( GTK_WIDGET( button ), 22, 22 ); } - { // filter entry + { // filter entry GtkWidget* entry = g_TextureBrowser.m_filter_entry = gtk_entry_new(); gtk_widget_set_size_request( entry, 64, -1 ); gtk_box_pack_start( GTK_BOX( vbox ), entry, FALSE, FALSE, 0 ); @@ -2095,7 +2095,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ g_signal_connect( G_OBJECT( entry ), "enter_notify_event", G_CALLBACK( TextureBrowser_filterEntryFocus ), 0 ); g_signal_connect( G_OBJECT( entry ), "leave_notify_event", G_CALLBACK( TextureBrowser_filterEntryUnfocus ), 0 ); } - { // Texture TreeView + { // Texture TreeView GtkWidget* w = g_TextureBrowser.m_scr_win_tree = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( w ), 0 ); @@ -2110,7 +2110,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_container_add( GTK_CONTAINER( w ), g_TextureBrowser.m_treeViewTree ); //GtkTreeView has native scrolling support; should not be used with the GtkViewport proxy. gtk_widget_show( g_TextureBrowser.m_treeViewTree ); } - { // gl_widget scrollbar + { // gl_widget scrollbar GtkWidget* w = g_TextureBrowser.m_texture_scroll = gtk_vscrollbar_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, 0, 0, 1, 1, 0 ) ) ); gtk_table_attach( GTK_TABLE( table ), w, 2, 3, 1, 2, GTK_SHRINK, GTK_FILL, 0, 0 ); gtk_widget_show( w ); @@ -2120,7 +2120,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ widget_set_visible( w, g_TextureBrowser.m_showTextureScrollbar ); } - { // gl_widget + { // gl_widget #if NV_DRIVER_GAMMA_BUG GtkWidget* w = g_TextureBrowser.m_gl_widget = glwidget_new( TRUE ); #else @@ -2145,7 +2145,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ // tag stuff if ( g_TextureBrowser.m_tags ) { - { // fill tag GtkListStore + { // fill tag GtkListStore g_TextureBrowser.m_all_tags_list = gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ); GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_all_tags_list ); gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING ); @@ -2153,7 +2153,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ TagBuilder.GetAllTags( g_TextureBrowser.m_all_tags ); TextureBrowser_buildTagList(); } - { // tag menu bar + { // tag menu bar GtkMenu* menu_tags = GTK_MENU( gtk_menu_new() ); gtk_menu_set_title( menu_tags, "Tags" ); TextureBrowser_constructTagsMenu( menu_tags ); @@ -2164,7 +2164,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ //show detached menu over floating tex bro and main wnd... gtk_menu_attach_to_widget( menu_tags, GTK_WIDGET( button ), NULL ); } - { // Tag TreeView + { // Tag TreeView g_TextureBrowser.m_scr_win_tags = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), 0 ); @@ -2179,15 +2179,15 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), g_TextureBrowser.m_treeViewTags ); gtk_widget_show( GTK_WIDGET( g_TextureBrowser.m_treeViewTags ) ); } - { // Texture/Tag notebook + { // Texture/Tag notebook TextureBrowser_constructTagNotebook(); gtk_box_pack_start( GTK_BOX( vbox ), g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0 ); } - { // Tag search button + { // Tag search button TextureBrowser_constructSearchButton(); gtk_box_pack_end( GTK_BOX( vbox ), g_TextureBrowser.m_search_button, FALSE, FALSE, 0 ); } - { // Tag frame + { // Tag frame frame_table = gtk_table_new( 3, 3, FALSE ); g_TextureBrowser.m_tag_frame = gtk_frame_new( "Tag assignment" ); @@ -2200,7 +2200,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_tag_frame ), frame_table ); } - { // assigned tag list + { // assigned tag list GtkWidget* scrolled_win = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS ); @@ -2229,7 +2229,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0 ); } - { // available tag list + { // available tag list GtkWidget* scrolled_win = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS ); @@ -2257,7 +2257,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 2, 3, 1, 3, GTK_FILL, GTK_FILL, 0, 0 ); } - { // tag arrow buttons + { // tag arrow buttons GtkWidget* m_btn_left = gtk_button_new(); GtkWidget* m_btn_right = gtk_button_new(); GtkWidget* m_arrow_left = gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ); @@ -2280,7 +2280,7 @@ GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){ gtk_widget_show( m_arrow_left ); gtk_widget_show( m_arrow_right ); } - { // tag fram labels + { // tag fram labels GtkWidget* m_lbl_assigned = gtk_label_new( "Assigned" ); GtkWidget* m_lbl_unassigned = gtk_label_new( "Available" ); @@ -2669,18 +2669,18 @@ typedef ReferenceCaller1 Unifo void TextureBrowser_constructPreferences( PreferencesPage& page ){ page.appendCheckBox( - "", "Texture scrollbar", - TextureBrowserImportShowScrollbarCaller( GlobalTextureBrowser() ), - BoolExportCaller( GlobalTextureBrowser().m_showTextureScrollbar ) - ); + "", "Texture scrollbar", + TextureBrowserImportShowScrollbarCaller( GlobalTextureBrowser() ), + BoolExportCaller( GlobalTextureBrowser().m_showTextureScrollbar ) + ); { const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" }; page.appendCombo( - "Texture Thumbnail Scale", - STRING_ARRAY_RANGE( texture_scale ), - IntImportCallback( TextureScaleImportCaller( GlobalTextureBrowser() ) ), - IntExportCallback( TextureScaleExportCaller( GlobalTextureBrowser() ) ) - ); + "Texture Thumbnail Scale", + STRING_ARRAY_RANGE( texture_scale ), + IntImportCallback( TextureScaleImportCaller( GlobalTextureBrowser() ) ), + IntExportCallback( TextureScaleExportCaller( GlobalTextureBrowser() ) ) + ); } page.appendSpinner( "Thumbnails Max Size", GlobalTextureBrowser().m_uniformTextureSize, 160.0, 16, 8192 ); page.appendSpinner( "Thumbnails Min Size", GlobalTextureBrowser().m_uniformTextureMinSize, 48.0, 16, 8192 ); @@ -2693,9 +2693,9 @@ void TextureBrowser_constructPreferences( PreferencesPage& page ){ StringOutputStream sstream( 256 ); sstream << "Hide nonShaders in " << TextureBrowser_getCommonShadersDir() << " folder"; page.appendCheckBox( - "", sstream.c_str(), - GlobalTextureBrowser().m_hideNonShadersInCommon - ); + "", sstream.c_str(), + GlobalTextureBrowser().m_hideNonShadersInCommon + ); } } void TextureBrowser_constructPage( PreferenceGroup& group ){ @@ -2737,19 +2737,19 @@ void TextureBrowser_Construct(){ GlobalToggles_insert( "SearchFromStart", FreeCaller(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_filter_searchFromStart_item ) ); GlobalPreferenceSystem().registerPreference( "TextureScale", - makeSizeStringImportCallback( TextureBrowserSetScaleCaller( g_TextureBrowser ) ), - SizeExportStringCaller( g_TextureBrowser.m_textureScale ) - ); + makeSizeStringImportCallback( TextureBrowserSetScaleCaller( g_TextureBrowser ) ), + SizeExportStringCaller( g_TextureBrowser.m_textureScale ) + ); GlobalPreferenceSystem().registerPreference( "UniformTextureSize", - makeIntStringImportCallback(UniformTextureSizeImportCaller(g_TextureBrowser)), - IntExportStringCaller(g_TextureBrowser.m_uniformTextureSize) ); + makeIntStringImportCallback(UniformTextureSizeImportCaller(g_TextureBrowser)), + IntExportStringCaller(g_TextureBrowser.m_uniformTextureSize) ); GlobalPreferenceSystem().registerPreference( "UniformTextureMinSize", - makeIntStringImportCallback(UniformTextureMinSizeImportCaller(g_TextureBrowser)), - IntExportStringCaller(g_TextureBrowser.m_uniformTextureMinSize) ); + makeIntStringImportCallback(UniformTextureMinSizeImportCaller(g_TextureBrowser)), + IntExportStringCaller(g_TextureBrowser.m_uniformTextureMinSize) ); GlobalPreferenceSystem().registerPreference( "TextureScrollbar", - makeBoolStringImportCallback( TextureBrowserImportShowScrollbarCaller( g_TextureBrowser ) ), - BoolExportStringCaller( GlobalTextureBrowser().m_showTextureScrollbar ) - ); + makeBoolStringImportCallback( TextureBrowserImportShowScrollbarCaller( g_TextureBrowser ) ), + BoolExportStringCaller( GlobalTextureBrowser().m_showTextureScrollbar ) + ); GlobalPreferenceSystem().registerPreference( "ShowShaders", BoolImportStringCaller( GlobalTextureBrowser().m_showShaders ), BoolExportStringCaller( GlobalTextureBrowser().m_showShaders ) ); GlobalPreferenceSystem().registerPreference( "ShowTextures", BoolImportStringCaller( GlobalTextureBrowser().m_showTextures ), BoolExportStringCaller( GlobalTextureBrowser().m_showTextures ) ); GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", BoolImportStringCaller( g_TextureBrowser_shaderlistOnly ), BoolExportStringCaller( g_TextureBrowser_shaderlistOnly ) ); diff --git a/radiant/timer.cpp b/radiant/timer.cpp index 1c55d930..e6c3012e 100644 --- a/radiant/timer.cpp +++ b/radiant/timer.cpp @@ -29,19 +29,19 @@ MillisecondTime MillisecondTime::current(){ static class Cached { - LONGLONG m_frequency; - LONGLONG m_base; -public: - Cached(){ - QueryPerformanceFrequency( (LARGE_INTEGER *) &m_frequency ); - QueryPerformanceCounter( (LARGE_INTEGER *) &m_base ); - } - LONGLONG frequency(){ - return m_frequency; - } - LONGLONG base(){ - return m_base; - } + LONGLONG m_frequency; + LONGLONG m_base; + public: + Cached(){ + QueryPerformanceFrequency( (LARGE_INTEGER *) &m_frequency ); + QueryPerformanceCounter( (LARGE_INTEGER *) &m_base ); + } + LONGLONG frequency(){ + return m_frequency; + } + LONGLONG base(){ + return m_base; + } } cached; if ( cached.frequency() > 0 ) { @@ -70,14 +70,14 @@ public: MillisecondTime MillisecondTime::current(){ static class Cached { - time_t m_base; -public: - Cached(){ - time( &m_base ); - } - time_t base(){ - return m_base; - } + time_t m_base; + public: + Cached(){ + time( &m_base ); + } + time_t base(){ + return m_base; + } } cached; timeval time; diff --git a/radiant/timer.h b/radiant/timer.h index 53280a8c..919160f6 100644 --- a/radiant/timer.h +++ b/radiant/timer.h @@ -28,18 +28,18 @@ const int msec_per_sec = 1000; class MillisecondTime { -unsigned int m_milliseconds; + unsigned int m_milliseconds; public: -MillisecondTime( unsigned int milliseconds ) - : m_milliseconds( milliseconds ){ -} -MillisecondTime(){ -} -static MillisecondTime current(); + MillisecondTime( unsigned int milliseconds ) + : m_milliseconds( milliseconds ){ + } + MillisecondTime(){ + } + static MillisecondTime current(); -unsigned int milliseconds_since( const MillisecondTime& other ) const { - return m_milliseconds - other.m_milliseconds; -} + unsigned int milliseconds_since( const MillisecondTime& other ) const { + return m_milliseconds - other.m_milliseconds; + } }; template @@ -53,41 +53,41 @@ const unsigned int usec_per_sec = 1000000; class MillisecondTime { -unsigned int m_sec; -unsigned int m_usec; + unsigned int m_sec; + unsigned int m_usec; public: -MillisecondTime( unsigned int sec, unsigned int usec ) - : m_sec( sec ), m_usec( usec ){ -} -MillisecondTime(){ -} -staticMillisecondTime current(); + MillisecondTime( unsigned int sec, unsigned int usec ) + : m_sec( sec ), m_usec( usec ){ + } + MillisecondTime(){ + } + staticMillisecondTime current(); -unsigned int milliseconds_since( const MillisecondTime& other ) const { - return static_cast( ( m_sec * static_cast( usec_per_sec ) + m_usec ) - - ( other.m_sec * static_cast( usec_per_sec ) + other.m_usec ) ) / 1000; -} + unsigned int milliseconds_since( const MillisecondTime& other ) const { + return static_cast( ( m_sec * static_cast( usec_per_sec ) + m_usec ) + - ( other.m_sec * static_cast( usec_per_sec ) + other.m_usec ) ) / 1000; + } }; template inline MillisecondTime time_from_ticks( tick_type tick_count, tick_type ticks_per_sec ){ return MillisecondTime( static_cast( tick_count / ticks_per_sec ), - static_cast( ( tick_count % ticks_per_sec ) * ( usec_per_sec / static_cast( ticks_per_sec ) ) ) ); + static_cast( ( tick_count % ticks_per_sec ) * ( usec_per_sec / static_cast( ticks_per_sec ) ) ) ); } #endif class Timer { -MillisecondTime m_start; + MillisecondTime m_start; public: -void start(){ - m_start = MillisecondTime::current(); -} -unsigned int elapsed_msec(){ - return MillisecondTime::current().milliseconds_since( m_start ); -} + void start(){ + m_start = MillisecondTime::current(); + } + unsigned int elapsed_msec(){ + return MillisecondTime::current().milliseconds_since( m_start ); + } }; #endif diff --git a/radiant/treemodel.cpp b/radiant/treemodel.cpp index 9d887db1..0bf79357 100644 --- a/radiant/treemodel.cpp +++ b/radiant/treemodel.cpp @@ -63,8 +63,8 @@ void graph_tree_model_delete( GraphTreeModel* model ){ bool graph_tree_model_subtree_find_node( GraphTreeModel* model, GtkTreeIter* parent, const scene::Node& node, GtkTreeIter* iter ){ for ( gboolean success = gtk_tree_model_iter_children( GTK_TREE_MODEL( model ), iter, parent ); - success; - success = gtk_tree_model_iter_next( GTK_TREE_MODEL( model ), iter ) ) + success; + success = gtk_tree_model_iter_next( GTK_TREE_MODEL( model ), iter ) ) { scene::Node* current; gtk_tree_model_get_pointer( GTK_TREE_MODEL( model ), iter, 0, ¤t ); @@ -172,27 +172,27 @@ typedef scene::Node* NodePointer; class NodeNameLess { public: -bool operator()( const NodePointer& self, const NodePointer& other ) const { - if ( self == 0 ) { - return true; + bool operator()( const NodePointer& self, const NodePointer& other ) const { + if ( self == 0 ) { + return true; + } + if ( other == 0 ) { + return false; + } + int result = string_compare( node_get_name( self ), node_get_name( other ) ); + if ( result == 0 ) { + return self < other; + } + return result < 0; } - if ( other == 0 ) { - return false; - } - int result = string_compare( node_get_name( self ), node_get_name( other ) ); - if ( result == 0 ) { - return self < other; - } - return result < 0; -} }; class PathNameLess { public: -bool operator()( const PathConstReference& self, const PathConstReference& other ) const { - return std::lexicographical_compare( self.get().begin(), self.get().end(), other.get().begin(), other.get().end(), NodeNameLess() ); -} + bool operator()( const PathConstReference& self, const PathConstReference& other ) const { + return std::lexicographical_compare( self.get().begin(), self.get().end(), other.get().begin(), other.get().end(), NodeNameLess() ); + } }; typedef std::map graph_type; @@ -508,7 +508,7 @@ static gboolean graph_tree_model_drag_data_received( GtkTreeDragDest *drag_dest, GtkTreeModel *src_model = 0; GtkTreePath *src_path = 0; if ( gtk_tree_get_row_drag_data( selection_data, &src_model, &src_path ) - && src_model == tree_model ) { + && src_model == tree_model ) { /* Copy the given row to a new position */ GtkTreeIter iter; @@ -599,17 +599,17 @@ GType graph_tree_model_get_type( void ){ }; graph_tree_model_type = g_type_register_static( G_TYPE_OBJECT, "GraphTreeModel", - &graph_tree_model_info, (GTypeFlags)0 ); + &graph_tree_model_info, (GTypeFlags)0 ); g_type_add_interface_static( graph_tree_model_type, - GTK_TYPE_TREE_MODEL, - &tree_model_info ); + GTK_TYPE_TREE_MODEL, + &tree_model_info ); g_type_add_interface_static( graph_tree_model_type, - GTK_TYPE_TREE_DRAG_SOURCE, - &drag_source_info ); + GTK_TYPE_TREE_DRAG_SOURCE, + &drag_source_info ); g_type_add_interface_static( graph_tree_model_type, - GTK_TYPE_TREE_DRAG_DEST, - &drag_dest_info ); + GTK_TYPE_TREE_DRAG_DEST, + &drag_dest_info ); } return graph_tree_model_type; @@ -631,17 +631,17 @@ void graph_tree_model_delete( GraphTreeModel* model ){ class TempNameable : public Nameable { -const char* m_name; + const char* m_name; public: -TempNameable( const char* name ) : m_name( name ){ -} -const char* name() const { - return m_name; -} -void attach( const NameCallback& callback ){ -} -void detach( const NameCallback& callback ){ -} + TempNameable( const char* name ) : m_name( name ){ + } + const char* name() const { + return m_name; + } + void attach( const NameCallback& callback ){ + } + void detach( const NameCallback& callback ){ + } }; void node_attach_name_changed_callback( scene::Node& node, const NameCallback& callback ){ @@ -744,84 +744,84 @@ void graph_tree_model_row_changed( GraphTreeNode& node ); class GraphTreeNode { public: -typedef std::pair key_type; + typedef std::pair key_type; private: -struct Compare{ - bool operator()( const key_type& one, const key_type& other ) const { - const int n = string_compare( one.first.c_str(), other.first.c_str() ); - return n != 0? n < 0 : one.second < other.second; - } -}; -typedef std::map ChildNodes; -ChildNodes m_childnodes; + struct Compare{ + bool operator()( const key_type& one, const key_type& other ) const { + const int n = string_compare( one.first.c_str(), other.first.c_str() ); + return n != 0? n < 0 : one.second < other.second; + } + }; + typedef std::map ChildNodes; + ChildNodes m_childnodes; -struct Dummy{}; -std::list m_list; // dummy list for child index identification -std::list::const_iterator m_parentListIterator; // iterator from parent's list -bool m_searchFromEnd = false; //silly optimization + struct Dummy{}; + std::list m_list; // dummy list for child index identification + std::list::const_iterator m_parentListIterator; // iterator from parent's list + bool m_searchFromEnd = false; //silly optimization public: -Reference m_instance; -GraphTreeNode* m_parent; + Reference m_instance; + GraphTreeNode* m_parent; -typedef ChildNodes::iterator iterator; -typedef ChildNodes::value_type value_type; -typedef ChildNodes::size_type size_type; + typedef ChildNodes::iterator iterator; + typedef ChildNodes::value_type value_type; + typedef ChildNodes::size_type size_type; -GraphTreeNode( scene::Instance& instance ) : m_instance( instance ), m_parent( 0 ){ - m_instance.get().setChildSelectedChangedCallback( RowChangedCaller( *this ) ); -} -~GraphTreeNode(){ - m_instance.get().setChildSelectedChangedCallback( Callback() ); - ASSERT_MESSAGE( empty(), "GraphTreeNode::~GraphTreeNode: memory leak" ); -} -GraphTreeNode() = delete; -GraphTreeNode( const GraphTreeNode& ) = delete; -GraphTreeNode( GraphTreeNode&& ) noexcept = delete; -GraphTreeNode& operator=( const GraphTreeNode& ) = delete; -GraphTreeNode& operator=( GraphTreeNode&& ) noexcept = delete; + GraphTreeNode( scene::Instance& instance ) : m_instance( instance ), m_parent( 0 ){ + m_instance.get().setChildSelectedChangedCallback( RowChangedCaller( *this ) ); + } + ~GraphTreeNode(){ + m_instance.get().setChildSelectedChangedCallback( Callback() ); + ASSERT_MESSAGE( empty(), "GraphTreeNode::~GraphTreeNode: memory leak" ); + } + GraphTreeNode() = delete; + GraphTreeNode( const GraphTreeNode& ) = delete; + GraphTreeNode( GraphTreeNode&& ) noexcept = delete; + GraphTreeNode& operator=( const GraphTreeNode& ) = delete; + GraphTreeNode& operator=( GraphTreeNode&& ) noexcept = delete; -iterator begin(){ - return m_childnodes.begin(); -} -iterator end(){ - return m_childnodes.end(); -} + iterator begin(){ + return m_childnodes.begin(); + } + iterator end(){ + return m_childnodes.end(); + } -size_type size() const { - return m_childnodes.size(); -} -bool empty() const { - return m_childnodes.empty(); -} + size_type size() const { + return m_childnodes.size(); + } + bool empty() const { + return m_childnodes.empty(); + } // may not be called on the root node! -int getIndex() const { - const int idx = m_parent->m_searchFromEnd? - m_parent->m_list.size() - std::distance( m_parentListIterator, m_parent->m_list.cend() ) : - std::distance( m_parent->m_list.cbegin(), m_parentListIterator ); - m_parent->m_searchFromEnd = idx * 2 > int( m_parent->size() ); - return idx; -} + int getIndex() const { + const int idx = m_parent->m_searchFromEnd? + m_parent->m_list.size() - std::distance( m_parentListIterator, m_parent->m_list.cend() ) : + std::distance( m_parent->m_list.cbegin(), m_parentListIterator ); + m_parent->m_searchFromEnd = idx * 2 > int( m_parent->size() ); + return idx; + } -iterator insert( const value_type& value ){ - auto [ i, inserted ] = m_childnodes.insert( value ); - ASSERT_MESSAGE( inserted, "GraphTreeNode::insert: already added" ); - ( *i ).second->m_parent = this; - const auto pos = std::next( i ) == end()? m_list.end() : std::next( i )->second->m_parentListIterator; - i->second->m_parentListIterator = m_list.insert( pos, Dummy() ); - return i; -} -void erase( iterator i ){ - m_list.erase( i->second->m_parentListIterator ); - m_childnodes.erase( i ); -} -iterator find( const key_type& key ){ - return m_childnodes.find( key ); -} + iterator insert( const value_type& value ){ + auto [ i, inserted ] = m_childnodes.insert( value ); + ASSERT_MESSAGE( inserted, "GraphTreeNode::insert: already added" ); + ( *i ).second->m_parent = this; + const auto pos = std::next( i ) == end()? m_list.end() : std::next( i )->second->m_parentListIterator; + i->second->m_parentListIterator = m_list.insert( pos, Dummy() ); + return i; + } + void erase( iterator i ){ + m_list.erase( i->second->m_parentListIterator ); + m_childnodes.erase( i ); + } + iterator find( const key_type& key ){ + return m_childnodes.find( key ); + } -void rowChanged(){ - graph_tree_model_row_changed( *this ); -} -typedef MemberCaller RowChangedCaller; + void rowChanged(){ + graph_tree_model_row_changed( *this ); + } + typedef MemberCaller RowChangedCaller; }; struct GraphTreeModel @@ -1008,8 +1008,8 @@ scene::Node* g_null_node = 0; class NullInstance : public scene::Instance { public: -NullInstance() : scene::Instance( scene::Path( makeReference( *g_null_node ) ), 0, 0, Static::instance() ){ -} + NullInstance() : scene::Instance( scene::Path( makeReference( *g_null_node ) ), 0, 0, Static::instance() ){ + } }; namespace @@ -1080,11 +1080,11 @@ GType graph_tree_model_get_type( void ){ }; graph_tree_model_type = g_type_register_static( G_TYPE_OBJECT, "GraphTreeModel", - &graph_tree_model_info, (GTypeFlags)0 ); + &graph_tree_model_info, (GTypeFlags)0 ); g_type_add_interface_static( graph_tree_model_type, - GTK_TYPE_TREE_MODEL, - &tree_model_info ); + GTK_TYPE_TREE_MODEL, + &tree_model_info ); } return graph_tree_model_type; @@ -1256,182 +1256,182 @@ void graph_tree_model_erase( GraphTreeModel* model, const scene::Instance& insta class TestGraphTreeModel { public: -TestGraphTreeModel(){ - gtk_init( 0, 0 ); + TestGraphTreeModel(){ + gtk_init( 0, 0 ); - graph_type graph; + graph_type graph; - scene::Node* root = *(scene::Node*)0xa0000000; - scene::Node* node1 = (scene::Node*)0xa0000001; - scene::Node* node2 = (scene::Node*)0xa0000002; - scene::Node* node3 = (scene::Node*)0xa0000003; - scene::Node* node4 = (scene::Node*)0xa0000004; - scene::Instance* instance = (scene::Instance*)0xaaaaaaaa; + scene::Node* root = *(scene::Node*)0xa0000000; + scene::Node* node1 = (scene::Node*)0xa0000001; + scene::Node* node2 = (scene::Node*)0xa0000002; + scene::Node* node3 = (scene::Node*)0xa0000003; + scene::Node* node4 = (scene::Node*)0xa0000004; + scene::Instance* instance = (scene::Instance*)0xaaaaaaaa; - scene::Path rootpath( root ); + scene::Path rootpath( root ); - graph.insert( graph_type::value_type( rootpath, instance ) ); + graph.insert( graph_type::value_type( rootpath, instance ) ); - rootpath.push( node1 ); - graph.insert( graph_type::value_type( rootpath, instance ) ); - rootpath.pop(); + rootpath.push( node1 ); + graph.insert( graph_type::value_type( rootpath, instance ) ); + rootpath.pop(); - rootpath.push( node2 ); - graph.insert( graph_type::value_type( rootpath, instance ) ); - rootpath.push( node3 ); - graph.insert( graph_type::value_type( rootpath, instance ) ); - rootpath.pop(); - rootpath.push( node4 ); - graph.insert( graph_type::value_type( rootpath, instance ) ); - rootpath.pop(); - rootpath.pop(); + rootpath.push( node2 ); + graph.insert( graph_type::value_type( rootpath, instance ) ); + rootpath.push( node3 ); + graph.insert( graph_type::value_type( rootpath, instance ) ); + rootpath.pop(); + rootpath.push( node4 ); + graph.insert( graph_type::value_type( rootpath, instance ) ); + rootpath.pop(); + rootpath.pop(); - GtkTreeModel* model = GTK_TREE_MODEL( graph_tree_model_new( &graph ) ); - - { - gint n_columns = gtk_tree_model_get_n_columns( model ); - ASSERT_MESSAGE( n_columns == 2, "test failed!" ); - } - - { - GType type = gtk_tree_model_get_column_type( model, 0 ); - ASSERT_MESSAGE( type == G_TYPE_POINTER, "test failed!" ); - } - - { - GType type = gtk_tree_model_get_column_type( model, 1 ); - ASSERT_MESSAGE( type == G_TYPE_POINTER, "test failed!" ); - } - - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first( model, &iter ); - - graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); - ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node1, "test failed!" ); - } - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first( model, &iter ); - - ASSERT_MESSAGE( !gtk_tree_model_iter_has_child( model, &iter ), "test failed!" ); - - ASSERT_MESSAGE( gtk_tree_model_iter_n_children( model, &iter ) == 0, "test failed!" ); - - gtk_tree_model_iter_next( model, &iter ); - - ASSERT_MESSAGE( gtk_tree_model_iter_has_child( model, &iter ), "test failed!" ); - - ASSERT_MESSAGE( gtk_tree_model_iter_n_children( model, &iter ) == 2, "test failed!" ); + GtkTreeModel* model = GTK_TREE_MODEL( graph_tree_model_new( &graph ) ); { - GtkTreeIter child; - gtk_tree_model_iter_nth_child( model, &child, &iter, 0 ); + gint n_columns = gtk_tree_model_get_n_columns( model ); + ASSERT_MESSAGE( n_columns == 2, "test failed!" ); + } - scene::Node* test; - gtk_tree_model_get_value( model, &child, 0, (GValue*)&test ); - ASSERT_MESSAGE( test == node3, "test failed!" ); + { + GType type = gtk_tree_model_get_column_type( model, 0 ); + ASSERT_MESSAGE( type == G_TYPE_POINTER, "test failed!" ); + } + + { + GType type = gtk_tree_model_get_column_type( model, 1 ); + ASSERT_MESSAGE( type == G_TYPE_POINTER, "test failed!" ); + } + + + { + GtkTreeIter iter; + gtk_tree_model_get_iter_first( model, &iter ); + + graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); + ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node1, "test failed!" ); + } + + { + GtkTreeIter iter; + gtk_tree_model_get_iter_first( model, &iter ); + + ASSERT_MESSAGE( !gtk_tree_model_iter_has_child( model, &iter ), "test failed!" ); + + ASSERT_MESSAGE( gtk_tree_model_iter_n_children( model, &iter ) == 0, "test failed!" ); + + gtk_tree_model_iter_next( model, &iter ); + + ASSERT_MESSAGE( gtk_tree_model_iter_has_child( model, &iter ), "test failed!" ); + + ASSERT_MESSAGE( gtk_tree_model_iter_n_children( model, &iter ) == 2, "test failed!" ); { - GtkTreeIter parent; - gtk_tree_model_iter_parent( model, &parent, &child ); + GtkTreeIter child; + gtk_tree_model_iter_nth_child( model, &child, &iter, 0 ); scene::Node* test; - gtk_tree_model_get_value( model, &parent, 0, (GValue*)&test ); - ASSERT_MESSAGE( test == node2, "test failed!" ); + gtk_tree_model_get_value( model, &child, 0, (GValue*)&test ); + ASSERT_MESSAGE( test == node3, "test failed!" ); + + { + GtkTreeIter parent; + gtk_tree_model_iter_parent( model, &parent, &child ); + + scene::Node* test; + gtk_tree_model_get_value( model, &parent, 0, (GValue*)&test ); + ASSERT_MESSAGE( test == node2, "test failed!" ); + } + } + + { + GtkTreeIter child; + gtk_tree_model_iter_nth_child( model, &child, &iter, 1 ); + + scene::Node* test; + gtk_tree_model_get_value( model, &child, 0, (GValue*)&test ); + ASSERT_MESSAGE( test == node4, "test failed!" ); } } { - GtkTreeIter child; - gtk_tree_model_iter_nth_child( model, &child, &iter, 1 ); + GtkTreeIter iter; + std::size_t count = 0; + for ( gboolean good = gtk_tree_model_get_iter_first( model, &iter ); good; good = gtk_tree_model_iter_next( model, &iter ) ) + { + scene::Node* test; + gtk_tree_model_get_value( model, &iter, 0, (GValue*)&test ); + + ASSERT_MESSAGE( ( count == 0 && test == node1 ) || ( count == 1 && test == node2 ), "test failed!" ); + ++count; + } + + ASSERT_MESSAGE( count == 2, "test failed!" ); - scene::Node* test; - gtk_tree_model_get_value( model, &child, 0, (GValue*)&test ); - ASSERT_MESSAGE( test == node4, "test failed!" ); } - } - { - GtkTreeIter iter; - std::size_t count = 0; - for ( gboolean good = gtk_tree_model_get_iter_first( model, &iter ); good; good = gtk_tree_model_iter_next( model, &iter ) ) { + GtkTreeIter iter; + gtk_tree_model_get_iter_first( model, &iter ); + scene::Node* test; gtk_tree_model_get_value( model, &iter, 0, (GValue*)&test ); - - ASSERT_MESSAGE( ( count == 0 && test == node1 ) || ( count == 1 && test == node2 ), "test failed!" ); - ++count; + ASSERT_MESSAGE( test == node1, "test failed!" ); } - ASSERT_MESSAGE( count == 2, "test failed!" ); + { + GtkTreeIter iter; + GtkTreePath* path = gtk_tree_path_new_from_string( "0" ); + gtk_tree_model_get_iter( model, &iter, path ); + gtk_tree_path_free( path ); + graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); + ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node1, "test failed!" ); + } + + { + GtkTreeIter iter; + GtkTreePath* path = gtk_tree_path_new_from_string( "1" ); + gtk_tree_model_get_iter( model, &iter, path ); + gtk_tree_path_free( path ); + + graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); + ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node2, "test failed!" ); + } + + { + GtkTreeIter iter; + graph_type::iterator i = graph.begin(); + ++i; + graph_iterator_write_tree_iter( i, &iter ); + + GtkTreePath* path = gtk_tree_model_get_path( model, &iter ); + + gint depth = gtk_tree_path_get_depth( path ); + gint* indices = gtk_tree_path_get_indices( path ); + + ASSERT_MESSAGE( depth == 1 && indices[0] == 0, "test failed!" ); + + gtk_tree_path_free( path ); + } + + { + GtkTreeIter iter; + graph_type::iterator i = graph.begin(); + ++i; + ++i; + graph_iterator_write_tree_iter( i, &iter ); + + GtkTreePath* path = gtk_tree_model_get_path( model, &iter ); + + gint depth = gtk_tree_path_get_depth( path ); + gint* indices = gtk_tree_path_get_indices( path ); + + ASSERT_MESSAGE( depth == 1 && indices[0] == 1, "test failed!" ); + + gtk_tree_path_free( path ); + } } - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first( model, &iter ); - - scene::Node* test; - gtk_tree_model_get_value( model, &iter, 0, (GValue*)&test ); - ASSERT_MESSAGE( test == node1, "test failed!" ); - } - - { - GtkTreeIter iter; - GtkTreePath* path = gtk_tree_path_new_from_string( "0" ); - gtk_tree_model_get_iter( model, &iter, path ); - gtk_tree_path_free( path ); - - graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); - ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node1, "test failed!" ); - } - - { - GtkTreeIter iter; - GtkTreePath* path = gtk_tree_path_new_from_string( "1" ); - gtk_tree_model_get_iter( model, &iter, path ); - gtk_tree_path_free( path ); - - graph_type::iterator i = graph_iterator_read_tree_iter( &iter ); - ASSERT_MESSAGE( ( *i ).first.get().size() == 2 && ( *i ).first.get().top() == node2, "test failed!" ); - } - - { - GtkTreeIter iter; - graph_type::iterator i = graph.begin(); - ++i; - graph_iterator_write_tree_iter( i, &iter ); - - GtkTreePath* path = gtk_tree_model_get_path( model, &iter ); - - gint depth = gtk_tree_path_get_depth( path ); - gint* indices = gtk_tree_path_get_indices( path ); - - ASSERT_MESSAGE( depth == 1 && indices[0] == 0, "test failed!" ); - - gtk_tree_path_free( path ); - } - - { - GtkTreeIter iter; - graph_type::iterator i = graph.begin(); - ++i; - ++i; - graph_iterator_write_tree_iter( i, &iter ); - - GtkTreePath* path = gtk_tree_model_get_path( model, &iter ); - - gint depth = gtk_tree_path_get_depth( path ); - gint* indices = gtk_tree_path_get_indices( path ); - - ASSERT_MESSAGE( depth == 1 && indices[0] == 1, "test failed!" ); - - gtk_tree_path_free( path ); - } -} }; diff --git a/radiant/undo.cpp b/radiant/undo.cpp index 82ba81da..dd8005bf 100644 --- a/radiant/undo.cpp +++ b/radiant/undo.cpp @@ -39,338 +39,338 @@ class DebugScopeTimer { -Timer m_timer; -const char* m_operation; + Timer m_timer; + const char* m_operation; public: -DebugScopeTimer( const char* operation ) - : m_operation( operation ){ - m_timer.start(); -} -~DebugScopeTimer(){ - unsigned int elapsed = m_timer.elapsed_msec(); - if ( elapsed > 0 ) { - globalOutputStream() << m_operation << ": " << elapsed << " msec\n"; + DebugScopeTimer( const char* operation ) + : m_operation( operation ){ + m_timer.start(); + } + ~DebugScopeTimer(){ + unsigned int elapsed = m_timer.elapsed_msec(); + if ( elapsed > 0 ) { + globalOutputStream() << m_operation << ": " << elapsed << " msec\n"; + } } -} }; class RadiantUndoSystem : public UndoSystem { -INTEGER_CONSTANT( MAX_UNDO_LEVELS, 4096 ); + INTEGER_CONSTANT( MAX_UNDO_LEVELS, 4096 ); -class Snapshot -{ -class StateApplicator -{ -public: -Undoable* m_undoable; -private: -UndoMemento* m_data; -public: - -StateApplicator( Undoable* undoable, UndoMemento* data ) - : m_undoable( undoable ), m_data( data ){ -} -void restore(){ - m_undoable->importState( m_data ); -} -void release(){ - m_data->release(); -} -}; - -typedef std::list states_t; -states_t m_states; - -public: -bool empty() const { - return m_states.empty(); -} -std::size_t size() const { - return m_states.size(); -} -void save( Undoable* undoable ){ - m_states.push_front( StateApplicator( undoable, undoable->exportState() ) ); -} -void restore(){ - for ( states_t::iterator i = m_states.begin(); i != m_states.end(); ++i ) + class Snapshot { - ( *i ).restore(); - } -} -void release(){ - for ( states_t::iterator i = m_states.begin(); i != m_states.end(); ++i ) - { - ( *i ).release(); - } -} -}; - -struct Operation -{ - Snapshot m_snapshot; - CopiedString m_command; - - Operation( const char* command ) - : m_command( command ){ - } - ~Operation(){ - m_snapshot.release(); - } -}; - - -class UndoStack -{ -//! Note: using std::list instead of vector/deque, to avoid copying of undos -typedef std::list Operations; - -Operations m_stack; -Operation* m_pending; - -public: -UndoStack() : m_pending( 0 ){ -} -~UndoStack(){ - clear(); -} -bool empty() const { - return m_stack.empty(); -} -std::size_t size() const { - return m_stack.size(); -} -Operation* back(){ - return m_stack.back(); -} -const Operation* back() const { - return m_stack.back(); -} -Operation* front(){ - return m_stack.front(); -} -const Operation* front() const { - return m_stack.front(); -} -void pop_front(){ - delete m_stack.front(); - m_stack.pop_front(); -} -void pop_back(){ - delete m_stack.back(); - m_stack.pop_back(); -} -void clear(){ - if ( !m_stack.empty() ) { - for ( Operations::iterator i = m_stack.begin(); i != m_stack.end(); ++i ) + class StateApplicator { - delete *i; + public: + Undoable* m_undoable; + private: + UndoMemento* m_data; + public: + + StateApplicator( Undoable* undoable, UndoMemento* data ) + : m_undoable( undoable ), m_data( data ){ + } + void restore(){ + m_undoable->importState( m_data ); + } + void release(){ + m_data->release(); + } + }; + + typedef std::list states_t; + states_t m_states; + + public: + bool empty() const { + return m_states.empty(); } - m_stack.clear(); - } -} -void start( const char* command ){ - if ( m_pending != 0 ) { - delete m_pending; - } - m_pending = new Operation( command ); -} -bool finish( const char* command ){ - if ( m_pending != 0 ) { - delete m_pending; - m_pending = 0; - return false; - } - else + std::size_t size() const { + return m_states.size(); + } + void save( Undoable* undoable ){ + m_states.push_front( StateApplicator( undoable, undoable->exportState() ) ); + } + void restore(){ + for ( states_t::iterator i = m_states.begin(); i != m_states.end(); ++i ) + { + ( *i ).restore(); + } + } + void release(){ + for ( states_t::iterator i = m_states.begin(); i != m_states.end(); ++i ) + { + ( *i ).release(); + } + } + }; + + struct Operation { - ASSERT_MESSAGE( !m_stack.empty(), "undo stack empty" ); - m_stack.back()->m_command = command; - return true; - } -} -void save( Undoable* undoable ){ - if ( m_pending != 0 ) { - m_stack.push_back( m_pending ); - m_pending = 0; - } - back()->m_snapshot.save( undoable ); -} -}; + Snapshot m_snapshot; + CopiedString m_command; -UndoStack m_undo_stack; -UndoStack m_redo_stack; + Operation( const char* command ) + : m_command( command ){ + } + ~Operation(){ + m_snapshot.release(); + } + }; -class UndoStackFiller : public UndoObserver -{ -UndoStack* m_stack; + + class UndoStack + { +//! Note: using std::list instead of vector/deque, to avoid copying of undos + typedef std::list Operations; + + Operations m_stack; + Operation* m_pending; + + public: + UndoStack() : m_pending( 0 ){ + } + ~UndoStack(){ + clear(); + } + bool empty() const { + return m_stack.empty(); + } + std::size_t size() const { + return m_stack.size(); + } + Operation* back(){ + return m_stack.back(); + } + const Operation* back() const { + return m_stack.back(); + } + Operation* front(){ + return m_stack.front(); + } + const Operation* front() const { + return m_stack.front(); + } + void pop_front(){ + delete m_stack.front(); + m_stack.pop_front(); + } + void pop_back(){ + delete m_stack.back(); + m_stack.pop_back(); + } + void clear(){ + if ( !m_stack.empty() ) { + for ( Operations::iterator i = m_stack.begin(); i != m_stack.end(); ++i ) + { + delete *i; + } + m_stack.clear(); + } + } + void start( const char* command ){ + if ( m_pending != 0 ) { + delete m_pending; + } + m_pending = new Operation( command ); + } + bool finish( const char* command ){ + if ( m_pending != 0 ) { + delete m_pending; + m_pending = 0; + return false; + } + else + { + ASSERT_MESSAGE( !m_stack.empty(), "undo stack empty" ); + m_stack.back()->m_command = command; + return true; + } + } + void save( Undoable* undoable ){ + if ( m_pending != 0 ) { + m_stack.push_back( m_pending ); + m_pending = 0; + } + back()->m_snapshot.save( undoable ); + } + }; + + UndoStack m_undo_stack; + UndoStack m_redo_stack; + + class UndoStackFiller : public UndoObserver + { + UndoStack* m_stack; + public: + + UndoStackFiller() + : m_stack( 0 ){ + } + void save( Undoable* undoable ){ + ASSERT_NOTNULL( undoable ); + + if ( m_stack != 0 ) { + m_stack->save( undoable ); + m_stack = 0; + } + } + void setStack( UndoStack* stack ){ + m_stack = stack; + } + }; + + typedef std::map undoables_t; + undoables_t m_undoables; + + void mark_undoables( UndoStack* stack ){ + for ( undoables_t::iterator i = m_undoables.begin(); i != m_undoables.end(); ++i ) + { + ( *i ).second.setStack( stack ); + } + } + + std::size_t m_undo_levels; + + typedef std::set Trackers; + Trackers m_trackers; public: - -UndoStackFiller() - : m_stack( 0 ){ -} -void save( Undoable* undoable ){ - ASSERT_NOTNULL( undoable ); - - if ( m_stack != 0 ) { - m_stack->save( undoable ); - m_stack = 0; + RadiantUndoSystem() + : m_undo_levels( 512 ){ } -} -void setStack( UndoStack* stack ){ - m_stack = stack; -} -}; - -typedef std::map undoables_t; -undoables_t m_undoables; - -void mark_undoables( UndoStack* stack ){ - for ( undoables_t::iterator i = m_undoables.begin(); i != m_undoables.end(); ++i ) - { - ( *i ).second.setStack( stack ); + ~RadiantUndoSystem(){ + clear(); } -} + UndoObserver* observer( Undoable* undoable ){ + ASSERT_NOTNULL( undoable ); -std::size_t m_undo_levels; + return &m_undoables[undoable]; + } + void release( Undoable* undoable ){ + ASSERT_NOTNULL( undoable ); -typedef std::set Trackers; -Trackers m_trackers; -public: -RadiantUndoSystem() - : m_undo_levels( 512 ){ -} -~RadiantUndoSystem(){ - clear(); -} -UndoObserver* observer( Undoable* undoable ){ - ASSERT_NOTNULL( undoable ); + m_undoables.erase( undoable ); + } + void setLevels( std::size_t levels ){ + if ( levels > static_cast( MAX_UNDO_LEVELS() ) ) { + levels = MAX_UNDO_LEVELS(); + } - return &m_undoables[undoable]; -} -void release( Undoable* undoable ){ - ASSERT_NOTNULL( undoable ); - - m_undoables.erase( undoable ); -} -void setLevels( std::size_t levels ){ - if ( levels > static_cast( MAX_UNDO_LEVELS() ) ) { - levels = MAX_UNDO_LEVELS(); + while ( m_undo_stack.size() > levels ) + { + m_undo_stack.pop_front(); + } + m_undo_levels = levels; } - - while ( m_undo_stack.size() > levels ) - { - m_undo_stack.pop_front(); + std::size_t getLevels() const { + return m_undo_levels; } - m_undo_levels = levels; -} -std::size_t getLevels() const { - return m_undo_levels; -} -std::size_t size() const { - return m_undo_stack.size(); -} -void startUndo(){ - m_undo_stack.start( "unnamedCommand" ); - mark_undoables( &m_undo_stack ); -} -bool finishUndo( const char* command ){ - bool changed = m_undo_stack.finish( command ); - mark_undoables( 0 ); - return changed; -} -void startRedo(){ - m_redo_stack.start( "unnamedCommand" ); - mark_undoables( &m_redo_stack ); -} -bool finishRedo( const char* command ){ - bool changed = m_redo_stack.finish( command ); - mark_undoables( 0 ); - return changed; -} -void start(){ - m_redo_stack.clear(); - if ( m_undo_stack.size() == m_undo_levels ) { - m_undo_stack.pop_front(); + std::size_t size() const { + return m_undo_stack.size(); } - startUndo(); - trackersBegin(); -} -void finish( const char* command ){ - if ( finishUndo( command ) ) { - globalOutputStream() << command << '\n'; + void startUndo(){ + m_undo_stack.start( "unnamedCommand" ); + mark_undoables( &m_undo_stack ); } -} -void undo(){ - if ( m_undo_stack.empty() ) { - globalOutputStream() << "Undo: no undo available\n"; + bool finishUndo( const char* command ){ + bool changed = m_undo_stack.finish( command ); + mark_undoables( 0 ); + return changed; } - else - { - Operation* operation = m_undo_stack.back(); - globalOutputStream() << "Undo: " << operation->m_command.c_str() << "\n"; - - startRedo(); - trackersUndo(); - operation->m_snapshot.restore(); - finishRedo( operation->m_command.c_str() ); - m_undo_stack.pop_back(); + void startRedo(){ + m_redo_stack.start( "unnamedCommand" ); + mark_undoables( &m_redo_stack ); } -} -void redo(){ - if ( m_redo_stack.empty() ) { - globalOutputStream() << "Redo: no redo available\n"; + bool finishRedo( const char* command ){ + bool changed = m_redo_stack.finish( command ); + mark_undoables( 0 ); + return changed; } - else - { - Operation* operation = m_redo_stack.back(); - globalOutputStream() << "Redo: " << operation->m_command.c_str() << "\n"; - + void start(){ + m_redo_stack.clear(); + if ( m_undo_stack.size() == m_undo_levels ) { + m_undo_stack.pop_front(); + } startUndo(); - trackersRedo(); - operation->m_snapshot.restore(); - finishUndo( operation->m_command.c_str() ); - m_redo_stack.pop_back(); + trackersBegin(); } -} -void clear(){ - mark_undoables( 0 ); - m_undo_stack.clear(); - m_redo_stack.clear(); - trackersClear(); -} -void trackerAttach( UndoTracker& tracker ){ - const bool inserted = m_trackers.insert( &tracker ).second; - ASSERT_MESSAGE( inserted, "undo tracker already attached" ); -} -void trackerDetach( UndoTracker& tracker ){ - const bool erased = m_trackers.erase( &tracker ); - ASSERT_MESSAGE( erased, "undo tracker cannot be detached" ); -} -void trackersClear() const { - for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) - { - ( *i )->clear(); + void finish( const char* command ){ + if ( finishUndo( command ) ) { + globalOutputStream() << command << '\n'; + } } -} -void trackersBegin() const { - for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) - { - ( *i )->begin(); + void undo(){ + if ( m_undo_stack.empty() ) { + globalOutputStream() << "Undo: no undo available\n"; + } + else + { + Operation* operation = m_undo_stack.back(); + globalOutputStream() << "Undo: " << operation->m_command.c_str() << "\n"; + + startRedo(); + trackersUndo(); + operation->m_snapshot.restore(); + finishRedo( operation->m_command.c_str() ); + m_undo_stack.pop_back(); + } } -} -void trackersUndo() const { - for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) - { - ( *i )->undo(); + void redo(){ + if ( m_redo_stack.empty() ) { + globalOutputStream() << "Redo: no redo available\n"; + } + else + { + Operation* operation = m_redo_stack.back(); + globalOutputStream() << "Redo: " << operation->m_command.c_str() << "\n"; + + startUndo(); + trackersRedo(); + operation->m_snapshot.restore(); + finishUndo( operation->m_command.c_str() ); + m_redo_stack.pop_back(); + } } -} -void trackersRedo() const { - for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) - { - ( *i )->redo(); + void clear(){ + mark_undoables( 0 ); + m_undo_stack.clear(); + m_redo_stack.clear(); + trackersClear(); + } + void trackerAttach( UndoTracker& tracker ){ + const bool inserted = m_trackers.insert( &tracker ).second; + ASSERT_MESSAGE( inserted, "undo tracker already attached" ); + } + void trackerDetach( UndoTracker& tracker ){ + const bool erased = m_trackers.erase( &tracker ); + ASSERT_MESSAGE( erased, "undo tracker cannot be detached" ); + } + void trackersClear() const { + for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) + { + ( *i )->clear(); + } + } + void trackersBegin() const { + for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) + { + ( *i )->begin(); + } + } + void trackersUndo() const { + for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) + { + ( *i )->undo(); + } + } + void trackersRedo() const { + for ( Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i ) + { + ( *i )->redo(); + } } -} }; @@ -415,19 +415,19 @@ class UndoSystemDependencies : public GlobalPreferenceSystemModuleRef class UndoSystemAPI { -RadiantUndoSystem m_undosystem; + RadiantUndoSystem m_undosystem; public: -typedef UndoSystem Type; -STRING_CONSTANT( Name, "*" ); + typedef UndoSystem Type; + STRING_CONSTANT( Name, "*" ); -UndoSystemAPI(){ - GlobalPreferenceSystem().registerPreference( "UndoLevels", makeIntStringImportCallback( UndoLevelsImportCaller( m_undosystem ) ), makeIntStringExportCallback( UndoLevelsExportCaller( m_undosystem ) ) ); + UndoSystemAPI(){ + GlobalPreferenceSystem().registerPreference( "UndoLevels", makeIntStringImportCallback( UndoLevelsImportCaller( m_undosystem ) ), makeIntStringExportCallback( UndoLevelsExportCaller( m_undosystem ) ) ); - Undo_registerPreferencesPage( m_undosystem ); -} -UndoSystem* getTable(){ - return &m_undosystem; -} + Undo_registerPreferencesPage( m_undosystem ); + } + UndoSystem* getTable(){ + return &m_undosystem; + } }; #include "modulesystem/singletonmodule.h" @@ -448,41 +448,41 @@ StaticRegisterModule staticRegisterUndoSystem( StaticUndoSystemModule::instance( class undoable_test : public Undoable { -struct state_type : public UndoMemento -{ - state_type() : test_data( 0 ){ - } - state_type( const state_type& other ) : UndoMemento( other ), test_data( other.test_data ){ - } - void release(){ - delete this; - } + struct state_type : public UndoMemento + { + state_type() : test_data( 0 ){ + } + state_type( const state_type& other ) : UndoMemento( other ), test_data( other.test_data ){ + } + void release(){ + delete this; + } - int test_data; -}; -state_type m_state; -UndoObserver* m_observer; + int test_data; + }; + state_type m_state; + UndoObserver* m_observer; public: -undoable_test() - : m_observer( GlobalUndoSystem().observer( this ) ){ -} -~undoable_test(){ - GlobalUndoSystem().release( this ); -} -UndoMemento* exportState() const { - return new state_type( m_state ); -} -void importState( const UndoMemento* state ){ - ASSERT_NOTNULL( state ); + undoable_test() + : m_observer( GlobalUndoSystem().observer( this ) ){ + } + ~undoable_test(){ + GlobalUndoSystem().release( this ); + } + UndoMemento* exportState() const { + return new state_type( m_state ); + } + void importState( const UndoMemento* state ){ + ASSERT_NOTNULL( state ); - m_observer->save( this ); - m_state = *( static_cast( state ) ); -} + m_observer->save( this ); + m_state = *( static_cast( state ) ); + } -void mutate( unsigned int data ){ - m_observer->save( this ); - m_state.test_data = data; -} + void mutate( unsigned int data ){ + m_observer->save( this ); + m_state.test_data = data; + } }; #if 0 @@ -490,17 +490,17 @@ void mutate( unsigned int data ){ class TestUndo { public: -TestUndo(){ - undoable_test test; - GlobalUndoSystem().begin( "bleh" ); - test.mutate( 3 ); - GlobalUndoSystem().begin( "blah" ); - test.mutate( 4 ); - GlobalUndoSystem().undo(); - GlobalUndoSystem().undo(); - GlobalUndoSystem().redo(); - GlobalUndoSystem().redo(); -} + TestUndo(){ + undoable_test test; + GlobalUndoSystem().begin( "bleh" ); + test.mutate( 3 ); + GlobalUndoSystem().begin( "blah" ); + test.mutate( 4 ); + GlobalUndoSystem().undo(); + GlobalUndoSystem().undo(); + GlobalUndoSystem().redo(); + GlobalUndoSystem().redo(); + } }; TestUndo g_TestUndo; diff --git a/radiant/url.cpp b/radiant/url.cpp index 60535d85..4300416d 100644 --- a/radiant/url.cpp +++ b/radiant/url.cpp @@ -37,7 +37,7 @@ bool open_url( const char* url ){ bool open_url( const char* url ){ char command[2 * PATH_MAX]; snprintf( command, sizeof( command ), - "xdg-open \"%s\" &", url ); + "xdg-open \"%s\" &", url ); return system( command ) == 0; } #endif diff --git a/radiant/view.h b/radiant/view.h index 0385c32b..35303f8b 100644 --- a/radiant/view.h +++ b/radiant/view.h @@ -78,123 +78,123 @@ inline void debug_count_oriented_bbox(){ class View : public VolumeTest { /// modelview matrix -Matrix4 m_modelview; + Matrix4 m_modelview; /// projection matrix -Matrix4 m_projection; + Matrix4 m_projection; /// device-to-screen transform -Matrix4 m_viewport; + Matrix4 m_viewport; -Matrix4 m_scissor; + Matrix4 m_scissor; /// combined modelview and projection matrix -Matrix4 m_viewproj; + Matrix4 m_viewproj; /// camera position in world space -Vector4 m_viewer; + Vector4 m_viewer; /// view frustum in world space -Frustum m_frustum; + Frustum m_frustum; -Vector3 m_viewdir; + Vector3 m_viewdir; -bool m_fill; + bool m_fill; -void construct(){ - m_viewproj = matrix4_multiplied_by_matrix4( matrix4_multiplied_by_matrix4( m_scissor, m_projection ), m_modelview ); + void construct(){ + m_viewproj = matrix4_multiplied_by_matrix4( matrix4_multiplied_by_matrix4( m_scissor, m_projection ), m_modelview ); - m_frustum = frustum_from_viewproj( m_viewproj ); - m_viewer = viewer_from_viewproj( m_viewproj ); - m_viewdir = vector3_normalised( fill()? Vector3( -m_modelview[2], -m_modelview[6], -m_modelview[10] ) : Vector3( m_modelview[2], m_modelview[6], m_modelview[10] ) ); -} + m_frustum = frustum_from_viewproj( m_viewproj ); + m_viewer = viewer_from_viewproj( m_viewproj ); + m_viewdir = vector3_normalised( fill()? Vector3( -m_modelview[2], -m_modelview[6], -m_modelview[10] ) : Vector3( m_modelview[2], m_modelview[6], m_modelview[10] ) ); + } public: -View( bool fill = false ) : - m_modelview( g_matrix4_identity ), - m_projection( g_matrix4_identity ), - m_scissor( g_matrix4_identity ), - m_fill( fill ){ -} -void Construct( const Matrix4& projection, const Matrix4& modelview, std::size_t width, std::size_t height ){ - // modelview - m_modelview = modelview; - - // projection - m_projection = projection; - - // viewport - m_viewport = g_matrix4_identity; - m_viewport[0] = float(width / 2); - m_viewport[5] = float(height / 2); - if ( fabs( m_projection[11] ) > 0.0000001 ) { - m_viewport[10] = m_projection[0] * m_viewport[0]; + View( bool fill = false ) : + m_modelview( g_matrix4_identity ), + m_projection( g_matrix4_identity ), + m_scissor( g_matrix4_identity ), + m_fill( fill ){ } - else{ - m_viewport[10] = 1 / m_projection[10]; + void Construct( const Matrix4& projection, const Matrix4& modelview, std::size_t width, std::size_t height ){ + // modelview + m_modelview = modelview; + + // projection + m_projection = projection; + + // viewport + m_viewport = g_matrix4_identity; + m_viewport[0] = float(width / 2); + m_viewport[5] = float(height / 2); + if ( fabs( m_projection[11] ) > 0.0000001 ) { + m_viewport[10] = m_projection[0] * m_viewport[0]; + } + else{ + m_viewport[10] = 1 / m_projection[10]; + } + + construct(); + } + void EnableScissor( float min_x, float max_x, float min_y, float max_y ){ + m_scissor = g_matrix4_identity; + m_scissor[0] = static_cast( ( max_x - min_x ) * 0.5 ); + m_scissor[5] = static_cast( ( max_y - min_y ) * 0.5 ); + m_scissor[12] = static_cast( ( min_x + max_x ) * 0.5 ); + m_scissor[13] = static_cast( ( min_y + max_y ) * 0.5 ); + matrix4_full_invert( m_scissor ); + + construct(); + } + void DisableScissor(){ + m_scissor = g_matrix4_identity; + + construct(); } - construct(); -} -void EnableScissor( float min_x, float max_x, float min_y, float max_y ){ - m_scissor = g_matrix4_identity; - m_scissor[0] = static_cast( ( max_x - min_x ) * 0.5 ); - m_scissor[5] = static_cast( ( max_y - min_y ) * 0.5 ); - m_scissor[12] = static_cast( ( min_x + max_x ) * 0.5 ); - m_scissor[13] = static_cast( ( min_y + max_y ) * 0.5 ); - matrix4_full_invert( m_scissor ); + bool TestPoint( const Vector3& point ) const { + return viewproj_test_point( m_viewproj, point ); + } + bool TestLine( const Segment& segment ) const { + return frustum_test_line( m_frustum, segment ); + } + bool TestPlane( const Plane3& plane ) const { + debug_count_plane(); + return viewer_test_plane( m_viewer, plane ); + } + bool TestPlane( const Plane3& plane, const Matrix4& localToWorld ) const { + debug_count_oriented_plane(); + return viewer_test_transformed_plane( m_viewer, plane, localToWorld ); + } + VolumeIntersectionValue TestAABB( const AABB& aabb ) const { + debug_count_bbox(); + return frustum_test_aabb( m_frustum, aabb ); + } + VolumeIntersectionValue TestAABB( const AABB& aabb, const Matrix4& localToWorld ) const { + debug_count_oriented_bbox(); + return frustum_intersects_transformed_aabb( m_frustum, aabb, localToWorld ); + } - construct(); -} -void DisableScissor(){ - m_scissor = g_matrix4_identity; + const Matrix4& GetViewMatrix() const { + return m_viewproj; + } + const Matrix4& GetViewport() const { + return m_viewport; + } + const Matrix4& GetModelview() const { + return m_modelview; + } + const Matrix4& GetProjection() const { + return m_projection; + } - construct(); -} - -bool TestPoint( const Vector3& point ) const { - return viewproj_test_point( m_viewproj, point ); -} -bool TestLine( const Segment& segment ) const { - return frustum_test_line( m_frustum, segment ); -} -bool TestPlane( const Plane3& plane ) const { - debug_count_plane(); - return viewer_test_plane( m_viewer, plane ); -} -bool TestPlane( const Plane3& plane, const Matrix4& localToWorld ) const { - debug_count_oriented_plane(); - return viewer_test_transformed_plane( m_viewer, plane, localToWorld ); -} -VolumeIntersectionValue TestAABB( const AABB& aabb ) const { - debug_count_bbox(); - return frustum_test_aabb( m_frustum, aabb ); -} -VolumeIntersectionValue TestAABB( const AABB& aabb, const Matrix4& localToWorld ) const { - debug_count_oriented_bbox(); - return frustum_intersects_transformed_aabb( m_frustum, aabb, localToWorld ); -} - -const Matrix4& GetViewMatrix() const { - return m_viewproj; -} -const Matrix4& GetViewport() const { - return m_viewport; -} -const Matrix4& GetModelview() const { - return m_modelview; -} -const Matrix4& GetProjection() const { - return m_projection; -} - -bool fill() const { - return m_fill; -} -const Vector3& getViewer() const { - return vector4_to_vector3( m_viewer ); -} -const Vector3& getViewDir() const { - return m_viewdir; -} -const Frustum& getFrustum() const { - return m_frustum; -} + bool fill() const { + return m_fill; + } + const Vector3& getViewer() const { + return vector4_to_vector3( m_viewer ); + } + const Vector3& getViewDir() const { + return m_viewdir; + } + const Frustum& getFrustum() const { + return m_frustum; + } }; #endif diff --git a/radiant/watchbsp.cpp b/radiant/watchbsp.cpp index d85a1905..fb3b809d 100644 --- a/radiant/watchbsp.cpp +++ b/radiant/watchbsp.cpp @@ -85,7 +85,7 @@ private: // a flag we have set to true when using an external BSP plugin // the resulting code with that is a bit dirty, cleaner solution would be to seperate the succession of commands from the listening loop // (in two seperate classes probably) -bool m_bBSPPlugin; + bool m_bBSPPlugin; // EIdle: we are not listening // DoMonitoringLoop will change state to EBeginStep @@ -93,69 +93,71 @@ bool m_bBSPPlugin; // incoming connection will change state to EWatching // EWatching: we have a connection, monitor it // connection closed will see if we start a new step (EBeginStep) or launch Quake3 and end (EIdle) -enum EWatchBSPState { EIdle, EBeginStep, EWatching } m_eState; -socket_t *m_pListenSocket; -socket_t *m_pInSocket; -netmessage_t msg; -GPtrArray *m_pCmd; + enum EWatchBSPState { EIdle, EBeginStep, EWatching } m_eState; + socket_t *m_pListenSocket; + socket_t *m_pInSocket; + netmessage_t msg; + GPtrArray *m_pCmd; // used to timeout EBeginStep -GTimer *m_pTimer; -std::size_t m_iCurrentStep; + GTimer *m_pTimer; + std::size_t m_iCurrentStep; // name of the map so we can run the engine -char *m_sBSPName; + char *m_sBSPName; // buffer we use in push mode to receive data directly from the network -xmlParserInputBufferPtr m_xmlInputBuffer; -xmlParserCtxtPtr m_xmlParserCtxt; + xmlParserInputBufferPtr m_xmlInputBuffer; + xmlParserCtxtPtr m_xmlParserCtxt; // call this to switch the set listening mode -bool SetupListening(); + bool SetupListening(); // start a new EBeginStep -void DoEBeginStep(); + void DoEBeginStep(); // the xml and sax parser state -char m_xmlBuf[MAX_NETMESSAGE]; -bool m_bNeedCtxtInit; -message_info_t m_message_info; + char m_xmlBuf[MAX_NETMESSAGE]; + bool m_bNeedCtxtInit; + message_info_t m_message_info; public: -CWatchBSP(){ - m_pCmd = 0; - m_bBSPPlugin = false; - m_pListenSocket = NULL; - m_pInSocket = NULL; - m_eState = EIdle; - m_pTimer = g_timer_new(); - m_sBSPName = NULL; - m_xmlInputBuffer = NULL; - m_bNeedCtxtInit = true; -} -virtual ~CWatchBSP(){ - EndMonitoringLoop(); - Net_Shutdown(); + CWatchBSP(){ + m_pCmd = 0; + m_bBSPPlugin = false; + m_pListenSocket = NULL; + m_pInSocket = NULL; + m_eState = EIdle; + m_pTimer = g_timer_new(); + m_sBSPName = NULL; + m_xmlInputBuffer = NULL; + m_bNeedCtxtInit = true; + } + virtual ~CWatchBSP(){ + EndMonitoringLoop(); + Net_Shutdown(); - g_timer_destroy( m_pTimer ); -} + g_timer_destroy( m_pTimer ); + } -bool HasBSPPlugin() const -{ return m_bBSPPlugin; } + bool HasBSPPlugin() const + { + return m_bBSPPlugin; + } // called regularly to keep listening -void RoutineProcessing(); + void RoutineProcessing(); // start a monitoring loop with the following steps -void DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ); -void EndMonitoringLoop(){ - Reset(); - if ( m_sBSPName ) { - string_release( m_sBSPName, string_length( m_sBSPName ) ); - m_sBSPName = 0; + void DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ); + void EndMonitoringLoop(){ + Reset(); + if ( m_sBSPName ) { + string_release( m_sBSPName, string_length( m_sBSPName ) ); + m_sBSPName = 0; + } + if ( m_pCmd ) { + g_ptr_array_free( m_pCmd, TRUE ); + m_pCmd = 0; + } } - if ( m_pCmd ) { - g_ptr_array_free( m_pCmd, TRUE ); - m_pCmd = 0; - } -} // close everything - may be called from the outside to abort the process -void Reset(); + void Reset(); // start a listening loop for an external process, possibly a BSP plugin -void ExternalListen(); + void ExternalListen(); }; CWatchBSP* g_pWatchBSP; @@ -263,15 +265,15 @@ static void saxStartElement( message_info_t *data, const xmlChar *name, const xm if ( !attrs[0] || !attrs[1] || ( strcmp( reinterpret_cast( attrs[0] ), "version" ) != 0 ) ) { message_flush( data ); globalErrorStream() << "No stream version given in the feedback stream, this is an old q3map version.\n" - "Please turn off monitored compiling if you still wish to use this q3map executable\n"; + "Please turn off monitored compiling if you still wish to use this q3map executable\n"; abortStream( data ); return; } else if ( strcmp( reinterpret_cast( attrs[1] ), Q3MAP_STREAM_VERSION ) != 0 ) { message_flush( data ); globalErrorStream() << - "This version of Radiant reads version " Q3MAP_STREAM_VERSION " debug streams, I got an incoming connection with version " << reinterpret_cast( attrs[1] ) << "\n" - "Please make sure your versions of Radiant and q3map are matching.\n"; + "This version of Radiant reads version " Q3MAP_STREAM_VERSION " debug streams, I got an incoming connection with version " << reinterpret_cast( attrs[1] ) << "\n" + "Please make sure your versions of Radiant and q3map are matching.\n"; abortStream( data ); return; } @@ -361,29 +363,29 @@ static void saxEndElement( message_info_t *data, const xmlChar *name ){ class MessageOutputStream : public TextOutputStream { -message_info_t* m_data; + message_info_t* m_data; public: -MessageOutputStream( message_info_t* data ) : m_data( data ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - if ( m_data->pGeometry != 0 ) { - m_data->pGeometry->saxCharacters( m_data, reinterpret_cast( buffer ), int(length) ); + MessageOutputStream( message_info_t* data ) : m_data( data ){ } - else - { - if ( m_data->ignore_depth == 0 ) { - // output the message using the level - message_print( m_data, buffer, length ); - // if this message has error level flag, we mark the depth to stop the compilation when we get out - // we don't set the msg level if we don't stop on leak - if ( m_data->msg_level == 3 ) { - m_data->stop_depth = m_data->recurse - 1; + std::size_t write( const char* buffer, std::size_t length ){ + if ( m_data->pGeometry != 0 ) { + m_data->pGeometry->saxCharacters( m_data, reinterpret_cast( buffer ), int(length) ); + } + else + { + if ( m_data->ignore_depth == 0 ) { + // output the message using the level + message_print( m_data, buffer, length ); + // if this message has error level flag, we mark the depth to stop the compilation when we get out + // we don't set the msg level if we don't stop on leak + if ( m_data->msg_level == 3 ) { + m_data->stop_depth = m_data->recurse - 1; + } } } - } - return length; -} + return length; + } }; template @@ -526,7 +528,7 @@ void CWatchBSP::DoEBeginStep(){ if ( !m_bBSPPlugin ) { globalOutputStream() << "=== running build command ===\n" - << static_cast( g_ptr_array_index( m_pCmd, m_iCurrentStep ) ) << "\n"; + << static_cast( g_ptr_array_index( m_pCmd, m_iCurrentStep ) ) << "\n"; if ( !Q_Exec( NULL, (char *)g_ptr_array_index( m_pCmd, m_iCurrentStep ), NULL, true, false ) ) { StringOutputStream msg( 256 ); @@ -563,20 +565,20 @@ void CWatchBSP::DoEBeginStep(){ class RunEngineConfiguration { public: -const char* executable; -const char* mp_executable; -bool do_sp_mp; + const char* executable; + const char* mp_executable; + bool do_sp_mp; -RunEngineConfiguration() : - executable( g_pGameDescription->getRequiredKeyValue( ENGINE_ATTRIBUTE ) ), - mp_executable( g_pGameDescription->getKeyValue( MP_ENGINE_ATTRIBUTE ) ){ - do_sp_mp = !string_empty( mp_executable ); -} + RunEngineConfiguration() : + executable( g_pGameDescription->getRequiredKeyValue( ENGINE_ATTRIBUTE ) ), + mp_executable( g_pGameDescription->getKeyValue( MP_ENGINE_ATTRIBUTE ) ){ + do_sp_mp = !string_empty( mp_executable ); + } }; inline void GlobalGameDescription_string_write_mapparameter( StringOutputStream& string, const char* mapname ){ if ( g_pGameDescription->mGameType == "q2" - || g_pGameDescription->mGameType == "heretic2" ) { + || g_pGameDescription->mGameType == "heretic2" ) { string << ". +exec radiant.cfg +map " << mapname; } else @@ -643,112 +645,112 @@ void CWatchBSP::RoutineProcessing(){ } break; case EWatching: - { + { #ifdef _DEBUG - // some debug checks - if ( !m_pInSocket ) { - globalErrorStream() << "ERROR: m_pInSocket == NULL in CWatchBSP::RoutineProcessing EWatching state\n"; - return; - } -#endif - - int ret = Net_Wait( m_pInSocket, 0, 0 ); - if ( ret == -1 ) { - globalErrorStream() << "SOCKET_ERROR in CWatchBSP::RoutineProcessing\n"; - globalErrorStream() << "Terminating the connection.\n"; - EndMonitoringLoop(); - return; - } - - if ( ret == 1 ) { - // the socket has been identified, there's something (message or disconnection) - // see if there's anything in input - ret = Net_Receive( m_pInSocket, &msg ); - if ( ret > 0 ) { - // unsigned int size = msg.size; //++timo just a check - strcpy( m_xmlBuf, NMSG_ReadString( &msg ) ); - if ( m_bNeedCtxtInit ) { - m_xmlParserCtxt = NULL; - m_xmlParserCtxt = xmlCreatePushParserCtxt( &saxParser, &m_message_info, m_xmlBuf, static_cast( strlen( m_xmlBuf ) ), NULL ); - - if ( m_xmlParserCtxt == NULL ) { - globalErrorStream() << "Failed to create the XML parser (incoming stream began with: " << m_xmlBuf << ")\n"; - EndMonitoringLoop(); - } - m_bNeedCtxtInit = false; - } - else - { - xmlParseChunk( m_xmlParserCtxt, m_xmlBuf, static_cast( strlen( m_xmlBuf ) ), 0 ); - } + // some debug checks + if ( !m_pInSocket ) { + globalErrorStream() << "ERROR: m_pInSocket == NULL in CWatchBSP::RoutineProcessing EWatching state\n"; + return; } - else - { - message_flush( &m_message_info ); - // error or connection closed/reset - // NOTE: if we get an error down the XML stream we don't reach here - Net_Disconnect( m_pInSocket ); - m_pInSocket = NULL; - globalOutputStream() << "Connection closed.\n"; -#if 0 - if ( m_bBSPPlugin ) { - EndMonitoringLoop(); - // let the BSP plugin know that the job is done - g_BSPFrontendTable.m_pfnEndListen( 0 ); - return; - } #endif - // move to next step or finish - m_iCurrentStep++; - if ( m_iCurrentStep < m_pCmd->len ) { - DoEBeginStep(); + + int ret = Net_Wait( m_pInSocket, 0, 0 ); + if ( ret == -1 ) { + globalErrorStream() << "SOCKET_ERROR in CWatchBSP::RoutineProcessing\n"; + globalErrorStream() << "Terminating the connection.\n"; + EndMonitoringLoop(); + return; + } + + if ( ret == 1 ) { + // the socket has been identified, there's something (message or disconnection) + // see if there's anything in input + ret = Net_Receive( m_pInSocket, &msg ); + if ( ret > 0 ) { + // unsigned int size = msg.size; //++timo just a check + strcpy( m_xmlBuf, NMSG_ReadString( &msg ) ); + if ( m_bNeedCtxtInit ) { + m_xmlParserCtxt = NULL; + m_xmlParserCtxt = xmlCreatePushParserCtxt( &saxParser, &m_message_info, m_xmlBuf, static_cast( strlen( m_xmlBuf ) ), NULL ); + + if ( m_xmlParserCtxt == NULL ) { + globalErrorStream() << "Failed to create the XML parser (incoming stream began with: " << m_xmlBuf << ")\n"; + EndMonitoringLoop(); + } + m_bNeedCtxtInit = false; + } + else + { + xmlParseChunk( m_xmlParserCtxt, m_xmlBuf, static_cast( strlen( m_xmlBuf ) ), 0 ); + } } else { - // launch the engine .. OMG - if ( g_WatchBSP_RunQuake ) { - globalOutputStream() << "Running engine...\n"; - StringOutputStream cmd( 256 ); - // build the command line - cmd << EnginePath_get(); - // this is game dependant + message_flush( &m_message_info ); + // error or connection closed/reset + // NOTE: if we get an error down the XML stream we don't reach here + Net_Disconnect( m_pInSocket ); + m_pInSocket = NULL; + globalOutputStream() << "Connection closed.\n"; +#if 0 + if ( m_bBSPPlugin ) { + EndMonitoringLoop(); + // let the BSP plugin know that the job is done + g_BSPFrontendTable.m_pfnEndListen( 0 ); + return; + } +#endif + // move to next step or finish + m_iCurrentStep++; + if ( m_iCurrentStep < m_pCmd->len ) { + DoEBeginStep(); + } + else + { + // launch the engine .. OMG + if ( g_WatchBSP_RunQuake ) { + globalOutputStream() << "Running engine...\n"; + StringOutputStream cmd( 256 ); + // build the command line + cmd << EnginePath_get(); + // this is game dependant - RunEngineConfiguration engineConfig; + RunEngineConfiguration engineConfig; - if ( engineConfig.do_sp_mp ) { - if ( string_equal( gamemode_get(), "mp" ) ) { - cmd << engineConfig.mp_executable; + if ( engineConfig.do_sp_mp ) { + if ( string_equal( gamemode_get(), "mp" ) ) { + cmd << engineConfig.mp_executable; + } + else + { + cmd << engineConfig.executable; + } } else { cmd << engineConfig.executable; } + + StringOutputStream cmdline; + + GlobalGameDescription_string_write_mapparameter( cmdline, m_sBSPName ); + + globalOutputStream() << cmd.c_str() << " " << cmdline.c_str() << "\n"; + + // execute now + if ( !Q_Exec( cmd.c_str(), (char *)cmdline.c_str(), EnginePath_get(), false, false ) ) { + StringOutputStream msg; + msg << "Failed to execute the following command: " << cmd.c_str() << cmdline.c_str(); + globalOutputStream() << msg.c_str(); + gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); + } } - else - { - cmd << engineConfig.executable; - } - - StringOutputStream cmdline; - - GlobalGameDescription_string_write_mapparameter( cmdline, m_sBSPName ); - - globalOutputStream() << cmd.c_str() << " " << cmdline.c_str() << "\n"; - - // execute now - if ( !Q_Exec( cmd.c_str(), (char *)cmdline.c_str(), EnginePath_get(), false, false ) ) { - StringOutputStream msg; - msg << "Failed to execute the following command: " << cmd.c_str() << cmdline.c_str(); - globalOutputStream() << msg.c_str(); - gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); - } + EndMonitoringLoop(); } - EndMonitoringLoop(); } } } - } - break; + break; default: break; } diff --git a/radiant/winding.cpp b/radiant/winding.cpp index 4ae5259d..566ea5c6 100644 --- a/radiant/winding.cpp +++ b/radiant/winding.cpp @@ -110,8 +110,8 @@ void windingTestInfinity(){ if( i == winding.size() ){ ++windingTestInfinity_OK; } - fail: - ; +fail: + ; } globalWarningStream() << windingTestInfinity_badNormal << " windingTestInfinity_badNormal\n"; @@ -189,7 +189,7 @@ void Winding_createInfinite( FixedWinding& winding, const Plane3& plane, double } const DoubleVector3 vup0 = ( maxi == 2 )? DoubleVector3( 0, -normal[2], normal[1] ) - : DoubleVector3( -normal[1], normal[0], 0 ); + : DoubleVector3( -normal[1], normal[0], 0 ); const DoubleVector3 vright0 = vector3_cross( vup0, normal ); const DoubleVector3 org = normal * plane.dist(); diff --git a/radiant/winding.h b/radiant/winding.h index 8599e7e9..4c8db13c 100644 --- a/radiant/winding.h +++ b/radiant/winding.h @@ -46,12 +46,12 @@ inline bool projectionaxis_better( float axis, float other ){ /// \brief Texture axis precedence: Z > X > Y inline ProjectionAxis projectionaxis_for_normal( const Vector3& normal ){ return ( projectionaxis_better( normal[eProjectionAxisY], normal[eProjectionAxisX] ) ) - ? ( projectionaxis_better( normal[eProjectionAxisY], normal[eProjectionAxisZ] ) ) - ? eProjectionAxisY - : eProjectionAxisZ - : ( projectionaxis_better( normal[eProjectionAxisX], normal[eProjectionAxisZ] ) ) - ? eProjectionAxisX - : eProjectionAxisZ; + ? ( projectionaxis_better( normal[eProjectionAxisY], normal[eProjectionAxisZ] ) ) + ? eProjectionAxisY + : eProjectionAxisZ + : ( projectionaxis_better( normal[eProjectionAxisX], normal[eProjectionAxisZ] ) ) + ? eProjectionAxisX + : eProjectionAxisZ; } @@ -86,11 +86,11 @@ const std::size_t c_brush_maxFaces = 1024; class WindingVertex { public: -Vector3 vertex; -Vector2 texcoord; -Vector3 tangent; -Vector3 bitangent; -std::size_t adjacent; + Vector3 vertex; + Vector2 texcoord; + Vector3 tangent; + Vector3 bitangent; + std::size_t adjacent; }; @@ -152,13 +152,13 @@ struct Winding class FixedWindingVertex { public: -DoubleVector3 vertex; -DoubleRay edge; -std::size_t adjacent; + DoubleVector3 vertex; + DoubleRay edge; + std::size_t adjacent; -FixedWindingVertex( const DoubleVector3& vertex_, const DoubleRay& edge_, std::size_t adjacent_ ) - : vertex( vertex_ ), edge( edge_ ), adjacent( adjacent_ ){ -} + FixedWindingVertex( const DoubleVector3& vertex_, const DoubleRay& edge_, std::size_t adjacent_ ) + : vertex( vertex_ ), edge( edge_ ), adjacent( adjacent_ ){ + } }; struct FixedWinding diff --git a/radiant/xmlstuff.h b/radiant/xmlstuff.h index a30303f4..6f7414fc 100644 --- a/radiant/xmlstuff.h +++ b/radiant/xmlstuff.h @@ -68,19 +68,19 @@ class IGL2DWindow; class ISAXHandler { public: -virtual void Release(){ -} -virtual void saxStartElement( message_info_t* ctx, const xmlChar* name, const xmlChar** attrs ) = 0; -virtual void saxEndElement( message_info_t* ctx, const xmlChar* name ) = 0; -virtual void saxCharacters( message_info_t* ctx, const xmlChar* ch, int len ) = 0; -virtual const char* getName(){ - return NULL; -} -virtual IGL2DWindow* Highlight(){ - return 0; -} -virtual void DropHighlight(){ -} + virtual void Release(){ + } + virtual void saxStartElement( message_info_t* ctx, const xmlChar* name, const xmlChar** attrs ) = 0; + virtual void saxEndElement( message_info_t* ctx, const xmlChar* name ) = 0; + virtual void saxCharacters( message_info_t* ctx, const xmlChar* ch, int len ) = 0; + virtual const char* getName(){ + return NULL; + } + virtual IGL2DWindow* Highlight(){ + return 0; + } + virtual void DropHighlight(){ + } }; #endif diff --git a/radiant/xywindow.cpp b/radiant/xywindow.cpp index 0d4e2044..26dea4d4 100644 --- a/radiant/xywindow.cpp +++ b/radiant/xywindow.cpp @@ -242,8 +242,8 @@ inline unsigned int buttons_for_state( guint state ){ void XYWnd::SetScale( float f ){ const float max_scale = 64.f; const float min_scale = std::min( Width(), Height() ) - / ( ( 1.1f + ( 1.f - GetMaxGridCoord() / g_MaxWorldCoord ) ) // adaptive min scale factor: from 2.0375 with 4096 grid to 1.1 with 64*1024 - * 2.f * GetMaxGridCoord() ); + / ( ( 1.1f + ( 1.f - GetMaxGridCoord() / g_MaxWorldCoord ) ) // adaptive min scale factor: from 2.0375 with 4096 grid to 1.1 with 64*1024 + * 2.f * GetMaxGridCoord() ); f = std::min( max_scale, std::max( min_scale, f ) ); if( !float_equal_epsilon( m_fScale, f, float_mid( m_fScale, f ) * 1e-5f ) ){ m_fScale = f; @@ -289,7 +289,7 @@ void XYWnd::FocusOnBounds( const AABB& bounds ){ SetOrigin( bounds.origin ); NDIM1NDIM2( m_viewType ) SetScale( std::min( Width() / ( 3.f * std::max( 128.f, bounds.extents[ nDim1 ] ) ), - Height() / ( 3.f * std::max( 128.f, bounds.extents[ nDim2 ] ) ) ) ); + Height() / ( 3.f * std::max( 128.f, bounds.extents[ nDim2 ] ) ) ) ); } @@ -526,10 +526,11 @@ void XYWnd::overlayDraw(){ glLoadIdentity(); // four view mode doesn't colorize - glColor3fv( vector3_to_array( ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit )? g_xywindow_globals.color_viewname - : m_viewType == YZ? g_xywindow_globals.AxisColorX - : m_viewType == XZ? g_xywindow_globals.AxisColorY - : g_xywindow_globals.AxisColorZ ) ); + glColor3fv( vector3_to_array( ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit )? + g_xywindow_globals.color_viewname + : m_viewType == YZ? g_xywindow_globals.AxisColorX + : m_viewType == XZ? g_xywindow_globals.AxisColorY + : g_xywindow_globals.AxisColorZ ) ); glBegin( GL_LINE_LOOP ); glVertex2f( 0.5, 0.5 ); glVertex2f( m_nWidth - 0.5, 0.5 ); @@ -980,67 +981,67 @@ void EntityClassMenu_addItem( GtkMenu* menu, const char* name ){ class EntityClassMenuInserter : public EntityClassVisitor { -typedef std::pair MenuPair; -typedef std::vector MenuStack; -MenuStack m_stack; -CopiedString m_previous; + typedef std::pair MenuPair; + typedef std::vector MenuStack; + MenuStack m_stack; + CopiedString m_previous; public: -EntityClassMenuInserter( GtkMenu* menu ){ - m_stack.reserve( 2 ); - m_stack.push_back( MenuPair( menu, "" ) ); -} -~EntityClassMenuInserter(){ - if ( !string_empty( m_previous.c_str() ) ) { - addItem( m_previous.c_str(), "" ); + EntityClassMenuInserter( GtkMenu* menu ){ + m_stack.reserve( 2 ); + m_stack.push_back( MenuPair( menu, "" ) ); } -} -void visit( EntityClass* e ){ - ASSERT_MESSAGE( !string_empty( e->name() ), "entity-class has no name" ); - if ( !string_empty( m_previous.c_str() ) ) { - addItem( m_previous.c_str(), e->name() ); - } - m_previous = e->name(); -} -void pushMenu( const CopiedString& name ){ - GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name.c_str() ) ); - gtk_widget_show( GTK_WIDGET( item ) ); - container_add_widget( GTK_CONTAINER( m_stack.back().first ), GTK_WIDGET( item ) ); - - GtkMenu* submenu = GTK_MENU( gtk_menu_new() ); - gtk_menu_item_set_submenu( item, GTK_WIDGET( submenu ) ); - - m_stack.push_back( MenuPair( submenu, name ) ); -} -void popMenu(){ - m_stack.pop_back(); -} -void addItem( const char* name, const char* next ){ - const char* underscore = strchr( name, '_' ); - - if ( underscore != 0 && underscore != name ) { - bool nextEqual = string_equal_n( name, next, ( underscore + 1 ) - name ); - const char* parent = m_stack.back().second.c_str(); - - if ( !string_empty( parent ) - && string_length( parent ) == std::size_t( underscore - name ) - && string_equal_n( name, parent, underscore - name ) ) { // this is a child + ~EntityClassMenuInserter(){ + if ( !string_empty( m_previous.c_str() ) ) { + addItem( m_previous.c_str(), "" ); } - else if ( nextEqual ) { - if ( m_stack.size() == 2 ) { + } + void visit( EntityClass* e ){ + ASSERT_MESSAGE( !string_empty( e->name() ), "entity-class has no name" ); + if ( !string_empty( m_previous.c_str() ) ) { + addItem( m_previous.c_str(), e->name() ); + } + m_previous = e->name(); + } + void pushMenu( const CopiedString& name ){ + GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name.c_str() ) ); + gtk_widget_show( GTK_WIDGET( item ) ); + container_add_widget( GTK_CONTAINER( m_stack.back().first ), GTK_WIDGET( item ) ); + + GtkMenu* submenu = GTK_MENU( gtk_menu_new() ); + gtk_menu_item_set_submenu( item, GTK_WIDGET( submenu ) ); + + m_stack.push_back( MenuPair( submenu, name ) ); + } + void popMenu(){ + m_stack.pop_back(); + } + void addItem( const char* name, const char* next ){ + const char* underscore = strchr( name, '_' ); + + if ( underscore != 0 && underscore != name ) { + bool nextEqual = string_equal_n( name, next, ( underscore + 1 ) - name ); + const char* parent = m_stack.back().second.c_str(); + + if ( !string_empty( parent ) + && string_length( parent ) == std::size_t( underscore - name ) + && string_equal_n( name, parent, underscore - name ) ) { // this is a child + } + else if ( nextEqual ) { + if ( m_stack.size() == 2 ) { + popMenu(); + } + pushMenu( CopiedString( StringRange( name, underscore ) ) ); + } + else if ( m_stack.size() == 2 ) { popMenu(); } - pushMenu( CopiedString( StringRange( name, underscore ) ) ); } else if ( m_stack.size() == 2 ) { popMenu(); } - } - else if ( m_stack.size() == 2 ) { - popMenu(); - } - EntityClassMenu_addItem( m_stack.back().first, name ); -} + EntityClassMenu_addItem( m_stack.back().first, name ); + } }; void XYWnd::OnContextMenu(){ @@ -1244,8 +1245,8 @@ void XYWnd::XY_MouseMoved( int x, int y, unsigned int buttons ){ { StringOutputStream status( 64 ); status << "x:: " << FloatFormat( m_mousePosition[0], 6, 1 ) - << " y:: " << FloatFormat( m_mousePosition[1], 6, 1 ) - << " z:: " << FloatFormat( m_mousePosition[2], 6, 1 ); + << " y:: " << FloatFormat( m_mousePosition[1], 6, 1 ) + << " z:: " << FloatFormat( m_mousePosition[2], 6, 1 ); g_pParentWnd->SetStatusText( c_status_position, status.c_str() ); } @@ -1378,7 +1379,7 @@ void BackgroundImage::set( const VIEWTYPE viewtype ){ NDIM1NDIM2( viewtype ) if( !( bounds.extents[nDim1] > 0 && bounds.extents[nDim2] > 0 ) ){ gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), "Select some objects to get the bounding box for image.\n", - "No selection", eMB_OK, eMB_ICONERROR ); + "No selection", eMB_OK, eMB_ICONERROR ); } else{ free_tex(); @@ -1748,10 +1749,10 @@ void XYWnd::DrawCameraIcon( const Vector3& origin, const Vector3& angles ){ const float x = origin[nDim1]; const float y = origin[nDim2]; const double a = ( m_viewType == XY )? - degrees_to_radians( angles[CAMERA_YAW] ) - : ( m_viewType == YZ )? - degrees_to_radians( ( angles[CAMERA_YAW] > 180 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] ) - : degrees_to_radians( ( angles[CAMERA_YAW] < 270 && angles[CAMERA_YAW] > 90 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] ); + degrees_to_radians( angles[CAMERA_YAW] ) + : ( m_viewType == YZ )? + degrees_to_radians( ( angles[CAMERA_YAW] > 180 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] ) + : degrees_to_radians( ( angles[CAMERA_YAW] < 270 && angles[CAMERA_YAW] > 90 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] ); glColor3f( 0.0, 0.0, 1.0 ); glBegin( GL_LINE_STRIP ); @@ -1835,61 +1836,61 @@ void XYWnd::PaintSizeInfo( const int nDim1, const int nDim2 ){ class XYRenderer : public Renderer { -struct state_type -{ - state_type() : - m_highlight( 0 ), - m_state( 0 ){ - } - unsigned int m_highlight; - Shader* m_state; -}; -public: -XYRenderer( RenderStateFlags globalstate, Shader* selected ) : - m_globalstate( globalstate ), - m_state_selected( selected ){ - ASSERT_NOTNULL( selected ); - m_state_stack.push_back( state_type() ); -} - -void SetState( Shader* state, EStyle style ){ - ASSERT_NOTNULL( state ); - if ( style == eWireframeOnly ) { - m_state_stack.back().m_state = state; - } -} -EStyle getStyle() const { - return eWireframeOnly; -} -void PushState(){ - m_state_stack.push_back( m_state_stack.back() ); -} -void PopState(){ - ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); - m_state_stack.pop_back(); -} -void Highlight( EHighlightMode mode, bool bEnable = true ){ - ( bEnable ) - ? m_state_stack.back().m_highlight |= mode - : m_state_stack.back().m_highlight &= ~mode; -} -void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){ - if ( m_state_stack.back().m_highlight & ePrimitive ) { - m_state_selected->addRenderable( renderable, localToWorld ); - } - else + struct state_type { - m_state_stack.back().m_state->addRenderable( renderable, localToWorld ); + state_type() : + m_highlight( 0 ), + m_state( 0 ){ + } + unsigned int m_highlight; + Shader* m_state; + }; +public: + XYRenderer( RenderStateFlags globalstate, Shader* selected ) : + m_globalstate( globalstate ), + m_state_selected( selected ){ + ASSERT_NOTNULL( selected ); + m_state_stack.push_back( state_type() ); } -} -void render( const Matrix4& modelview, const Matrix4& projection ){ - GlobalShaderCache().render( m_globalstate, modelview, projection ); -} + void SetState( Shader* state, EStyle style ){ + ASSERT_NOTNULL( state ); + if ( style == eWireframeOnly ) { + m_state_stack.back().m_state = state; + } + } + EStyle getStyle() const { + return eWireframeOnly; + } + void PushState(){ + m_state_stack.push_back( m_state_stack.back() ); + } + void PopState(){ + ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" ); + m_state_stack.pop_back(); + } + void Highlight( EHighlightMode mode, bool bEnable = true ){ + ( bEnable ) + ? m_state_stack.back().m_highlight |= mode + : m_state_stack.back().m_highlight &= ~mode; + } + void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){ + if ( m_state_stack.back().m_highlight & ePrimitive ) { + m_state_selected->addRenderable( renderable, localToWorld ); + } + else + { + m_state_stack.back().m_state->addRenderable( renderable, localToWorld ); + } + } + + void render( const Matrix4& modelview, const Matrix4& projection ){ + GlobalShaderCache().render( m_globalstate, modelview, projection ); + } private: -std::vector m_state_stack; -RenderStateFlags m_globalstate; -Shader* m_state_selected; + std::vector m_state_stack; + RenderStateFlags m_globalstate; + Shader* m_state_selected; }; void XYWnd::updateProjection(){ @@ -1901,17 +1902,9 @@ void XYWnd::updateProjection(){ m_projection[13] = 0.0f; m_projection[14] = -1.0f; - m_projection[1] = - m_projection[2] = - m_projection[3] = - - m_projection[4] = - m_projection[6] = - m_projection[7] = - - m_projection[8] = - m_projection[9] = - m_projection[11] = 0.0f; + m_projection[1] = m_projection[2] = m_projection[3] = + m_projection[4] = m_projection[6] = m_projection[7] = + m_projection[8] = m_projection[9] = m_projection[11] = 0.0f; m_projection[15] = 1.0f; @@ -2003,8 +1996,8 @@ void XYWnd::XY_Draw(){ // glViewport( 0, 0, m_nWidth, m_nHeight ); glClearColor( g_xywindow_globals.color_gridback[0], - g_xywindow_globals.color_gridback[1], - g_xywindow_globals.color_gridback[2],0 ); + g_xywindow_globals.color_gridback[1], + g_xywindow_globals.color_gridback[2], 0 ); glClear( GL_COLOR_BUFFER_BIT ); @@ -2153,8 +2146,8 @@ void XYWnd::OnEntityCreate( const char* item ){ inline AABB GetCenterBbox(){ return ( GlobalSelectionSystem().countSelected() != 0 )? - GlobalSelectionSystem().getBoundsSelected() : - AABB( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Vector3( 128.f, 128.f, 128.f ) ); + GlobalSelectionSystem().getBoundsSelected() : + AABB( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Vector3( 128.f, 128.f, 128.f ) ); } void XYWnd_Centralize( XYWnd* xywnd ){ @@ -2241,22 +2234,22 @@ void XZ_Front_Shown_Construct( GtkWindow* parent ){ class EntityClassMenu : public ModuleObserver { -std::size_t m_unrealised; + std::size_t m_unrealised; public: -EntityClassMenu() : m_unrealised( 1 ){ -} -void realise(){ - if ( --m_unrealised == 0 ) { + EntityClassMenu() : m_unrealised( 1 ){ } -} -void unrealise(){ - if ( ++m_unrealised == 1 ) { - if ( XYWnd::m_mnuDrop != 0 ) { - gtk_widget_destroy( GTK_WIDGET( XYWnd::m_mnuDrop ) ); - XYWnd::m_mnuDrop = 0; + void realise(){ + if ( --m_unrealised == 0 ) { + } + } + void unrealise(){ + if ( ++m_unrealised == 1 ) { + if ( XYWnd::m_mnuDrop != 0 ) { + gtk_widget_destroy( GTK_WIDGET( XYWnd::m_mnuDrop ) ); + XYWnd::m_mnuDrop = 0; + } } } -} }; EntityClassMenu g_EntityClassMenu; @@ -2463,11 +2456,11 @@ void Orthographic_constructPreferences( PreferencesPage& page ){ const char* samples[] = { "0", "2", "4", "8", "16", "32" }; page.appendCombo( - "MSAA", - STRING_ARRAY_RANGE( samples ), - IntImportCallback( MSAAImportCaller() ), - IntExportCallback( MSAAExportCaller() ) - ); + "MSAA", + STRING_ARRAY_RANGE( samples ), + IntImportCallback( MSAAImportCaller() ), + IntExportCallback( MSAAExportCaller() ) + ); } } void Orthographic_constructPage( PreferenceGroup& group ){ diff --git a/radiant/xywindow.h b/radiant/xywindow.h index ecd443ba..4422c074 100644 --- a/radiant/xywindow.h +++ b/radiant/xywindow.h @@ -82,179 +82,179 @@ class FBO; class XYWnd { -GtkWidget* m_gl_widget; -guint m_sizeHandler; -guint m_exposeHandler; + GtkWidget* m_gl_widget; + guint m_sizeHandler; + guint m_exposeHandler; -DeferredDraw m_deferredDraw; -IdleDraw m_deferredOverlayDraw; -DeferredMotion m_deferred_motion; + DeferredDraw m_deferredDraw; + IdleDraw m_deferredOverlayDraw; + DeferredMotion m_deferred_motion; -FBO* m_fbo; + FBO* m_fbo; public: -FBO* fbo_get(); + FBO* fbo_get(); -GtkWindow* m_parent; -XYWnd(); -~XYWnd(); + GtkWindow* m_parent; + XYWnd(); + ~XYWnd(); -void queueDraw(){ - m_deferredDraw.draw(); -} -GtkWidget* GetWidget(){ - return m_gl_widget; -} + void queueDraw(){ + m_deferredDraw.draw(); + } + GtkWidget* GetWidget(){ + return m_gl_widget; + } -SelectionSystemWindowObserver* m_window_observer; -XORRectangle m_XORRectangle; -WindowPositionTracker m_positionTracker; + SelectionSystemWindowObserver* m_window_observer; + XORRectangle m_XORRectangle; + WindowPositionTracker m_positionTracker; -static void captureStates(); -static void releaseStates(); -static void recaptureStates(){ - releaseStates(); - captureStates(); -} + static void captureStates(); + static void releaseStates(); + static void recaptureStates(){ + releaseStates(); + captureStates(); + } -const Vector3& GetOrigin() const; -void SetOrigin( const Vector3& origin ); -void Scroll( int x, int y ); + const Vector3& GetOrigin() const; + void SetOrigin( const Vector3& origin ); + void Scroll( int x, int y ); -void XY_Draw(); -bool overlayStart(); -void overlayFinish(); -void overlayDraw(); -void overlayUpdate(); -void DrawCameraIcon( const Vector3& origin, const Vector3& angles ); -void XY_DrawBlockGrid(); -void XY_DrawAxis(); -void XY_DrawGrid(); + void XY_Draw(); + bool overlayStart(); + void overlayFinish(); + void overlayDraw(); + void overlayUpdate(); + void DrawCameraIcon( const Vector3& origin, const Vector3& angles ); + void XY_DrawBlockGrid(); + void XY_DrawAxis(); + void XY_DrawGrid(); -void XY_MouseUp( int x, int y, unsigned int buttons ); -void XY_MouseDown( int x, int y, unsigned int buttons ); -void XY_MouseMoved( int x, int y, unsigned int buttons ); + void XY_MouseUp( int x, int y, unsigned int buttons ); + void XY_MouseDown( int x, int y, unsigned int buttons ); + void XY_MouseMoved( int x, int y, unsigned int buttons ); -void NewBrushDrag_Begin( int x, int y ); -void NewBrushDrag( int x, int y, bool square, bool cube ); -void NewBrushDrag_End( int x, int y ); + void NewBrushDrag_Begin( int x, int y ); + void NewBrushDrag( int x, int y, bool square, bool cube ); + void NewBrushDrag_End( int x, int y ); -Vector3 XY_ToPoint( int x, int y, bool snap = false ) const; + Vector3 XY_ToPoint( int x, int y, bool snap = false ) const; -void Move_Begin(); -void Move_End(); -bool m_move_started; -guint m_move_focusOut; + void Move_Begin(); + void Move_End(); + bool m_move_started; + guint m_move_focusOut; -void Zoom_Begin( int x, int y ); -void Zoom_End(); -bool m_zoom_started; -guint m_zoom_focusOut; + void Zoom_Begin( int x, int y ); + void Zoom_End(); + bool m_zoom_started; + guint m_zoom_focusOut; -void ZoomIn(); -void ZoomOut(); -void ZoomInWithMouse( int x, int y ); -void ZoomOutWithMouse( int x, int y ); -void ZoomCompensateOrigin( int x, int y, float old_scale ); -void FocusOnBounds( const AABB& bounds ); + void ZoomIn(); + void ZoomOut(); + void ZoomInWithMouse( int x, int y ); + void ZoomOutWithMouse( int x, int y ); + void ZoomCompensateOrigin( int x, int y, float old_scale ); + void FocusOnBounds( const AABB& bounds ); -void SetActive( bool b ){ - m_bActive = b; - overlayUpdate(); -}; -bool Active(){ - return m_bActive; -}; + void SetActive( bool b ){ + m_bActive = b; + overlayUpdate(); + }; + bool Active(){ + return m_bActive; + }; -void SetCustomPivotOrigin( int x, int y ) const; + void SetCustomPivotOrigin( int x, int y ) const; -void SetViewType( VIEWTYPE n ); -bool m_bActive; + void SetViewType( VIEWTYPE n ); + bool m_bActive; -static GtkMenu* m_mnuDrop; + static GtkMenu* m_mnuDrop; -int m_chasemouse_current_x, m_chasemouse_current_y; -int m_chasemouse_delta_x, m_chasemouse_delta_y; + int m_chasemouse_current_x, m_chasemouse_current_y; + int m_chasemouse_delta_x, m_chasemouse_delta_y; -guint m_chasemouse_handler; -void ChaseMouse(); -bool chaseMouseMotion( int x, int y ); + guint m_chasemouse_handler; + void ChaseMouse(); + bool chaseMouseMotion( int x, int y ); -void updateModelview(); -void updateProjection(); -Matrix4 m_projection; -Matrix4 m_modelview; + void updateModelview(); + void updateProjection(); + Matrix4 m_projection; + Matrix4 m_modelview; -int m_nWidth; -int m_nHeight; + int m_nWidth; + int m_nHeight; -void setBackgroundImage(){ - m_backgroundImage.set( m_viewType ); -} + void setBackgroundImage(){ + m_backgroundImage.set( m_viewType ); + } private: -BackgroundImage m_backgroundImage; + BackgroundImage m_backgroundImage; -float m_fScale; -Vector3 m_vOrigin; + float m_fScale; + Vector3 m_vOrigin; -View m_view; -static Shader* m_state_selected; + View m_view; + static Shader* m_state_selected; -unsigned int m_buttonstate; + unsigned int m_buttonstate; -int m_nNewBrushPressx; -int m_nNewBrushPressy; -scene::Node* m_NewBrushDrag; -bool m_bNewBrushDrag; + int m_nNewBrushPressx; + int m_nNewBrushPressy; + scene::Node* m_NewBrushDrag; + bool m_bNewBrushDrag; -Vector3 m_mousePosition; + Vector3 m_mousePosition; -VIEWTYPE m_viewType; + VIEWTYPE m_viewType; -void PaintSizeInfo( int nDim1, int nDim2 ); + void PaintSizeInfo( int nDim1, int nDim2 ); -int m_entityCreate_x, m_entityCreate_y; -bool m_entityCreate; + int m_entityCreate_x, m_entityCreate_y; + bool m_entityCreate; -Timer m_render_time; + Timer m_render_time; public: -void OnContextMenu(); -void ButtonState_onMouseDown( unsigned int buttons ){ - //m_buttonstate |= buttons; - m_buttonstate = buttons; -} -void ButtonState_onMouseUp( unsigned int buttons ){ - //m_buttonstate &= ~buttons; - m_buttonstate = 0; -} -unsigned int getButtonState() const { - return m_buttonstate; -} -void EntityCreate_MouseDown( int x, int y ); -void EntityCreate_MouseMove( int x, int y ); -void EntityCreate_MouseUp( int x, int y ); + void OnContextMenu(); + void ButtonState_onMouseDown( unsigned int buttons ){ + //m_buttonstate |= buttons; + m_buttonstate = buttons; + } + void ButtonState_onMouseUp( unsigned int buttons ){ + //m_buttonstate &= ~buttons; + m_buttonstate = 0; + } + unsigned int getButtonState() const { + return m_buttonstate; + } + void EntityCreate_MouseDown( int x, int y ); + void EntityCreate_MouseMove( int x, int y ); + void EntityCreate_MouseUp( int x, int y ); -void OnEntityCreate( const char* item ); -VIEWTYPE GetViewType() const { - return m_viewType; -} -void SetScale( float f ); -float Scale() const { - return m_fScale; -} -int Width() const { - return m_nWidth; -} -int Height() const { - return m_nHeight; -} + void OnEntityCreate( const char* item ); + VIEWTYPE GetViewType() const { + return m_viewType; + } + void SetScale( float f ); + float Scale() const { + return m_fScale; + } + int Width() const { + return m_nWidth; + } + int Height() const { + return m_nHeight; + } -Signal0 onDestroyed; -Signal3 onMouseDown; -void mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ); -typedef Member3 MouseDownCaller; + Signal0 onDestroyed; + Signal3 onMouseDown; + void mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ); + typedef Member3 MouseDownCaller; }; inline void XYWnd_Update( XYWnd& xywnd ){ diff --git a/tools/quake3/common/bspfile.cpp b/tools/quake3/common/bspfile.cpp index 0ecb4f77..3aa4aac6 100644 --- a/tools/quake3/common/bspfile.cpp +++ b/tools/quake3/common/bspfile.cpp @@ -435,40 +435,40 @@ void PrintBSPFileSizes( void ) { } Sys_Printf( "%6i models %7i\n" - ,nummodels, (int)( nummodels * sizeof( dmodel_t ) ) ); + ,nummodels, (int)( nummodels * sizeof( dmodel_t ) ) ); Sys_Printf( "%6i shaders %7i\n" - ,numShaders, (int)( numShaders * sizeof( dshader_t ) ) ); + ,numShaders, (int)( numShaders * sizeof( dshader_t ) ) ); Sys_Printf( "%6i brushes %7i\n" - ,numbrushes, (int)( numbrushes * sizeof( dbrush_t ) ) ); + ,numbrushes, (int)( numbrushes * sizeof( dbrush_t ) ) ); Sys_Printf( "%6i brushsides %7i\n" - ,numbrushsides, (int)( numbrushsides * sizeof( dbrushside_t ) ) ); + ,numbrushsides, (int)( numbrushsides * sizeof( dbrushside_t ) ) ); Sys_Printf( "%6i fogs %7i\n" - ,numFogs, (int)( numFogs * sizeof( dfog_t ) ) ); + ,numFogs, (int)( numFogs * sizeof( dfog_t ) ) ); Sys_Printf( "%6i planes %7i\n" - ,numplanes, (int)( numplanes * sizeof( dplane_t ) ) ); + ,numplanes, (int)( numplanes * sizeof( dplane_t ) ) ); Sys_Printf( "%6i entdata %7i\n", num_entities, entdatasize ); Sys_Printf( "\n" ); Sys_Printf( "%6i nodes %7i\n" - ,numnodes, (int)( numnodes * sizeof( dnode_t ) ) ); + ,numnodes, (int)( numnodes * sizeof( dnode_t ) ) ); Sys_Printf( "%6i leafs %7i\n" - ,numleafs, (int)( numleafs * sizeof( dleaf_t ) ) ); + ,numleafs, (int)( numleafs * sizeof( dleaf_t ) ) ); Sys_Printf( "%6i leafsurfaces %7i\n" - ,numleafsurfaces, (int)( numleafsurfaces * sizeof( dleafsurfaces[0] ) ) ); + ,numleafsurfaces, (int)( numleafsurfaces * sizeof( dleafsurfaces[0] ) ) ); Sys_Printf( "%6i leafbrushes %7i\n" - ,numleafbrushes, (int)( numleafbrushes * sizeof( dleafbrushes[0] ) ) ); + ,numleafbrushes, (int)( numleafbrushes * sizeof( dleafbrushes[0] ) ) ); Sys_Printf( "%6i drawverts %7i\n" - ,numDrawVerts, (int)( numDrawVerts * sizeof( drawVerts[0] ) ) ); + ,numDrawVerts, (int)( numDrawVerts * sizeof( drawVerts[0] ) ) ); Sys_Printf( "%6i drawindexes %7i\n" - ,numDrawIndexes, (int)( numDrawIndexes * sizeof( drawIndexes[0] ) ) ); + ,numDrawIndexes, (int)( numDrawIndexes * sizeof( drawIndexes[0] ) ) ); Sys_Printf( "%6i drawsurfaces %7i\n" - ,numDrawSurfaces, (int)( numDrawSurfaces * sizeof( drawSurfaces[0] ) ) ); + ,numDrawSurfaces, (int)( numDrawSurfaces * sizeof( drawSurfaces[0] ) ) ); Sys_Printf( "%6i lightmaps %7i\n" - ,numLightBytes / ( LIGHTMAP_WIDTH * LIGHTMAP_HEIGHT * 3 ), numLightBytes ); + ,numLightBytes / ( LIGHTMAP_WIDTH * LIGHTMAP_HEIGHT * 3 ), numLightBytes ); Sys_Printf( " visibility %7i\n" - , numVisBytes ); + , numVisBytes ); } diff --git a/tools/quake3/common/cmdlib.cpp b/tools/quake3/common/cmdlib.cpp index e71dfe6b..c17d4722 100644 --- a/tools/quake3/common/cmdlib.cpp +++ b/tools/quake3/common/cmdlib.cpp @@ -105,7 +105,7 @@ void ExpandWildcards( int *argc, char ***argv ){ { path = ( *argv )[i]; if ( path[0] == '-' - || ( !strchr( path, '*' ) && !strchr( path, '?' ) ) ) { + || ( !strchr( path, '*' ) && !strchr( path, '?' ) ) ) { ex_argv[ex_argc++] = path; continue; } diff --git a/tools/quake3/common/imagelib.cpp b/tools/quake3/common/imagelib.cpp index 9d25cd12..ac38a3d3 100644 --- a/tools/quake3/common/imagelib.cpp +++ b/tools/quake3/common/imagelib.cpp @@ -226,7 +226,7 @@ void LoadLBM( const char *filename, byte **picture, byte **palette ){ if ( formtype != ILBMID && formtype != PBMID ) { Error( "Unrecognized form type: %c%c%c%c\n", formtype & 0xff - ,( formtype >> 8 ) & 0xff,( formtype >> 16 ) & 0xff,( formtype >> 24 ) & 0xff ); + ,( formtype >> 8 ) & 0xff,( formtype >> 16 ) & 0xff,( formtype >> 24 ) & 0xff ); } LBM_P += 4; @@ -271,7 +271,7 @@ void LoadLBM( const char *filename, byte **picture, byte **palette ){ { if ( bmhd.compression == cm_rle1 ) { body_p = LBMRLEDecompress( (byte *)body_p - , pic_p, bmhd.w ); + , pic_p, bmhd.w ); } else if ( bmhd.compression == cm_none ) { memcpy( pic_p,body_p,bmhd.w ); @@ -317,7 +317,7 @@ void LoadLBM( const char *filename, byte **picture, byte **palette ){ ============== */ void WriteLBMfile( const char *filename, byte *data, - int width, int height, byte *palette ){ + int width, int height, byte *palette ){ byte *lbm, *lbmptr; int *formlength, *bmhdlength, *cmaplength, *bodylength; int length; @@ -492,11 +492,11 @@ void LoadPCX( const char *filename, byte **pic, byte **palette, int *width, int pcx->palette_type = LittleShort( pcx->palette_type ); if ( pcx->manufacturer != 0x0a - || pcx->version != 5 - || pcx->encoding != 1 - || pcx->bits_per_pixel != 8 - || pcx->xmax >= 640 - || pcx->ymax >= 480 ) { + || pcx->version != 5 + || pcx->encoding != 1 + || pcx->bits_per_pixel != 8 + || pcx->xmax >= 640 + || pcx->ymax >= 480 ) { Error( "Bad pcx file %s", filename ); } @@ -562,7 +562,7 @@ void LoadPCX( const char *filename, byte **pic, byte **palette, int *width, int ============== */ void WritePCXfile( const char *filename, byte *data, - int width, int height, byte *palette ){ + int width, int height, byte *palette ){ int i, j, length; pcx_t *pcx; byte *pack; @@ -848,7 +848,7 @@ void Load256Image( const char *name, byte **pixels, byte **palette, int *width, ============== */ void Save256Image( const char *name, byte *pixels, byte *palette, - int width, int height ){ + int width, int height ){ const char *ext = path_get_extension( name ); if ( striEqual( ext, "lbm" ) ) { diff --git a/tools/quake3/common/imagelib.h b/tools/quake3/common/imagelib.h index 194ac5b1..e538b847 100644 --- a/tools/quake3/common/imagelib.h +++ b/tools/quake3/common/imagelib.h @@ -24,16 +24,16 @@ void LoadLBM( const char *filename, byte **picture, byte **palette ); void WriteLBMfile( const char *filename, byte *data, int width, int height - , byte *palette ); + , byte *palette ); void LoadPCX( const char *filename, byte **picture, byte **palette, int *width, int *height ); void WritePCXfile( const char *filename, byte *data, int width, int height - , byte *palette ); + , byte *palette ); // loads / saves either lbm or pcx, depending on extension void Load256Image( const char *name, byte **pixels, byte **palette, - int *width, int *height ); + int *width, int *height ); void Save256Image( const char *name, byte *pixels, byte *palette, - int width, int height ); + int width, int height ); void LoadTGA( const char *filename, byte **pixels, int *width, int *height ); diff --git a/tools/quake3/common/inout.cpp b/tools/quake3/common/inout.cpp index 4878d299..dbc57bc5 100644 --- a/tools/quake3/common/inout.cpp +++ b/tools/quake3/common/inout.cpp @@ -250,8 +250,8 @@ void set_console_colour_for_flag( int flag ){ if( curFlag != flag ){ curFlag = flag; SetConsoleTextAttribute( hConsole, flag == SYS_WRN ? FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY - : flag == SYS_ERR ? FOREGROUND_RED | FOREGROUND_INTENSITY - : colour_saved ); + : flag == SYS_ERR ? FOREGROUND_RED | FOREGROUND_INTENSITY + : colour_saved ); } #endif } diff --git a/tools/quake3/common/jpeg.cpp b/tools/quake3/common/jpeg.cpp index a86e01cc..74a7e186 100644 --- a/tools/quake3/common/jpeg.cpp +++ b/tools/quake3/common/jpeg.cpp @@ -218,12 +218,12 @@ static void jpeg_buffer_src( j_decompress_ptr cinfo, void* buffer, int bufsize ) */ if ( cinfo->src == NULL ) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - sizeof( my_source_mgr ) ); + ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, + sizeof( my_source_mgr ) ); src = (my_src_ptr) cinfo->src; src->buffer = (JOCTET *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - INPUT_BUF_SIZE * sizeof( JOCTET ) ); + ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, + INPUT_BUF_SIZE * sizeof( JOCTET ) ); } src = (my_src_ptr) cinfo->src; diff --git a/tools/quake3/common/md4.cpp b/tools/quake3/common/md4.cpp index df18d76d..436d9e39 100644 --- a/tools/quake3/common/md4.cpp +++ b/tools/quake3/common/md4.cpp @@ -99,7 +99,7 @@ static void copy64( std::uint32_t *M, unsigned char *in ){ for ( i = 0; i < 16; i++ ) M[i] = ( in[i * 4 + 3] << 24 ) | ( in[i * 4 + 2] << 16 ) | - ( in[i * 4 + 1] << 8 ) | ( in[i * 4 + 0] << 0 ); + ( in[i * 4 + 1] << 8 ) | ( in[i * 4 + 0] << 0 ); } static void copy4( unsigned char *out, std::uint32_t x ){ diff --git a/tools/quake3/common/polylib.cpp b/tools/quake3/common/polylib.cpp index c829e24a..eed054c1 100644 --- a/tools/quake3/common/polylib.cpp +++ b/tools/quake3/common/polylib.cpp @@ -168,7 +168,7 @@ Vector3 WindingCenter( const winding_t *w ){ for ( int i = 0 ; i < w->numpoints ; i++ ) center += w->p[i]; - + return center / w->numpoints; } @@ -427,7 +427,7 @@ winding_t *ReverseWinding( const winding_t *w ){ ============= */ void ClipWindingEpsilonStrict( winding_t *in, const Plane3f& plane, - float epsilon, winding_t **front, winding_t **back ){ + float epsilon, winding_t **front, winding_t **back ){ float dists[MAX_POINTS_ON_WINDING + 4]; EPlaneSide sides[MAX_POINTS_ON_WINDING + 4]; int counts[3]; @@ -507,7 +507,7 @@ void ClipWindingEpsilonStrict( winding_t *in, const Plane3f& plane, const double dot = dists[i] / ( dists[i] - dists[i + 1] ); Vector3 mid; for ( j = 0 ; j < 3 ; j++ ) - { // avoid round off error when possible + { // avoid round off error when possible if ( plane.normal()[j] == 1 ) { mid[j] = plane.dist(); } @@ -534,7 +534,7 @@ void ClipWindingEpsilonStrict( winding_t *in, const Plane3f& plane, } void ClipWindingEpsilon( winding_t *in, const Plane3f& plane, - float epsilon, winding_t **front, winding_t **back ){ + float epsilon, winding_t **front, winding_t **back ){ ClipWindingEpsilonStrict( in, plane, epsilon, front, back ); /* apparently most code expects that in the winding-on-plane case, the back winding is the original winding */ if ( !*front && !*back ) { @@ -676,7 +676,9 @@ void ChopWindingInPlaceAccu( winding_accu_t **inout, const Plane3f& plane, float else if ( plane.normal()[j] == -1 ) { mid[j] = -plane.dist(); } - else{mid[j] = p1[j] + ( w * ( p2[j] - p1[j] ) ); } + else{ + mid[j] = p1[j] + ( w * ( p2[j] - p1[j] ) ); + } } if ( f->numpoints >= MAX_POINTS_ON_WINDING ) { Error( "ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING" ); @@ -769,7 +771,7 @@ void ChopWindingInPlace( winding_t **inout, const Plane3f& plane, float epsilon const double dot = dists[i] / ( dists[i] - dists[i + 1] ); Vector3 mid; for ( j = 0 ; j < 3 ; j++ ) - { // avoid round off error when possible + { // avoid round off error when possible if ( plane.normal()[j] == 1 ) { mid[j] = plane.dist(); } diff --git a/tools/quake3/common/polylib.h b/tools/quake3/common/polylib.h index 4c4b3d2a..8835b3ac 100644 --- a/tools/quake3/common/polylib.h +++ b/tools/quake3/common/polylib.h @@ -48,9 +48,9 @@ winding_t *AllocWinding( int points ); float WindingArea( const winding_t *w ); Vector3 WindingCenter( const winding_t *w ); void ClipWindingEpsilon( winding_t *in, const Plane3f& plane, - float epsilon, winding_t **front, winding_t **back ); + float epsilon, winding_t **front, winding_t **back ); void ClipWindingEpsilonStrict( winding_t *in, const Plane3f& plane, - float epsilon, winding_t **front, winding_t **back ); + float epsilon, winding_t **front, winding_t **back ); winding_t *ChopWinding( winding_t *in, const Plane3f& plane ); winding_t *CopyWinding( const winding_t *w ); winding_t *ReverseWinding( const winding_t *w ); diff --git a/tools/quake3/common/scriplib.cpp b/tools/quake3/common/scriplib.cpp index e0e49966..ad16156f 100644 --- a/tools/quake3/common/scriplib.cpp +++ b/tools/quake3/common/scriplib.cpp @@ -243,7 +243,7 @@ skipspace: // ; # // comments if ( *script->script_p == ';' || *script->script_p == '#' - || ( script->script_p[0] == '/' && script->script_p[1] == '/' ) ) { + || ( script->script_p[0] == '/' && script->script_p[1] == '/' ) ) { if ( !crossline ) { Error( "Line %i is incomplete\nFile location be: %s\n", scriptline, g_strLoadedFileLocation ); } diff --git a/tools/quake3/common/threads.cpp b/tools/quake3/common/threads.cpp index 50536a72..30ec6e81 100644 --- a/tools/quake3/common/threads.cpp +++ b/tools/quake3/common/threads.cpp @@ -192,16 +192,16 @@ void RunThreadsOn( int workcnt, bool showpacifier, void ( *func )( int ) ){ for ( i = 0 ; i < numthreads ; i++ ) { threadhandle[i] = CreateThread( - NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes, - //0, // SIZE_T dwStackSize, + NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes, + //0, // SIZE_T dwStackSize, - /* ydnar: cranking stack size to eliminate radiosity crash with 1MB stack on win32 */ - ( 4096 * 1024 ), + /* ydnar: cranking stack size to eliminate radiosity crash with 1MB stack on win32 */ + ( 4096 * 1024 ), - (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddress, - (LPVOID)i, // LPVOID lpParameter, - 0, // DWORD dwCreationFlags, - NULL ); // LPDWORD lpThreadId + (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddress, + (LPVOID)i, // LPVOID lpParameter, + 0, // DWORD dwCreationFlags, + NULL ); // LPDWORD lpThreadId } for ( i = 0 ; i < numthreads ; i++ ) @@ -303,7 +303,7 @@ void RunThreadsOn( int workcnt, bool showpacifier, void ( *func )( int ) ){ for ( i = 0 ; i < numthreads ; i++ ) { if ( pthread_create( &work_threads[i], attrib - , (pthread_startroutine_t)func, (pthread_addr_t)i ) == -1 ) { + , (pthread_startroutine_t)func, (pthread_addr_t)i ) == -1 ) { Error( "pthread_create failed" ); } } @@ -390,7 +390,7 @@ void RunThreadsOn( int workcnt, bool showpacifier, void ( *func )( int ) ){ for ( i = 0 ; i < numthreads - 1 ; i++ ) { pid[i] = sprocsp( ( void ( * )( void *, size_t ) )func, PR_SALL, (void *)i - , NULL, 0x200000 ); // 2 meg stacks + , NULL, 0x200000 ); // 2 meg stacks if ( pid[i] == -1 ) { perror( "sproc" ); Error( "sproc failed" ); diff --git a/tools/quake3/common/vfs.cpp b/tools/quake3/common/vfs.cpp index d867bc24..e42af6b9 100644 --- a/tools/quake3/common/vfs.cpp +++ b/tools/quake3/common/vfs.cpp @@ -208,7 +208,7 @@ void vfsInitDirectory( const char *path ){ // lists all .shader files void vfsListShaderFiles( StrList* list, void pushStringCallback( StrList* list, const char* string ) ){ -/* search in dirs */ + /* search in dirs */ for ( int i = 0; i < g_numDirs; i++ ){ GDir *dir = g_dir_open( StringOutputStream( 256 )( g_strDirs[ i ], "scripts/" ), 0, NULL ); @@ -470,9 +470,9 @@ bool vfsPackFile( const char *filename, const char *packname, const int compLeve else{ mz_bool success = MZ_TRUE; success &= mz_zip_add_mem_to_archive_file_in_place_with_time( packname, filename, bufferptr, i, 0, 0, compLevel, file->zipinfo.cur_file_info.dosDate ); - if ( !success ){ - Error( "Failed creating zip archive \"%s\"!\n", packname ); - } + if ( !success ){ + Error( "Failed creating zip archive \"%s\"!\n", packname ); + } free( bufferptr ); return true; } diff --git a/tools/quake3/q3map2/autopk3.cpp b/tools/quake3/q3map2/autopk3.cpp index 9a40d56b..aa3eea1f 100644 --- a/tools/quake3/q3map2/autopk3.cpp +++ b/tools/quake3/q3map2/autopk3.cpp @@ -89,9 +89,9 @@ static inline void tex2list( StrList* texlist, StrList* EXtex, StrList* rEXtex ) /* exclude */ if( !StrList_find( texlist, token ) && - !StrList_find( EXtex, token ) && - ( rEXtex == NULL || - !StrList_find( rEXtex, token ) ) ){ + !StrList_find( EXtex, token ) && + ( rEXtex == NULL || + !StrList_find( rEXtex, token ) ) ){ StrList_append( texlist, token ); } strcat( token, ".tga" ); // default extension for repacked shader text @@ -383,7 +383,7 @@ int pk3BSPMain( int argc, char **argv ){ } //Parse Shader Files - /* hack */ + /* hack */ endofscript = true; for ( i = 0; i < pk3Shaderfiles->n; ++i ){ @@ -430,8 +430,8 @@ int pk3BSPMain( int argc, char **argv ){ break; } if ( !strEqual( token, "{" ) ) { - Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", - scriptFile, scriptline, token, g_strLoadedFileLocation ); + Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", + scriptFile, scriptline, token, g_strLoadedFileLocation ); } while ( 1 ) @@ -481,8 +481,8 @@ int pk3BSPMain( int argc, char **argv ){ break; } if ( !strEqual( token, "{" ) ) { - Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", - scriptFile, scriptline, token, g_strLoadedFileLocation ); + Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", + scriptFile, scriptline, token, g_strLoadedFileLocation ); } bool hasmap = false; @@ -523,7 +523,7 @@ int pk3BSPMain( int argc, char **argv ){ /* digest any images */ if ( striEqual( token, "map" ) || - striEqual( token, "clampMap" ) ) { + striEqual( token, "clampMap" ) ) { hasmap = true; /* get an image */ GetToken( false ); @@ -532,7 +532,7 @@ int pk3BSPMain( int argc, char **argv ){ } } else if ( striEqual( token, "animMap" ) || - striEqual( token, "clampAnimMap" ) ) { + striEqual( token, "clampAnimMap" ) ) { hasmap = true; GetToken( false );// skip num while ( TokenAvailable() ){ @@ -548,7 +548,7 @@ int pk3BSPMain( int argc, char **argv ){ strcpy( token, stream( "video/", token ) ); } if( !StrList_find( pk3Videos, token ) && - !StrList_find( ExVideos, token ) ) + !StrList_find( ExVideos, token ) ) StrList_append( pk3Videos, token ); } } @@ -618,7 +618,7 @@ int pk3BSPMain( int argc, char **argv ){ -/* exclude stuff */ + /* exclude stuff */ //wanted shaders from excluded .shaders Sys_Printf( "\n" ); for ( i = 0; i < pk3Shaders->n; ++i ){ @@ -639,7 +639,7 @@ int pk3BSPMain( int argc, char **argv ){ if ( !strEmpty( pk3Shaders->s[i] ) ){ FixDOSName( pk3Shaders->s[i] ); if( StrList_find( pk3Textures, pk3Shaders->s[i] ) || - StrList_find( ExTextures, pk3Shaders->s[i] ) ) + StrList_find( ExTextures, pk3Shaders->s[i] ) ) strClear( pk3Shaders->s[i] ); } } @@ -780,7 +780,7 @@ int repackBSPMain( int argc, char **argv ){ } } -/* load exclusions file */ + /* load exclusions file */ StrList* ExTextures = StrList_allocate( 4096 ); StrList* ExShaders = StrList_allocate( 4096 ); StrList* ExShaderfiles = StrList_allocate( 4096 ); @@ -819,7 +819,7 @@ int repackBSPMain( int argc, char **argv ){ } -/* load repack.exclude */ + /* load repack.exclude */ StrList* rExTextures = StrList_allocate( 65536 ); StrList* rExShaders = StrList_allocate( 32768 ); StrList* rExShaderfiles = StrList_allocate( 4096 ); @@ -890,7 +890,7 @@ int repackBSPMain( int argc, char **argv ){ /* extract input file name */ const CopiedString nameOFrepack( PathFilename( source ) ); -/* load bsps */ + /* load bsps */ StrList* pk3Shaders = StrList_allocate( 65536 ); StrList* pk3Sounds = StrList_allocate( 4096 ); StrList* pk3Shaderfiles = StrList_allocate( 4096 ); @@ -1136,7 +1136,7 @@ int repackBSPMain( int argc, char **argv ){ Sys_Printf( "\t\nParsing shaders....\n\n" ); StringOutputStream shaderText( 4096 ); StringOutputStream allShaders( 1048576 ); - /* hack */ + /* hack */ endofscript = true; for ( i = 0; i < pk3Shaderfiles->n; ++i ){ @@ -1181,8 +1181,8 @@ int repackBSPMain( int argc, char **argv ){ break; } if ( !strEqual( token, "{" ) ) { - Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", - scriptFile, scriptline, token, g_strLoadedFileLocation ); + Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", + scriptFile, scriptline, token, g_strLoadedFileLocation ); } shaderText << "\n{"; bool hasmap = false; @@ -1226,7 +1226,7 @@ int repackBSPMain( int argc, char **argv ){ /* digest any images */ if ( striEqual( token, "map" ) || - striEqual( token, "clampMap" ) ) { + striEqual( token, "clampMap" ) ) { shaderText << "\n\t\t" << token; hasmap = true; @@ -1238,7 +1238,7 @@ int repackBSPMain( int argc, char **argv ){ shaderText << " " << token; } else if ( striEqual( token, "animMap" ) || - striEqual( token, "clampAnimMap" ) ) { + striEqual( token, "clampAnimMap" ) ) { shaderText << "\n\t\t" << token; hasmap = true; @@ -1261,8 +1261,8 @@ int repackBSPMain( int argc, char **argv ){ strcpy( token, stream( "video/", token ) ); } if( !StrList_find( pk3Videos, token ) && - !StrList_find( ExVideos, token ) && - !StrList_find( rExVideos, token ) ) + !StrList_find( ExVideos, token ) && + !StrList_find( rExVideos, token ) ) StrList_append( pk3Videos, token ); } else if ( striEqual( token, "mapComp" ) || striEqual( token, "mapNoComp" ) || striEqual( token, "animmapcomp" ) || striEqual( token, "animmapnocomp" ) ){ @@ -1356,10 +1356,10 @@ int repackBSPMain( int argc, char **argv ){ } } } -/* TODO: RTCW's mapComp, mapNoComp, animmapcomp, animmapnocomp; nocompress?; ET's implicitmap, implicitblend, implicitmask */ + /* TODO: RTCW's mapComp, mapNoComp, animmapcomp, animmapnocomp; nocompress?; ET's implicitmap, implicitblend, implicitmask */ -/* exclude stuff */ + /* exclude stuff */ //pure textures (shader ones are done) for ( i = 0; i < pk3Shaders->n; ++i ){ @@ -1377,8 +1377,8 @@ int repackBSPMain( int argc, char **argv ){ } if ( !strEmpty( pk3Shaders->s[i] ) ){ if( StrList_find( pk3Textures, pk3Shaders->s[i] ) || - StrList_find( ExTextures, pk3Shaders->s[i] ) || - StrList_find( rExTextures, pk3Shaders->s[i] ) ) + StrList_find( ExTextures, pk3Shaders->s[i] ) || + StrList_find( rExTextures, pk3Shaders->s[i] ) ) strClear( pk3Shaders->s[i] ); } } @@ -1387,7 +1387,7 @@ int repackBSPMain( int argc, char **argv ){ //snds for ( i = 0; i < pk3Sounds->n; ++i ){ if( StrList_find( ExSounds, pk3Sounds->s[i] ) || - StrList_find( rExSounds, pk3Sounds->s[i] ) ) + StrList_find( rExSounds, pk3Sounds->s[i] ) ) strClear( pk3Sounds->s[i] ); } diff --git a/tools/quake3/q3map2/brush.cpp b/tools/quake3/q3map2/brush.cpp index 13c5ce17..d4db011e 100644 --- a/tools/quake3/q3map2/brush.cpp +++ b/tools/quake3/q3map2/brush.cpp @@ -265,14 +265,18 @@ void SnapWeldVectorAccu( const DoubleVector3& a, const DoubleVector3& b, DoubleV if ( ad < SNAP_EPSILON ) { out[i] = ai; } - else{out[i] = a[i]; } + else{ + out[i] = a[i]; + } } else { if ( bd < SNAP_EPSILON ) { out[i] = bi; } - else{out[i] = b[i]; } + else{ + out[i] = b[i]; + } } } } @@ -780,9 +784,9 @@ node_t *AllocNode( void ){ #define EDGE_LENGTH 0.2 bool WindingIsTiny( winding_t *w ){ /* - if (WindingArea (w) < 1) - return true; - return false; + if (WindingArea (w) < 1) + return true; + return false; */ int i, j; int edges = 0; @@ -952,7 +956,7 @@ void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back ) continue; } ClipWindingEpsilonStrict( w, plane->plane, - 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1] ); /* strict, in parallel case we get the face back because it also is the midwinding */ + 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1] ); /* strict, in parallel case we get the face back because it also is the midwinding */ for ( j = 0 ; j < 2 ; j++ ) { if ( !cw[j] ) { diff --git a/tools/quake3/q3map2/bspfile_abstract.cpp b/tools/quake3/q3map2/bspfile_abstract.cpp index da7517d4..84a6a6ef 100644 --- a/tools/quake3/q3map2/bspfile_abstract.cpp +++ b/tools/quake3/q3map2/bspfile_abstract.cpp @@ -447,47 +447,47 @@ void PrintBSPFileSizes( void ){ /* print various and sundry bits */ Sys_Printf( "%9d models %9d\n", - numBSPModels, (int) ( numBSPModels * sizeof( bspModel_t ) ) ); + numBSPModels, (int) ( numBSPModels * sizeof( bspModel_t ) ) ); Sys_Printf( "%9d shaders %9d\n", - numBSPShaders, (int) ( numBSPShaders * sizeof( bspShader_t ) ) ); + numBSPShaders, (int) ( numBSPShaders * sizeof( bspShader_t ) ) ); Sys_Printf( "%9d brushes %9d\n", - numBSPBrushes, (int) ( numBSPBrushes * sizeof( bspBrush_t ) ) ); + numBSPBrushes, (int) ( numBSPBrushes * sizeof( bspBrush_t ) ) ); Sys_Printf( "%9d brushsides %9d *\n", - numBSPBrushSides, (int) ( numBSPBrushSides * sizeof( bspBrushSide_t ) ) ); + numBSPBrushSides, (int) ( numBSPBrushSides * sizeof( bspBrushSide_t ) ) ); Sys_Printf( "%9d fogs %9d\n", - numBSPFogs, (int) ( numBSPFogs * sizeof( bspFog_t ) ) ); + numBSPFogs, (int) ( numBSPFogs * sizeof( bspFog_t ) ) ); Sys_Printf( "%9d planes %9d\n", - numBSPPlanes, (int) ( numBSPPlanes * sizeof( bspPlane_t ) ) ); + numBSPPlanes, (int) ( numBSPPlanes * sizeof( bspPlane_t ) ) ); Sys_Printf( "%9zu entdata %9d\n", - entities.size(), bspEntDataSize ); + entities.size(), bspEntDataSize ); Sys_Printf( "\n" ); Sys_Printf( "%9d nodes %9d\n", - numBSPNodes, (int) ( numBSPNodes * sizeof( bspNode_t ) ) ); + numBSPNodes, (int) ( numBSPNodes * sizeof( bspNode_t ) ) ); Sys_Printf( "%9d leafs %9d\n", - numBSPLeafs, (int) ( numBSPLeafs * sizeof( bspLeaf_t ) ) ); + numBSPLeafs, (int) ( numBSPLeafs * sizeof( bspLeaf_t ) ) ); Sys_Printf( "%9d leafsurfaces %9d\n", - numBSPLeafSurfaces, (int) ( numBSPLeafSurfaces * sizeof( *bspLeafSurfaces ) ) ); + numBSPLeafSurfaces, (int) ( numBSPLeafSurfaces * sizeof( *bspLeafSurfaces ) ) ); Sys_Printf( "%9d leafbrushes %9d\n", - numBSPLeafBrushes, (int) ( numBSPLeafBrushes * sizeof( *bspLeafBrushes ) ) ); + numBSPLeafBrushes, (int) ( numBSPLeafBrushes * sizeof( *bspLeafBrushes ) ) ); Sys_Printf( "\n" ); Sys_Printf( "%9d drawsurfaces %9d *\n", - numBSPDrawSurfaces, (int) ( numBSPDrawSurfaces * sizeof( *bspDrawSurfaces ) ) ); + numBSPDrawSurfaces, (int) ( numBSPDrawSurfaces * sizeof( *bspDrawSurfaces ) ) ); Sys_Printf( "%9d patchsurfaces \n", - patchCount ); + patchCount ); Sys_Printf( "%9d drawverts %9d *\n", - numBSPDrawVerts, (int) ( numBSPDrawVerts * sizeof( *bspDrawVerts ) ) ); + numBSPDrawVerts, (int) ( numBSPDrawVerts * sizeof( *bspDrawVerts ) ) ); Sys_Printf( "%9d drawindexes %9d\n", - numBSPDrawIndexes, (int) ( numBSPDrawIndexes * sizeof( *bspDrawIndexes ) ) ); + numBSPDrawIndexes, (int) ( numBSPDrawIndexes * sizeof( *bspDrawIndexes ) ) ); Sys_Printf( "\n" ); Sys_Printf( "%9d lightmaps %9d\n", - numBSPLightBytes / ( game->lightmapSize * game->lightmapSize * 3 ), numBSPLightBytes ); + numBSPLightBytes / ( game->lightmapSize * game->lightmapSize * 3 ), numBSPLightBytes ); Sys_Printf( "%9d lightgrid %9d *\n", - numBSPGridPoints, (int) ( numBSPGridPoints * sizeof( *bspGridPoints ) ) ); + numBSPGridPoints, (int) ( numBSPGridPoints * sizeof( *bspGridPoints ) ) ); Sys_Printf( " visibility %9d\n", - numBSPVisBytes ); + numBSPVisBytes ); } @@ -647,8 +647,8 @@ void UnparseEntities( void ){ /* ydnar: certain entities get stripped from bsp file */ const char *classname = e.classname(); if ( striEqual( classname, "misc_model" ) || - striEqual( classname, "_decal" ) || - striEqual( classname, "_skybox" ) ) { + striEqual( classname, "_decal" ) || + striEqual( classname, "_skybox" ) ) { continue; } diff --git a/tools/quake3/q3map2/bspfile_rbsp.cpp b/tools/quake3/q3map2/bspfile_rbsp.cpp index 5bca723d..d2e32c61 100644 --- a/tools/quake3/q3map2/bspfile_rbsp.cpp +++ b/tools/quake3/q3map2/bspfile_rbsp.cpp @@ -158,7 +158,7 @@ static void AddLightGridLumps( FILE *file, rbspHeader_t *header ){ for ( c = 0; c < 3; c++ ) { if ( abs( (int) in->ambient[ k ][ c ] - (int) out->ambient[ k ][ c ] ) > LG_EPSILON || - abs( (int) in->directed[ k ][ c ] - (int) out->directed[ k ][ c ] ) > LG_EPSILON ) { + abs( (int) in->directed[ k ][ c ] - (int) out->directed[ k ][ c ] ) > LG_EPSILON ) { bad = true; break; } diff --git a/tools/quake3/q3map2/convert_ase.cpp b/tools/quake3/q3map2/convert_ase.cpp index 4f82af78..9f42fd2f 100644 --- a/tools/quake3/q3map2/convert_ase.cpp +++ b/tools/quake3/q3map2/convert_ase.cpp @@ -123,7 +123,7 @@ static void ConvertSurface( FILE *f, bspModel_t *model, int modelNum, bspDrawSur c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; fprintf( f, "\t\t\t*MESH_FACE\t%d\tA:\t%d\tB:\t%d\tC:\t%d\tAB:\t1\tBC:\t1\tCA:\t1\t*MESH_SMOOTHING\t0\t*MESH_MTLID\t0\r\n", - face, a, b, c ); + face, a, b, c ); } fprintf( f, "\t\t}\r\n" ); diff --git a/tools/quake3/q3map2/convert_bsp.cpp b/tools/quake3/q3map2/convert_bsp.cpp index 7f73f7ea..30cfc888 100644 --- a/tools/quake3/q3map2/convert_bsp.cpp +++ b/tools/quake3/q3map2/convert_bsp.cpp @@ -563,12 +563,12 @@ int ScaleBSPMain( int argc, char **argv ){ // b->xyz -> ob // c->xyz -> oc ExtrapolateTexcoords( - &oa[0], &oa[3], - &ob[0], &ob[3], - &oc[0], &oc[3], - a->xyz, a->st, - b->xyz, b->st, - c->xyz, c->st ); + &oa[0], &oa[3], + &ob[0], &ob[3], + &oc[0], &oc[3], + a->xyz, a->st, + b->xyz, b->st, + c->xyz, c->st ); } break; } diff --git a/tools/quake3/q3map2/convert_map.cpp b/tools/quake3/q3map2/convert_map.cpp index 6eca8d8f..69c47d3f 100644 --- a/tools/quake3/q3map2/convert_map.cpp +++ b/tools/quake3/q3map2/convert_map.cpp @@ -39,12 +39,12 @@ */ static float Det3x3( float a00, float a01, float a02, - float a10, float a11, float a12, - float a20, float a21, float a22 ){ + float a10, float a11, float a12, + float a20, float a21, float a22 ){ return - a00 * ( a11 * a22 - a12 * a21 ) - - a01 * ( a10 * a22 - a12 * a20 ) - + a02 * ( a10 * a21 - a11 * a20 ); + a00 * ( a11 * a22 - a12 * a21 ) + - a01 * ( a10 * a22 - a12 * a20 ) + + a02 * ( a10 * a21 - a11 * a20 ); } void GetBestSurfaceTriangleMatchForBrushside( side_t *buildSide, bspDrawVert_t *bestVert[3] ){ @@ -163,27 +163,27 @@ static void ConvertOriginBrush( FILE *f, int num, const Vector3& origin, bool br { if ( brushPrimitives ) { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - origin[0] + 8 * S( i,0,0 ), origin[1] + 8 * S( i,0,1 ), origin[2] + 8 * S( i,0,2 ), - origin[0] + 8 * S( i,1,0 ), origin[1] + 8 * S( i,1,1 ), origin[2] + 8 * S( i,1,2 ), - origin[0] + 8 * S( i,2,0 ), origin[1] + 8 * S( i,2,1 ), origin[2] + 8 * S( i,2,2 ), - 1.0f / 16.0f, 0.0f, FRAC( ( S( i,5,0 ) * origin[0] + S( i,5,1 ) * origin[1] + S( i,5,2 ) * origin[2] ) / 16.0 + 0.5 ), - 0.0f, 1.0f / 16.0f, FRAC( ( S( i,6,0 ) * origin[0] + S( i,6,1 ) * origin[1] + S( i,6,2 ) * origin[2] ) / 16.0 + 0.5 ), - "common/origin", - 0 - ); + origin[0] + 8 * S( i,0,0 ), origin[1] + 8 * S( i,0,1 ), origin[2] + 8 * S( i,0,2 ), + origin[0] + 8 * S( i,1,0 ), origin[1] + 8 * S( i,1,1 ), origin[2] + 8 * S( i,1,2 ), + origin[0] + 8 * S( i,2,0 ), origin[1] + 8 * S( i,2,1 ), origin[2] + 8 * S( i,2,2 ), + 1.0f / 16.0f, 0.0f, FRAC( ( S( i,5,0 ) * origin[0] + S( i,5,1 ) * origin[1] + S( i,5,2 ) * origin[2] ) / 16.0 + 0.5 ), + 0.0f, 1.0f / 16.0f, FRAC( ( S( i,6,0 ) * origin[0] + S( i,6,1 ) * origin[1] + S( i,6,2 ) * origin[2] ) / 16.0 + 0.5 ), + "common/origin", + 0 + ); } else { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - origin[0] + 8 * S( i,0,0 ), origin[1] + 8 * S( i,0,1 ), origin[2] + 8 * S( i,0,2 ), - origin[0] + 8 * S( i,1,0 ), origin[1] + 8 * S( i,1,1 ), origin[2] + 8 * S( i,1,2 ), - origin[0] + 8 * S( i,2,0 ), origin[1] + 8 * S( i,2,1 ), origin[2] + 8 * S( i,2,2 ), - "common/origin", - FRAC( ( S( i,3,0 ) * origin[0] + S( i,3,1 ) * origin[1] + S( i,3,2 ) * origin[2] ) / 16.0 + 0.5 ) * originSize, - FRAC( ( S( i,4,0 ) * origin[0] + S( i,4,1 ) * origin[1] + S( i,4,2 ) * origin[2] ) / 16.0 + 0.5 ) * originSize, - 0.0f, 16.0 / originSize, 16.0 / originSize, - 0 - ); + origin[0] + 8 * S( i,0,0 ), origin[1] + 8 * S( i,0,1 ), origin[2] + 8 * S( i,0,2 ), + origin[0] + 8 * S( i,1,0 ), origin[1] + 8 * S( i,1,1 ), origin[2] + 8 * S( i,1,2 ), + origin[0] + 8 * S( i,2,0 ), origin[1] + 8 * S( i,2,1 ), origin[2] + 8 * S( i,2,2 ), + "common/origin", + FRAC( ( S( i,3,0 ) * origin[0] + S( i,3,1 ) * origin[1] + S( i,3,2 ) * origin[2] ) / 16.0 + 0.5 ) * originSize, + FRAC( ( S( i,4,0 ) * origin[0] + S( i,4,1 ) * origin[1] + S( i,4,2 ) * origin[2] ) / 16.0 + 0.5 ) * originSize, + 0.0f, 16.0 / originSize, 16.0 / originSize, + 0 + ); } } #undef S @@ -313,25 +313,25 @@ static void ConvertBrushFast( FILE *f, int num, bspBrush_t *brush, const Vector3 { if ( brushPrimitives ) { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - 1.0f / 32.0f, 0.0f, 0.0f, - 0.0f, 1.0f / 32.0f, 0.0f, - texture, - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + 1.0f / 32.0f, 0.0f, 0.0f, + 0.0f, 1.0f / 32.0f, 0.0f, + texture, + 0 + ); } else { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture, - 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture, + 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, + 0 + ); } } } @@ -534,53 +534,53 @@ static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, const Vector3& or // - st[i] = texMat[i][0]*x + texMat[i][1]*y + texMat[i][2] // (for three vertices) D = Det3x3( - xyI[0], xyI[1], 1, - xyJ[0], xyJ[1], 1, - xyK[0], xyK[1], 1 - ); + xyI[0], xyI[1], 1, + xyJ[0], xyJ[1], 1, + xyK[0], xyK[1], 1 + ); if ( D != 0 ) { for ( i = 0; i < 2; ++i ) { D0 = Det3x3( - stI[i], xyI[1], 1, - stJ[i], xyJ[1], 1, - stK[i], xyK[1], 1 - ); + stI[i], xyI[1], 1, + stJ[i], xyJ[1], 1, + stK[i], xyK[1], 1 + ); D1 = Det3x3( - xyI[0], stI[i], 1, - xyJ[0], stJ[i], 1, - xyK[0], stK[i], 1 - ); + xyI[0], stI[i], 1, + xyJ[0], stJ[i], 1, + xyK[0], stK[i], 1 + ); D2 = Det3x3( - xyI[0], xyI[1], stI[i], - xyJ[0], xyJ[1], stJ[i], - xyK[0], xyK[1], stK[i] - ); + xyI[0], xyI[1], stI[i], + xyJ[0], xyJ[1], stJ[i], + xyK[0], xyK[1], stK[i] + ); buildSide->texMat[i] = { D0 / D, D1 / D, D2 / D }; } } else{ fprintf( stderr, "degenerate triangle found when solving texMat equations for\n(%f %f %f) (%f %f %f) (%f %f %f)\n( %f %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n", - buildPlane.normal()[0], buildPlane.normal()[1], buildPlane.normal()[2], - vert[0]->normal[0], vert[0]->normal[1], vert[0]->normal[2], - texX[0], texX[1], texX[2], texY[0], texY[1], texY[2], - vert[0]->xyz[0], vert[0]->xyz[1], vert[0]->xyz[2], xyI[0], xyI[1], - vert[1]->xyz[0], vert[1]->xyz[1], vert[1]->xyz[2], xyJ[0], xyJ[1], - vert[2]->xyz[0], vert[2]->xyz[1], vert[2]->xyz[2], xyK[0], xyK[1] - ); + buildPlane.normal()[0], buildPlane.normal()[1], buildPlane.normal()[2], + vert[0]->normal[0], vert[0]->normal[1], vert[0]->normal[2], + texX[0], texX[1], texX[2], texY[0], texY[1], texY[2], + vert[0]->xyz[0], vert[0]->xyz[1], vert[0]->xyz[2], xyI[0], xyI[1], + vert[1]->xyz[0], vert[1]->xyz[1], vert[1]->xyz[2], xyJ[0], xyJ[1], + vert[2]->xyz[0], vert[2]->xyz[1], vert[2]->xyz[2], xyK[0], xyK[1] + ); } /* print brush side */ /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - buildSide->texMat[0][0], buildSide->texMat[0][1], FRAC( buildSide->texMat[0][2] ), - buildSide->texMat[1][0], buildSide->texMat[1][1], FRAC( buildSide->texMat[1][2] ), - texture, - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + buildSide->texMat[0][0], buildSide->texMat[0][1], FRAC( buildSide->texMat[0][2] ), + buildSide->texMat[1][0], buildSide->texMat[1][1], FRAC( buildSide->texMat[1][2] ), + texture, + 0 + ); } else { @@ -613,33 +613,36 @@ static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, const Vector3& or tv = 2; } - stI[0] = vert[0]->st[0] * buildSide->shaderInfo->shaderWidth; stI[1] = vert[0]->st[1] * buildSide->shaderInfo->shaderHeight; - stJ[0] = vert[1]->st[0] * buildSide->shaderInfo->shaderWidth; stJ[1] = vert[1]->st[1] * buildSide->shaderInfo->shaderHeight; - stK[0] = vert[2]->st[0] * buildSide->shaderInfo->shaderWidth; stK[1] = vert[2]->st[1] * buildSide->shaderInfo->shaderHeight; + stI[0] = vert[0]->st[0] * buildSide->shaderInfo->shaderWidth; + stI[1] = vert[0]->st[1] * buildSide->shaderInfo->shaderHeight; + stJ[0] = vert[1]->st[0] * buildSide->shaderInfo->shaderWidth; + stJ[1] = vert[1]->st[1] * buildSide->shaderInfo->shaderHeight; + stK[0] = vert[2]->st[0] * buildSide->shaderInfo->shaderWidth; + stK[1] = vert[2]->st[1] * buildSide->shaderInfo->shaderHeight; D = Det3x3( - vert[0]->xyz[sv], vert[0]->xyz[tv], 1, - vert[1]->xyz[sv], vert[1]->xyz[tv], 1, - vert[2]->xyz[sv], vert[2]->xyz[tv], 1 - ); + vert[0]->xyz[sv], vert[0]->xyz[tv], 1, + vert[1]->xyz[sv], vert[1]->xyz[tv], 1, + vert[2]->xyz[sv], vert[2]->xyz[tv], 1 + ); if ( D != 0 ) { for ( i = 0; i < 2; ++i ) { D0 = Det3x3( - stI[i], vert[0]->xyz[tv], 1, - stJ[i], vert[1]->xyz[tv], 1, - stK[i], vert[2]->xyz[tv], 1 - ); + stI[i], vert[0]->xyz[tv], 1, + stJ[i], vert[1]->xyz[tv], 1, + stK[i], vert[2]->xyz[tv], 1 + ); D1 = Det3x3( - vert[0]->xyz[sv], stI[i], 1, - vert[1]->xyz[sv], stJ[i], 1, - vert[2]->xyz[sv], stK[i], 1 - ); + vert[0]->xyz[sv], stI[i], 1, + vert[1]->xyz[sv], stJ[i], 1, + vert[2]->xyz[sv], stK[i], 1 + ); D2 = Det3x3( - vert[0]->xyz[sv], vert[0]->xyz[tv], stI[i], - vert[1]->xyz[sv], vert[1]->xyz[tv], stJ[i], - vert[2]->xyz[sv], vert[2]->xyz[tv], stK[i] - ); + vert[0]->xyz[sv], vert[0]->xyz[tv], stI[i], + vert[1]->xyz[sv], vert[1]->xyz[tv], stJ[i], + vert[2]->xyz[sv], vert[2]->xyz[tv], stK[i] + ); sts[i] = { D0 / D, D1 / D, D2 / D }; //Sys_Printf( "%.3f %.3f %.3f \n", sts[i][0], sts[i][1], sts[i][2] ); } @@ -671,13 +674,13 @@ static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, const Vector3& or /* print brush side */ /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture, - shift[0], shift[1], rotate, scale[0], scale[1], - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture, + shift[0], shift[1], rotate, scale[0], scale[1], + 0 + ); } } else @@ -692,25 +695,25 @@ static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, const Vector3& or if ( brushPrimitives ) { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - 1.0f / 16.0f, 0.0f, 0.0f, - 0.0f, 1.0f / 16.0f, 0.0f, - texture, - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + 1.0f / 16.0f, 0.0f, 0.0f, + 0.0f, 1.0f / 16.0f, 0.0f, + texture, + 0 + ); } else { fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture, - 0.0f, 0.0f, 0.0f, 0.25f, 0.25f, - 0 - ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture, + 0.0f, 0.0f, 0.0f, 0.25f, 0.25f, + 0 + ); } } } @@ -768,10 +771,10 @@ for ( i = 0; i < brush->numSides; i++ ) /* print brush side */ /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s 0 0 0 0.5 0.5 0 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture ); + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture ); } #endif diff --git a/tools/quake3/q3map2/convert_obj.cpp b/tools/quake3/q3map2/convert_obj.cpp index 430b0490..e5d87dd5 100644 --- a/tools/quake3/q3map2/convert_obj.cpp +++ b/tools/quake3/q3map2/convert_obj.cpp @@ -111,10 +111,10 @@ static void ConvertSurfaceToOBJ( FILE *f, bspModel_t *model, int modelNum, bspDr c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; fprintf( f, "f %d/%d/%d %d/%d/%d %d/%d/%d\r\n", - a + objVertexCount + 1, a + objVertexCount + 1, a + objVertexCount + 1, - b + objVertexCount + 1, b + objVertexCount + 1, b + objVertexCount + 1, - c + objVertexCount + 1, c + objVertexCount + 1, c + objVertexCount + 1 - ); + a + objVertexCount + 1, a + objVertexCount + 1, a + objVertexCount + 1, + b + objVertexCount + 1, b + objVertexCount + 1, b + objVertexCount + 1, + c + objVertexCount + 1, c + objVertexCount + 1, c + objVertexCount + 1 + ); } objVertexCount += ds->numVerts; @@ -242,8 +242,8 @@ void Convert_ReferenceLightmaps( const char* base, int* lmIndices ){ if ( !GetToken( true ) ) break; if ( !strEqual( token, "{" ) ) - Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", - shaderfile, scriptline, token, g_strLoadedFileLocation ); + Error( "ParseShaderFile: %s, line %d: { not found!\nFound instead: %s\nFile location be: %s", + shaderfile, scriptline, token, g_strLoadedFileLocation ); while ( 1 ) { /* get the next token */ @@ -271,7 +271,7 @@ void Convert_ReferenceLightmaps( const char* base, int* lmIndices ){ int lmindex; int okcount = 0; if( sscanf( token + strlen( token ) - ( strlen( EXTERNAL_LIGHTMAP ) + 1 ), "/" EXTERNAL_LIGHTMAP "%n", &lmindex, &okcount ) - && okcount == ( strlen( EXTERNAL_LIGHTMAP ) + 1 ) ){ + && okcount == ( strlen( EXTERNAL_LIGHTMAP ) + 1 ) ){ for ( int i = 0; i < numBSPShaders; ++i ){ // find bspShaders[i]<->lmindex pair if( strEqual( bspShaders[i].shader, shadername ) ){ lmIndices[i] = lmindex; diff --git a/tools/quake3/q3map2/decals.cpp b/tools/quake3/q3map2/decals.cpp index 0313bb09..90631f94 100644 --- a/tools/quake3/q3map2/decals.cpp +++ b/tools/quake3/q3map2/decals.cpp @@ -177,7 +177,7 @@ static bool MakeTextureMatrix( decalProjector_t *dp, const Plane3f& projection, for ( k = 0; k < 3; k++ ) { if ( fabs( deltas[ k ][ j ] ) > delta && - fabs( texDeltas[ k ][ i ] ) > texDelta ) { + fabs( texDeltas[ k ][ i ] ) > texDelta ) { delta = deltas[ k ][ j ]; texDelta = texDeltas[ k ][ i ]; } @@ -201,15 +201,15 @@ static bool MakeTextureMatrix( decalProjector_t *dp, const Plane3f& projection, /* debug code */ #if 1 Sys_Printf( "Mat: [ %f %f %f %f ] [ %f %f %f %f ] Theta: %lf (%lf)\n", - dp->texMat[ 0 ][ 0 ], dp->texMat[ 0 ][ 1 ], dp->texMat[ 0 ][ 2 ], dp->texMat[ 0 ][ 3 ], - dp->texMat[ 1 ][ 0 ], dp->texMat[ 1 ][ 1 ], dp->texMat[ 1 ][ 2 ], dp->texMat[ 1 ][ 3 ], - radians_to_degrees( acos( vector3_dot( dp->texMat[ 0 ].vec3(), dp->texMat[ 1 ].vec3() ) ) ), - radians_to_degrees( acos( vector3_dot( axis[ 0 ], axis[ 1 ] ) ) ) ); + dp->texMat[ 0 ][ 0 ], dp->texMat[ 0 ][ 1 ], dp->texMat[ 0 ][ 2 ], dp->texMat[ 0 ][ 3 ], + dp->texMat[ 1 ][ 0 ], dp->texMat[ 1 ][ 1 ], dp->texMat[ 1 ][ 2 ], dp->texMat[ 1 ][ 3 ], + radians_to_degrees( acos( vector3_dot( dp->texMat[ 0 ].vec3(), dp->texMat[ 1 ].vec3() ) ) ), + radians_to_degrees( acos( vector3_dot( axis[ 0 ], axis[ 1 ] ) ) ) ); Sys_Printf( "XYZ: %f %f %f ST: %f %f ST(t): %lf %lf\n", - a->xyz[ 0 ], a->xyz[ 1 ], a->xyz[ 2 ], - a->st[ 0 ], a->st[ 1 ], - vector3_dot( a->xyz, dp->texMat[ 0 ].vec3() ) + dp->texMat[ 0 ][ 3 ], vector3_dot( a->xyz, dp->texMat[ 1 ].vec3() ) + dp->texMat[ 1 ][ 3 ] ); + a->xyz[ 0 ], a->xyz[ 1 ], a->xyz[ 2 ], + a->st[ 0 ], a->st[ 1 ], + vector3_dot( a->xyz, dp->texMat[ 0 ].vec3() ) + dp->texMat[ 0 ][ 3 ], vector3_dot( a->xyz, dp->texMat[ 1 ].vec3() ) + dp->texMat[ 1 ][ 3 ] ); #endif /* test texture matrix */ @@ -217,21 +217,21 @@ static bool MakeTextureMatrix( decalProjector_t *dp, const Plane3f& projection, t = vector3_dot( a->xyz, dp->texMat[ 1 ].vec3() ) + dp->texMat[ 1 ][ 3 ]; if ( !float_equal_epsilon( s, a->st[ 0 ], 0.01 ) || !float_equal_epsilon( t, a->st[ 1 ], 0.01 ) ) { Sys_Printf( "Bad texture matrix! (A) (%f, %f) != (%f, %f)\n", - s, t, a->st[ 0 ], a->st[ 1 ] ); + s, t, a->st[ 0 ], a->st[ 1 ] ); //% return false; } s = vector3_dot( b->xyz, dp->texMat[ 0 ].vec3() ) + dp->texMat[ 0 ][ 3 ]; t = vector3_dot( b->xyz, dp->texMat[ 1 ].vec3() ) + dp->texMat[ 1 ][ 3 ]; if ( !float_equal_epsilon( s, b->st[ 0 ], 0.01 ) || !float_equal_epsilon( t, b->st[ 1 ], 0.01 ) ) { Sys_Printf( "Bad texture matrix! (B) (%f, %f) != (%f, %f)\n", - s, t, b->st[ 0 ], b->st[ 1 ] ); + s, t, b->st[ 0 ], b->st[ 1 ] ); //% return false; } s = vector3_dot( c->xyz, dp->texMat[ 0 ].vec3() ) + dp->texMat[ 0 ][ 3 ]; t = vector3_dot( c->xyz, dp->texMat[ 1 ].vec3() ) + dp->texMat[ 1 ][ 3 ]; if ( !float_equal_epsilon( s, c->st[ 0 ], 0.01 ) || !float_equal_epsilon( t, c->st[ 1 ], 0.01 ) ) { Sys_Printf( "Bad texture matrix! (C) (%f, %f) != (%f, %f)\n", - s, t, c->st[ 0 ], c->st[ 1 ] ); + s, t, c->st[ 0 ], c->st[ 1 ] ); //% return false; } @@ -450,7 +450,7 @@ void ProcessDecals( void ){ /* planar? (nuking this optimization as it doesn't work on non-rectangular quads) */ if ( 0 && PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) && - fabs( plane3_distance_to_point( plane, dv[ 1 ]->xyz ) ) <= PLANAR_EPSILON ) { + fabs( plane3_distance_to_point( plane, dv[ 1 ]->xyz ) ) <= PLANAR_EPSILON ) { /* make a quad projector */ MakeDecalProjector( p->shaderInfo, projection, distance, 4, dv ); } @@ -697,7 +697,7 @@ static void ProjectDecalOntoPatch( decalProjector_t *dp, mapDrawSurface_t *ds ){ */ static void ProjectDecalOntoTriangles( decalProjector_t *dp, mapDrawSurface_t *ds ){ - + /* triangle surfaces without shaders don't get marks by default */ if ( ds->type == ESurfaceType::Triangles && ds->shaderInfo->shaderText == NULL ) { return; diff --git a/tools/quake3/q3map2/facebsp.cpp b/tools/quake3/q3map2/facebsp.cpp index 4ac11e10..806f198f 100644 --- a/tools/quake3/q3map2/facebsp.cpp +++ b/tools/quake3/q3map2/facebsp.cpp @@ -281,7 +281,7 @@ void BuildFaceTree_r( node_t *node, face_t *list ){ /* switch on side */ if ( side == eSideCross ) { ClipWindingEpsilonStrict( split->w, plane.plane, CLIP_EPSILON * 2, - &frontWinding, &backWinding ); /* strict; if no winding is left, we have a "virtually identical" plane and don't want to split by it */ + &frontWinding, &backWinding ); /* strict; if no winding is left, we have a "virtually identical" plane and don't want to split by it */ if ( frontWinding ) { newFace = AllocBspFace(); newFace->w = frontWinding; diff --git a/tools/quake3/q3map2/fog.cpp b/tools/quake3/q3map2/fog.cpp index d6e5387d..d483043c 100644 --- a/tools/quake3/q3map2/fog.cpp +++ b/tools/quake3/q3map2/fog.cpp @@ -640,7 +640,7 @@ int FogForBounds( const MinMax& minmax, float epsilon ){ } const Vector3 overlap( std::max( 1.f, std::min( minmax.maxs[0], fogMinmax.maxs[0] ) - std::max( minmax.mins[0], fogMinmax.mins[0] ) ), std::max( 1.f, std::min( minmax.maxs[1], fogMinmax.maxs[1] ) - std::max( minmax.mins[1], fogMinmax.mins[1] ) ), - std::max( 1.f, std::min( minmax.maxs[2], fogMinmax.maxs[2] ) - std::max( minmax.mins[2], fogMinmax.mins[2] ) ) ); + std::max( 1.f, std::min( minmax.maxs[2], fogMinmax.maxs[2] ) - std::max( minmax.mins[2], fogMinmax.mins[2] ) ) ); /* get volume */ const float volume = overlap[0] * overlap[1] * overlap[2]; diff --git a/tools/quake3/q3map2/help.cpp b/tools/quake3/q3map2/help.cpp index e59b1ae2..66dc4849 100644 --- a/tools/quake3/q3map2/help.cpp +++ b/tools/quake3/q3map2/help.cpp @@ -63,7 +63,7 @@ void HelpOptions(const char* group_name, int indentation, int width, struct Help printf("%s%26c",indent,' '); int fragment = width - printed; while ( fragment > 0 && options[i].description[j+fragment-1] != ' ') - fragment--; + fragment--; j += fwrite(options[i].description+j, sizeof(char), fragment, stdout); putchar('\n'); printed = indentation+26; diff --git a/tools/quake3/q3map2/image.cpp b/tools/quake3/q3map2/image.cpp index 487e1905..131d4669 100644 --- a/tools/quake3/q3map2/image.cpp +++ b/tools/quake3/q3map2/image.cpp @@ -181,14 +181,14 @@ static void LoadPNGBuffer( byte *buffer, int size, byte **pixels, int *width, in /* read image header chunk */ png_get_IHDR( png, info, - &w, &h, &bitDepth, &colorType, NULL, NULL, NULL ); + &w, &h, &bitDepth, &colorType, NULL, NULL, NULL ); /* the following will probably bork on certain types of png images, but hey... */ /* force indexed/gray/trans chunk to rgb */ if ( ( colorType == PNG_COLOR_TYPE_PALETTE && bitDepth <= 8 ) || - ( colorType == PNG_COLOR_TYPE_GRAY && bitDepth <= 8 ) || - png_get_valid( png, info, PNG_INFO_tRNS ) ) { + ( colorType == PNG_COLOR_TYPE_GRAY && bitDepth <= 8 ) || + png_get_valid( png, info, PNG_INFO_tRNS ) ) { png_set_expand( png ); } diff --git a/tools/quake3/q3map2/leakfile.cpp b/tools/quake3/q3map2/leakfile.cpp index a2a72496..5d4ffdf0 100644 --- a/tools/quake3/q3map2/leakfile.cpp +++ b/tools/quake3/q3map2/leakfile.cpp @@ -90,7 +90,7 @@ xmlNodePtr LeakFile( tree_t *tree ){ { s = ( p->nodes[0] == node ); if ( p->nodes[s]->occupied - && p->nodes[s]->occupied < next ) { + && p->nodes[s]->occupied < next ) { nextportal = p; nextnode = p->nodes[s]; next = nextnode->occupied; diff --git a/tools/quake3/q3map2/light.cpp b/tools/quake3/q3map2/light.cpp index 9a46a3e2..9ece3699 100644 --- a/tools/quake3/q3map2/light.cpp +++ b/tools/quake3/q3map2/light.cpp @@ -335,7 +335,7 @@ void CreateEntityLights( void ){ intensity = 300.0f; } - { /* ydnar: set light scale (sof2) */ + { /* ydnar: set light scale (sof2) */ float scale; if( e->read_keyvalue( scale, "scale" ) && scale != 0.f ) intensity *= scale; @@ -347,7 +347,7 @@ void CreateEntityLights( void ){ intensity /= numSamples; - { /* ydnar: get filter radius */ + { /* ydnar: get filter radius */ light->filterRadius = std::max( 0.f, e->floatForKey( "_filterradius", "_filteradius", "_filter" ) ); } @@ -384,7 +384,7 @@ void CreateEntityLights( void ){ e2 = FindTargetEntity( target ); if ( e2 == NULL ) { Sys_Warning( "light at (%i %i %i) has missing target\n", - (int) light->origin[ 0 ], (int) light->origin[ 1 ], (int) light->origin[ 2 ] ); + (int) light->origin[ 0 ], (int) light->origin[ 1 ], (int) light->origin[ 2 ] ); light->photons *= pointScale; } else @@ -787,7 +787,7 @@ int LightContributionToSample( trace_t *trace ){ return 0; } else if ( angle < 0.0f && - ( trace->twoSided || ( light->flags & LightFlags::Twosided ) ) ) { + ( trace->twoSided || ( light->flags & LightFlags::Twosided ) ) ) { angle = -angle; /* no deluxemap contribution from "other side" light */ @@ -1130,7 +1130,7 @@ void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], Vector3 (&c for ( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) { if ( styles[ lightmapNum ] == trace->light->style || - styles[ lightmapNum ] == LS_NONE ) { + styles[ lightmapNum ] == LS_NONE ) { break; } } @@ -1159,9 +1159,9 @@ void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], Vector3 (&c /* cheap mode */ if ( cheap && - colors[ 0 ][ 0 ] >= 255.0f && - colors[ 0 ][ 1 ] >= 255.0f && - colors[ 0 ][ 2 ] >= 255.0f ) { + colors[ 0 ][ 0 ] >= 255.0f && + colors[ 0 ][ 1 ] >= 255.0f && + colors[ 0 ][ 2 ] >= 255.0f ) { break; } } @@ -1627,9 +1627,9 @@ void TraceGrid( int num ){ #if 0 //% Sys_FPrintf( SYS_VRB, "%10d %10d %10d ", &gp->ambient[ 0 ][ 0 ], &gp->ambient[ 0 ][ 1 ], &gp->ambient[ 0 ][ 2 ] ); Sys_FPrintf( SYS_VRB, "%9d Amb: (%03.1f %03.1f %03.1f) Dir: (%03.1f %03.1f %03.1f)\n", - num, - gp->ambient[ 0 ][ 0 ], gp->ambient[ 0 ][ 1 ], gp->ambient[ 0 ][ 2 ], - gp->directed[ 0 ][ 0 ], gp->directed[ 0 ][ 1 ], gp->directed[ 0 ][ 2 ] ); + num, + gp->ambient[ 0 ][ 0 ], gp->ambient[ 0 ][ 1 ], gp->ambient[ 0 ][ 2 ], + gp->directed[ 0 ][ 0 ], gp->directed[ 0 ][ 1 ], gp->directed[ 0 ][ 2 ] ); #endif /* store direction */ @@ -1803,7 +1803,7 @@ void LightWorld( bool fastAllocate ){ RunThreadsOnIndividual( numRawGridPoints, true, TraceGrid ); inGrid = false; Sys_Printf( "%d x %d x %d = %d grid\n", - gridBounds[ 0 ], gridBounds[ 1 ], gridBounds[ 2 ], numBSPGridPoints ); + gridBounds[ 0 ], gridBounds[ 1 ], gridBounds[ 2 ], numBSPGridPoints ); /* ydnar: emit statistics on light culling */ Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled ); @@ -2344,7 +2344,7 @@ int LightMain( int argc, char **argv ){ } else if ( striEqual( argv[ i ], "-lightmapsize" ) - || striEqual( argv[ i ], "-extlmhacksize" ) ) { + || striEqual( argv[ i ], "-extlmhacksize" ) ) { const bool extlmhack = striEqual( argv[ i ], "-extlmhacksize" ); lmCustomSizeW = lmCustomSizeH = atoi( argv[ i + 1 ] ); @@ -2355,7 +2355,7 @@ int LightMain( int argc, char **argv ){ i++; /* must be a power of 2 and greater than 2 */ if ( ( ( lmCustomSizeW - 1 ) & lmCustomSizeW ) || lmCustomSizeW < 2 || - ( ( lmCustomSizeH - 1 ) & lmCustomSizeH ) || lmCustomSizeH < 2 ) { + ( ( lmCustomSizeH - 1 ) & lmCustomSizeH ) || lmCustomSizeH < 2 ) { Sys_Warning( "Lightmap size must be a power of 2, greater or equal to 2 pixels.\n" ); lmCustomSizeW = lmCustomSizeH = game->lightmapSize; } diff --git a/tools/quake3/q3map2/light_bounce.cpp b/tools/quake3/q3map2/light_bounce.cpp index e7a7955d..de44bb49 100644 --- a/tools/quake3/q3map2/light_bounce.cpp +++ b/tools/quake3/q3map2/light_bounce.cpp @@ -66,7 +66,7 @@ void RadFreeLights( void ){ */ static void RadClipWindingEpsilon( radWinding_t *in, const Vector3& normal, float dist, - float epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw ){ + float epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw ){ float *dists; EPlaneSide *sides; int counts[ 3 ]; @@ -384,7 +384,7 @@ static void RadSample( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, - float scale, float subdivide, radWinding_t *rw, clipWork_t *cw ){ + float scale, float subdivide, radWinding_t *rw, clipWork_t *cw ){ int i, style = 0; float dist, area, value; Vector3 normal, color, gradient; @@ -439,7 +439,7 @@ static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, raw /* if color gradient is too high, subdivide again */ if ( subdivide > minDiffuseSubdivide && - ( gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT ) ) { + ( gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT ) ) { RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, ( subdivide / 2.0f ), rw, cw ); return; } @@ -507,7 +507,7 @@ static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, raw /* bouncing light? */ if ( !bouncing ) { /* This is weird. This actually handles surfacelight and not - * bounces. */ + * bounces. */ /* handle first-pass lights in normal q3a style */ value = si->value; @@ -590,7 +590,7 @@ static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, raw splash->origin = normal * si->backsplashDistance + light->origin; splash->normal = -normal; - splash->dist = vector3_dot( splash->origin, splash->normal ); + splash->dist = vector3_dot( splash->origin, splash->normal ); // splash->flags |= LightFlags::Twosided; } @@ -847,8 +847,8 @@ void RadLight( int num ){ /* early outs? */ if ( scale <= 0.0f || ( si->compileFlags & C_SKY ) || si->autosprite || - ( bspShaders[ ds->shaderNum ].contentFlags & contentFlags ) || ( bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags ) || - ( si->compileFlags & compileFlags ) ) { + ( bspShaders[ ds->shaderNum ].contentFlags & contentFlags ) || ( bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags ) || + ( si->compileFlags & compileFlags ) ) { return; } @@ -922,22 +922,22 @@ void RadCreateDiffuseLights( void ){ for ( light = lights; light; light = light->next ) { fprintf( file, - "{\n" - "\"classname\" \"light\"\n" - "\"light\" \"%d\"\n" - "\"origin\" \"%.0f %.0f %.0f\"\n" - "\"_color\" \"%.3f %.3f %.3f\"\n" - "}\n", + "{\n" + "\"classname\" \"light\"\n" + "\"light\" \"%d\"\n" + "\"origin\" \"%.0f %.0f %.0f\"\n" + "\"_color\" \"%.3f %.3f %.3f\"\n" + "}\n", - (int) light->add, + (int) light->add, - light->origin[ 0 ], - light->origin[ 1 ], - light->origin[ 2 ], + light->origin[ 0 ], + light->origin[ 1 ], + light->origin[ 2 ], - light->color[ 0 ], - light->color[ 1 ], - light->color[ 2 ] ); + light->color[ 0 ], + light->color[ 1 ], + light->color[ 2 ] ); } fclose( file ); } diff --git a/tools/quake3/q3map2/light_trace.cpp b/tools/quake3/q3map2/light_trace.cpp index 5bf7a2d1..1c839c64 100644 --- a/tools/quake3/q3map2/light_trace.cpp +++ b/tools/quake3/q3map2/light_trace.cpp @@ -128,9 +128,9 @@ static int AddTraceInfo( traceInfo_t *ti ){ for ( num = firstTraceInfo; num < numTraceInfos; num++ ) { if ( traceInfos[ num ].si == ti->si && - traceInfos[ num ].surfaceNum == ti->surfaceNum && - traceInfos[ num ].castShadows == ti->castShadows && - traceInfos[ num ].skipGrid == ti->skipGrid ) { + traceInfos[ num ].surfaceNum == ti->surfaceNum && + traceInfos[ num ].castShadows == ti->castShadows && + traceInfos[ num ].skipGrid == ti->skipGrid ) { return num; } } @@ -230,8 +230,8 @@ static int AddTraceTriangle( traceTriangle_t *tt ){ } /* find vectors for two edges sharing the first vert */ - tt->edge1 = tt->v[ 1 ].xyz - tt->v[ 0 ].xyz; - tt->edge2 = tt->v[ 2 ].xyz - tt->v[ 0 ].xyz; + tt->edge1 = tt->v[ 1 ].xyz - tt->v[ 0 ].xyz; + tt->edge2 = tt->v[ 2 ].xyz - tt->v[ 0 ].xyz; /* add the triangle */ memcpy( &traceTriangles[ num ], tt, sizeof( *traceTriangles ) ); @@ -856,7 +856,7 @@ static void PopulateWithBSPModel( bspModel_t *model, const Matrix4& transform ){ /* some surfaces in the bsp might have been tagged as nodraw, with a bogus shader */ if ( ( bspShaders[ ds->shaderNum ].contentFlags & noDrawContentFlags ) || - ( bspShaders[ ds->shaderNum ].surfaceFlags & noDrawSurfaceFlags ) ) { + ( bspShaders[ ds->shaderNum ].surfaceFlags & noDrawSurfaceFlags ) ) { continue; } @@ -865,8 +865,8 @@ static void PopulateWithBSPModel( bspModel_t *model, const Matrix4& transform ){ continue; } if ( ( info->si->compileFlags & C_TRANSLUCENT ) && - !( info->si->compileFlags & C_ALPHASHADOW ) && - !( info->si->compileFlags & C_LIGHTFILTER ) ) { + !( info->si->compileFlags & C_ALPHASHADOW ) && + !( info->si->compileFlags & C_LIGHTFILTER ) ) { continue; } @@ -1042,8 +1042,8 @@ static void PopulateWithPicoModel( int castShadows, picoModel_t *model, const Ma continue; } if ( ( ti.si->compileFlags & C_TRANSLUCENT ) && - !( ti.si->compileFlags & C_ALPHASHADOW ) && - !( ti.si->compileFlags & C_LIGHTFILTER ) ) { + !( ti.si->compileFlags & C_ALPHASHADOW ) && + !( ti.si->compileFlags & C_LIGHTFILTER ) ) { continue; } @@ -1119,7 +1119,7 @@ static void PopulateTraceNodes( void ){ /* get "angle" (yaw) or "angles" (pitch yaw roll), store as (roll pitch yaw) */ Vector3 angles( 0 ); if ( !e->read_keyvalue( value, "angles" ) || - 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) + 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) e->read_keyvalue( angles[ 2 ], "angle" ); /* set transform matrix (thanks spog) */ @@ -1152,11 +1152,8 @@ static void PopulateTraceNodes( void ){ /* external model */ default: - { - model = LoadModel( value, e->intForKey( "_frame", "frame" ) ); - if ( model == NULL ) { - continue; - } + model = LoadModel( value, e->intForKey( "_frame", "frame" ) ); + if ( model != NULL ) { PopulateWithPicoModel( castShadows, model, transform ); } continue; @@ -1271,7 +1268,7 @@ void SetupTraceNodes( void ){ tw = &traceWindings[ i ]; for ( j = 0; j < tw->numVerts + 1; j++ ) fprintf( file, "%f %f %f\n", - tw->v[ j % tw->numVerts ].xyz[ 0 ], tw->v[ j % tw->numVerts ].xyz[ 1 ], tw->v[ j % tw->numVerts ].xyz[ 2 ] ); + tw->v[ j % tw->numVerts ].xyz[ 0 ], tw->v[ j % tw->numVerts ].xyz[ 1 ], tw->v[ j % tw->numVerts ].xyz[ 2 ] ); } /* close it */ @@ -1403,7 +1400,7 @@ bool TraceTriangle( traceInfo_t *ti, traceTriangle_t *tt, trace_t *trace ){ /* most surfaces are completely opaque */ if ( !( si->compileFlags & ( C_ALPHASHADOW | C_LIGHTFILTER ) ) || - si->lightImage == NULL || si->lightImage->pixels == NULL ) { + si->lightImage == NULL || si->lightImage->pixels == NULL ) { trace->hit = trace->origin + trace->direction * depth; trace->color.set( 0 ); trace->opaque = true; @@ -1415,7 +1412,7 @@ bool TraceTriangle( traceInfo_t *ti, traceTriangle_t *tt, trace_t *trace ){ /* try to avoid double shadows near triangle seams */ if ( u < -ASLF_EPSILON || u > ( 1.0f + ASLF_EPSILON ) || - v < -ASLF_EPSILON || ( u + v ) > ( 1.0f + ASLF_EPSILON ) ) { + v < -ASLF_EPSILON || ( u + v ) > ( 1.0f + ASLF_EPSILON ) ) { return false; } @@ -1665,8 +1662,8 @@ void TraceLine( trace_t *trace ){ /* testall means trace through sky */ if ( trace->testAll && trace->numTestNodes < MAX_TRACE_TEST_NODES && - trace->compileFlags & C_SKY && - ( trace->numSurfaces == 0 || surfaceInfos[ trace->surfaces[ 0 ] ].childSurfaceNum < 0 ) ) { + trace->compileFlags & C_SKY && + ( trace->numSurfaces == 0 || surfaceInfos[ trace->surfaces[ 0 ] ].childSurfaceNum < 0 ) ) { //% trace->testNodes[ trace->numTestNodes++ ] = skyboxNodeNum; TraceLine_r( skyboxNodeNum, trace->origin, trace->end, trace ); } diff --git a/tools/quake3/q3map2/light_ydnar.cpp b/tools/quake3/q3map2/light_ydnar.cpp index 14b8fe34..81ea782f 100644 --- a/tools/quake3/q3map2/light_ydnar.cpp +++ b/tools/quake3/q3map2/light_ydnar.cpp @@ -1008,9 +1008,9 @@ void MapRawLightmap( int rawLightmapNum ){ #if 0 if ( lm->plane ) { Sys_Printf( "Planar patch: [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f]\n", - lm->plane[ 0 ], lm->plane[ 1 ], lm->plane[ 2 ], - lm->vecs[ 0 ][ 0 ], lm->vecs[ 0 ][ 1 ], lm->vecs[ 0 ][ 2 ], - lm->vecs[ 1 ][ 0 ], lm->vecs[ 1 ][ 1 ], lm->vecs[ 1 ][ 2 ] ); + lm->plane[ 0 ], lm->plane[ 1 ], lm->plane[ 2 ], + lm->vecs[ 0 ][ 0 ], lm->vecs[ 0 ][ 1 ], lm->vecs[ 0 ][ 2 ], + lm->vecs[ 1 ][ 0 ], lm->vecs[ 1 ][ 1 ], lm->vecs[ 1 ][ 2 ] ); } #endif @@ -1258,11 +1258,11 @@ void MapRawLightmap( int rawLightmapNum ){ /* report bogus origin */ Sys_Printf( "%6d [%2d,%2d] (%4d): XYZ(%+4.1f %+4.1f %+4.1f) LO(%+4.1f %+4.1f %+4.1f) HI(%+4.1f %+4.1f %+4.1f) <%3.0f>\n", - rawLightmapNum, x, y, cluster, - origin[ 0 ], origin[ 1 ], origin[ 2 ], - minmax.mins[ 0 ], minmax.mins[ 1 ], minmax.mins[ 2 ], - minmax.maxs[ 0 ], minmax.maxs[ 1 ], minmax.maxs[ 2 ], - luxel.count ); + rawLightmapNum, x, y, cluster, + origin[ 0 ], origin[ 1 ], origin[ 2 ], + minmax.mins[ 0 ], minmax.mins[ 1 ], minmax.mins[ 2 ], + minmax.maxs[ 0 ], minmax.maxs[ 1 ], minmax.maxs[ 2 ], + luxel.count ); } } #endif @@ -1721,8 +1721,8 @@ static void SubsampleRawLuxel_r( rawLightmap_t *lm, trace_t *trace, const Vector /* subsample further? */ if ( ( lightLuxel.count + 1.0f ) < lightSamples && - ( total[ 0 ] > 4.0f || total[ 1 ] > 4.0f || total[ 2 ] > 4.0f ) && - lighted != 0 && lighted != mapped ) { + ( total[ 0 ] > 4.0f || total[ 1 ] > 4.0f || total[ 2 ] > 4.0f ) && + lighted != 0 && lighted != mapped ) { for ( b = 0; b < 4; b++ ) { if ( cluster[ b ] < 0 ) { @@ -2009,7 +2009,7 @@ void IlluminateRawLightmap( int rawLightmapNum ){ for ( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) { if ( lm->styles[ lightmapNum ] == trace.light->style || - lm->styles[ lightmapNum ] == LS_NONE ) { + lm->styles[ lightmapNum ] == LS_NONE ) { break; } } @@ -2430,9 +2430,9 @@ void IlluminateRawLightmap( int rawLightmapNum ){ filterColor = false; filterDir = false; if ( cluster < 0 || - ( lm->splotchFix && ( luxel.value[ 0 ] <= ambientColor[ 0 ] - || luxel.value[ 1 ] <= ambientColor[ 1 ] - || luxel.value[ 2 ] <= ambientColor[ 2 ] ) ) ) { + ( lm->splotchFix && ( luxel.value[ 0 ] <= ambientColor[ 0 ] + || luxel.value[ 1 ] <= ambientColor[ 1 ] + || luxel.value[ 2 ] <= ambientColor[ 2 ] ) ) ) { filterColor = true; } @@ -2467,7 +2467,7 @@ void IlluminateRawLightmap( int rawLightmapNum ){ /* ignore unmapped/unlit luxels */ if ( lm->getSuperCluster( sx, sy ) < 0 || luxel2.count == 0.0f || - ( lm->splotchFix && VectorCompare( luxel2.value, ambientColor ) ) ) { + ( lm->splotchFix && VectorCompare( luxel2.value, ambientColor ) ) ) { continue; } @@ -2738,7 +2738,6 @@ void IlluminateVertexes( int num ){ colors[ lightmapNum ] += floodColor; /* store */ - getRadVertexLuxel( lightmapNum, ds->firstVert + i ) = colors[ lightmapNum ]; } diff --git a/tools/quake3/q3map2/lightmaps_ydnar.cpp b/tools/quake3/q3map2/lightmaps_ydnar.cpp index 7cc336ad..dd7987fa 100644 --- a/tools/quake3/q3map2/lightmaps_ydnar.cpp +++ b/tools/quake3/q3map2/lightmaps_ydnar.cpp @@ -233,7 +233,7 @@ int ImportLightmapsMain( int argc, char **argv ){ } if ( width != game->lightmapSize || height != game->lightmapSize ) { Sys_Warning( "Image %s is not the right size (%d, %d) != (%d, %d)\n", - filename, width, height, game->lightmapSize, game->lightmapSize ); + filename, width, height, game->lightmapSize, game->lightmapSize ); } /* copy the pixels */ @@ -583,13 +583,13 @@ bool AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ){ /* match identical attributes */ if ( info->sampleSize != lm->sampleSize || - info->entityNum != lm->entityNum || - info->recvShadows != lm->recvShadows || - info->si->lmCustomWidth != lm->customWidth || - info->si->lmCustomHeight != lm->customHeight || - info->si->lmBrightness != lm->brightness || - info->si->lmFilterRadius != lm->filterRadius || - info->si->splotchFix != lm->splotchFix ) { + info->entityNum != lm->entityNum || + info->recvShadows != lm->recvShadows || + info->si->lmCustomWidth != lm->customWidth || + info->si->lmCustomHeight != lm->customHeight || + info->si->lmBrightness != lm->brightness || + info->si->lmFilterRadius != lm->filterRadius || + info->si->splotchFix != lm->splotchFix ) { return false; } @@ -608,7 +608,7 @@ bool AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ){ if( !vector3_equal_epsilon( info->plane->normal(), lm->plane->normal(), EQUAL_EPSILON ) || !float_equal_epsilon( info->plane->dist(), lm->plane->dist(), EQUAL_EPSILON ) ){ return false; - } + } } /* debug code hacking */ @@ -626,7 +626,7 @@ bool AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ){ /* check to see if this is a non-planar patch */ if ( ds->surfaceType == MST_PATCH && - lm->axis == g_vector3_identity ) { + lm->axis == g_vector3_identity ) { return AddPatchToRawLightmap( num, lm ); } @@ -650,25 +650,25 @@ bool AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ){ if ( sampleSize != lm->sampleSize && lmLimitSize == 0 ){ if ( debugSampleSize == 1 || lm->customWidth > 128 ){ Sys_FPrintf( SYS_WRN | SYS_VRBflag, "WARNING: surface at (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) too large for desired samplesize/lightmapsize/lightmapscale combination, increased samplesize from %d to %d\n", - info->minmax.mins[0], - info->minmax.mins[1], - info->minmax.mins[2], - info->minmax.maxs[0], - info->minmax.maxs[1], - info->minmax.maxs[2], - lm->sampleSize, - (int) sampleSize ); + info->minmax.mins[0], + info->minmax.mins[1], + info->minmax.mins[2], + info->minmax.maxs[0], + info->minmax.maxs[1], + info->minmax.maxs[2], + lm->sampleSize, + (int) sampleSize ); } else if ( debugSampleSize == 0 ){ Sys_FPrintf( SYS_WRN | SYS_VRBflag, "WARNING: surface at (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) too large for desired samplesize/lightmapsize/lightmapscale combination, increased samplesize from %d to %d\n", - info->minmax.mins[0], - info->minmax.mins[1], - info->minmax.mins[2], - info->minmax.maxs[0], - info->minmax.maxs[1], - info->minmax.maxs[2], - lm->sampleSize, - (int) sampleSize ); + info->minmax.mins[0], + info->minmax.mins[1], + info->minmax.mins[2], + info->minmax.maxs[0], + info->minmax.maxs[1], + info->minmax.maxs[2], + lm->sampleSize, + (int) sampleSize ); debugSampleSize--; } else{ @@ -748,7 +748,7 @@ bool AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ){ if ( s > (float) lm->w || t > (float) lm->h ) { Sys_FPrintf( SYS_WRN | SYS_VRBflag, "WARNING: Lightmap texture coords out of range: S %1.4f > %3d || T %1.4f > %3d\n", - s, lm->w, t, lm->h ); + s, lm->w, t, lm->h ); } } } @@ -1046,9 +1046,9 @@ void SetupSurfaceLightmaps( void ){ /* determine if surface requires a lightmap */ if ( ds->surfaceType == MST_TRIANGLE_SOUP || - ds->surfaceType == MST_FOLIAGE || - ( info->si->compileFlags & C_VERTEXLIT ) || - nolm ) { + ds->surfaceType == MST_FOLIAGE || + ( info->si->compileFlags & C_VERTEXLIT ) || + nolm ) { numSurfsVertexLit++; } else @@ -1184,7 +1184,7 @@ void SetupSurfaceLightmaps( void ){ void StitchSurfaceLightmaps( void ){ int i, j, x, y, x2, y2, - numStitched, numCandidates, numLuxels, f, fOld, start; + numStitched, numCandidates, numLuxels, f, fOld, start; rawLightmap_t *lm, *a, *b, *c[ MAX_STITCH_CANDIDATES ]; float sampleSize, totalColor; @@ -1340,15 +1340,15 @@ void StitchSurfaceLightmaps( void ){ static bool CompareBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bNum ){ /* styled lightmaps will never be collapsed to non-styled lightmaps when there is _minlight */ if ( minLight != g_vector3_identity && - ( aNum == 0 ) != ( bNum == 0 ) ) { + ( aNum == 0 ) != ( bNum == 0 ) ) { return false; } /* basic tests */ if ( a->customWidth != b->customWidth || a->customHeight != b->customHeight || - a->brightness != b->brightness || - a->solid[ aNum ] != b->solid[ bNum ] || - a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) { + a->brightness != b->brightness || + a->solid[ aNum ] != b->solid[ bNum ] || + a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) { return false; } @@ -1423,9 +1423,9 @@ static bool MergeBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bN /* basic tests */ if ( a->customWidth != b->customWidth || a->customHeight != b->customHeight || - a->brightness != b->brightness || - a->solid[ aNum ] != b->solid[ bNum ] || - a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) { + a->brightness != b->brightness || + a->solid[ aNum ] != b->solid[ bNum ] || + a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) { return false; } @@ -1668,8 +1668,8 @@ static bool ApproximateLightmap( rawLightmap_t *lm ){ /* assume that surfaces whose bounding boxes is smaller than 2x samplesize will be forced to vertex */ if ( ( info->minmax.maxs[ 0 ] - info->minmax.mins[ 0 ] ) <= ( 2.0f * info->sampleSize ) && - ( info->minmax.maxs[ 1 ] - info->minmax.mins[ 1 ] ) <= ( 2.0f * info->sampleSize ) && - ( info->minmax.maxs[ 2 ] - info->minmax.mins[ 2 ] ) <= ( 2.0f * info->sampleSize ) ) { + ( info->minmax.maxs[ 1 ] - info->minmax.mins[ 1 ] ) <= ( 2.0f * info->sampleSize ) && + ( info->minmax.maxs[ 2 ] - info->minmax.mins[ 2 ] ) <= ( 2.0f * info->sampleSize ) ) { info->approximated = true; numSurfsVertexForced++; continue; @@ -1913,7 +1913,7 @@ static void FindOutLightmaps( rawLightmap_t *lm, bool fastAllocate ){ /* don't store non-custom raw lightmaps on custom bsp lightmaps */ if ( olm->customWidth != lm->customWidth || - olm->customHeight != lm->customHeight ) { + olm->customHeight != lm->customHeight ) { continue; } @@ -1989,7 +1989,7 @@ static void FindOutLightmaps( rawLightmap_t *lm, bool fastAllocate ){ /* don't store non-custom raw lightmaps on custom bsp lightmaps */ if ( olm->customWidth != lm->customWidth || - olm->customHeight != lm->customHeight ) { + olm->customHeight != lm->customHeight ) { continue; } @@ -2643,7 +2643,7 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ /* check solid color */ sample = colorMinmax.maxs - colorMinmax.mins; if ( ( sample[ 0 ] <= SOLID_EPSILON && sample[ 1 ] <= SOLID_EPSILON && sample[ 2 ] <= SOLID_EPSILON ) || - ( lm->w <= 2 && lm->h <= 2 ) ) { /* small lightmaps get forced to solid color */ + ( lm->w <= 2 && lm->h <= 2 ) ) { /* small lightmaps get forced to solid color */ /* set to solid */ lm->solidColor[ lightmapNum ] = colorMinmax.mins; lm->solid[ lightmapNum ] = true; @@ -2844,7 +2844,7 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ { /* early outs */ if ( lm->bspLuxels[ lightmapNum ] == NULL || - lm->twins[ lightmapNum ] != NULL ) { + lm->twins[ lightmapNum ] != NULL ) { continue; } @@ -2859,7 +2859,7 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ { /* early outs */ if ( lm2->bspLuxels[ lightmapNum2 ] == NULL || - lm2->twins[ lightmapNum2 ] != NULL ) { + lm2->twins[ lightmapNum2 ] != NULL ) { continue; } @@ -3263,35 +3263,35 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ /* create additional stage */ if ( lmxy.x() == 0.0f && lmxy.y() == 0.0f ) { - sprintf( styleStage, "\t{\n" - "\t\tmap %s\n" /* lightmap */ - "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" - "%s" /* depthFunc equal */ - "%s" /* rgbGen */ - "%s" /* alphaGen */ - "\t\ttcGen lightmap\n" - "\t}\n", - lightmapName, - ( dfEqual ? "\t\tdepthFunc equal\n" : "" ), - rgbGen, - alphaGen ); + sprintf( styleStage, "\t{\n" + "\t\tmap %s\n" /* lightmap */ + "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" + "%s" /* depthFunc equal */ + "%s" /* rgbGen */ + "%s" /* alphaGen */ + "\t\ttcGen lightmap\n" + "\t}\n", + lightmapName, + ( dfEqual ? "\t\tdepthFunc equal\n" : "" ), + rgbGen, + alphaGen ); } else { - sprintf( styleStage, "\t{\n" - "\t\tmap %s\n" /* lightmap */ - "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" - "%s" /* depthFunc equal */ - "%s" /* rgbGen */ - "%s" /* alphaGen */ - "\t\ttcGen lightmap\n" - "\t\ttcMod transform 1 0 0 1 %1.5f %1.5f\n" /* st offset */ - "\t}\n", - lightmapName, - ( dfEqual ? "\t\tdepthFunc equal\n" : "" ), - rgbGen, - alphaGen, - lmxy.x(), lmxy.y() ); + sprintf( styleStage, "\t{\n" + "\t\tmap %s\n" /* lightmap */ + "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" + "%s" /* depthFunc equal */ + "%s" /* rgbGen */ + "%s" /* alphaGen */ + "\t\ttcGen lightmap\n" + "\t\ttcMod transform 1 0 0 1 %1.5f %1.5f\n" /* st offset */ + "\t}\n", + lightmapName, + ( dfEqual ? "\t\tdepthFunc equal\n" : "" ), + rgbGen, + alphaGen, + lmxy.x(), lmxy.y() ); } @@ -3320,7 +3320,7 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ /* devise a custom shader for this surface (fixme: make this work with light styles) */ else if ( olm != NULL && lm != NULL && !externalLightmaps && - ( olm->customWidth != game->lightmapSize || olm->customHeight != game->lightmapSize ) ) { + ( olm->customWidth != game->lightmapSize || olm->customHeight != game->lightmapSize ) ) { /* get output lightmap */ olm = &outLightmaps[ lm->outLightmapNums[ 0 ] ]; @@ -3354,8 +3354,8 @@ void StoreSurfaceLightmaps( bool fastAllocate ){ /* calc num stored */ numStored = numBSPLightBytes / 3; efficiency = ( numStored <= 0 ) - ? 0 - : (float) numUsed / (float) numStored; + ? 0 + : (float) numUsed / (float) numStored; /* print stats */ Sys_Printf( "%9d luxels used\n", numUsed ); diff --git a/tools/quake3/q3map2/main.cpp b/tools/quake3/q3map2/main.cpp index d65b6086..fcffaa6b 100644 --- a/tools/quake3/q3map2/main.cpp +++ b/tools/quake3/q3map2/main.cpp @@ -83,7 +83,7 @@ int main( int argc, char **argv ){ { /* -help */ if ( striEqual( argv[ i ], "-h" ) || striEqual( argv[ i ], "--help" ) - || striEqual( argv[ i ], "-help" ) ) { + || striEqual( argv[ i ], "-help" ) ) { HelpMain( ( i + 1 < argc ) ? argv[ i + 1 ] : NULL ); return 0; } @@ -183,7 +183,7 @@ int main( int argc, char **argv ){ /* check if we have enough options left to attempt something */ if ( argc < 2 ) { - Error( "Usage: %s [general options] [options] mapfile\n%s -help for help", argv[ 0 ] , argv[ 0 ] ); + Error( "Usage: %s [general options] [options] mapfile\n%s -help for help", argv[ 0 ], argv[ 0 ] ); } /* fixaas */ diff --git a/tools/quake3/q3map2/map.cpp b/tools/quake3/q3map2/map.cpp index cc942b06..09ac5df0 100644 --- a/tools/quake3/q3map2/map.cpp +++ b/tools/quake3/q3map2/map.cpp @@ -65,9 +65,9 @@ bool PlaneEqual( const plane_t& p, const Plane3f& plane ){ // consistent with the true meaning of "epsilon", and also because other // parts of the code uses this inequality. if ( ( p.dist() == plane.dist() || fabs( p.dist() - plane.dist() ) < de ) && - ( p.normal()[0] == plane.normal()[0] || fabs( p.normal()[0] - plane.normal()[0] ) < ne ) && - ( p.normal()[1] == plane.normal()[1] || fabs( p.normal()[1] - plane.normal()[1] ) < ne ) && - ( p.normal()[2] == plane.normal()[2] || fabs( p.normal()[2] - plane.normal()[2] ) < ne ) ) { + ( p.normal()[0] == plane.normal()[0] || fabs( p.normal()[0] - plane.normal()[0] ) < ne ) && + ( p.normal()[1] == plane.normal()[1] || fabs( p.normal()[1] - plane.normal()[1] ) < ne ) && + ( p.normal()[2] == plane.normal()[2] || fabs( p.normal()[2] - plane.normal()[2] ) < ne ) ) { return true; } @@ -611,7 +611,7 @@ void AddBrushBevels( void ){ } #else if ( ( dir > 0 && mapplanes[ s->planenum ].normal()[ axis ] == 1.0f ) || - ( dir < 0 && mapplanes[ s->planenum ].normal()[ axis ] == -1.0f ) ) { + ( dir < 0 && mapplanes[ s->planenum ].normal()[ axis ] == -1.0f ) ) { break; } #endif @@ -818,11 +818,11 @@ brush_t *FinishBrush( bool noCollapseGroups ){ after the entire entity is parsed, the planenums and texinfos will be adjusted for the origin brush */ if ( buildBrush->compileFlags & C_ORIGIN ) { Sys_Printf( "Entity %i (%s), Brush %i: origin brush detected\n", - mapEnt->mapEntityNum, mapEnt->classname(), entitySourceBrushes ); + mapEnt->mapEntityNum, mapEnt->classname(), entitySourceBrushes ); if ( entities.size() == 1 ) { Sys_FPrintf( SYS_WRN, "Entity %i, Brush %i: origin brushes not allowed in world\n", - mapEnt->mapEntityNum, entitySourceBrushes ); + mapEnt->mapEntityNum, entitySourceBrushes ); return NULL; } @@ -872,8 +872,8 @@ brush_t *FinishBrush( bool noCollapseGroups ){ /* link colorMod volume brushes to the entity directly */ if ( b->contentShader != NULL && - b->contentShader->colorMod != NULL && - b->contentShader->colorMod->type == EColorMod::Volume ) { + b->contentShader->colorMod != NULL && + b->contentShader->colorMod->type == EColorMod::Volume ) { b->nextColorModBrush = mapEnt->colorModBrushes; mapEnt->colorModBrushes = b; } @@ -1597,8 +1597,8 @@ static bool ParseMapEntity( bool onlyLights, bool noCollapseGroups ){ /* conformance check */ if ( !strEqual( token, "{" ) ) { Sys_Warning( "ParseEntity: { not found, found %s on line %d - last entity was at: <%4.2f, %4.2f, %4.2f>...\n" - "Continuing to process map, but resulting BSP may be invalid.\n", - token, scriptline, entities.back().origin[ 0 ], entities.back().origin[ 1 ], entities.back().origin[ 2 ] ); + "Continuing to process map, but resulting BSP may be invalid.\n", + token, scriptline, entities.back().origin[ 0 ], entities.back().origin[ 1 ], entities.back().origin[ 2 ] ); return false; } @@ -1617,7 +1617,7 @@ static bool ParseMapEntity( bool onlyLights, bool noCollapseGroups ){ /* get initial token */ if ( !GetToken( true ) ) { Sys_Warning( "ParseEntity: EOF without closing brace\n" - "Continuing to process map, but resulting BSP may be invalid.\n" ); + "Continuing to process map, but resulting BSP may be invalid.\n" ); return false; } @@ -1699,7 +1699,7 @@ static bool ParseMapEntity( bool onlyLights, bool noCollapseGroups ){ shaderInfo_t *celShader; const char *value; if( mapEnt->read_keyvalue( value, "_celshader" ) || - entities[ 0 ].read_keyvalue( value, "_celshader" ) ){ + entities[ 0 ].read_keyvalue( value, "_celshader" ) ){ celShader = ShaderInfoForShader( String64()( "textures/", value ) ); Sys_Printf( "Entity %d (%s) has cel shader %s\n", mapEnt->mapEntityNum, classname, celShader->shader.c_str() ); } @@ -1842,8 +1842,8 @@ void LoadMapFile( char *filename, bool onlyLights, bool noCollapseGroups ){ Sys_FPrintf( SYS_VRB, "%9d planes\n", nummapplanes ); Sys_Printf( "%9d areaportals\n", c_areaportals ); Sys_Printf( "Size: %5.0f, %5.0f, %5.0f to %5.0f, %5.0f, %5.0f\n", - g_mapMinmax.mins[0], g_mapMinmax.mins[1], g_mapMinmax.mins[2], - g_mapMinmax.maxs[0], g_mapMinmax.maxs[1], g_mapMinmax.maxs[2] ); + g_mapMinmax.mins[0], g_mapMinmax.mins[1], g_mapMinmax.mins[2], + g_mapMinmax.maxs[0], g_mapMinmax.maxs[1], g_mapMinmax.maxs[2] ); /* write bogus map */ if ( fakemap ) { diff --git a/tools/quake3/q3map2/mesh.cpp b/tools/quake3/q3map2/mesh.cpp index 0985a1b8..154a78db 100644 --- a/tools/quake3/q3map2/mesh.cpp +++ b/tools/quake3/q3map2/mesh.cpp @@ -99,9 +99,9 @@ void PrintMesh( mesh_t *m ) { for ( i = 0 ; i < m->height ; i++ ) { for ( j = 0 ; j < m->width ; j++ ) { Sys_Printf( "(%5.2f %5.2f %5.2f) " - , m->verts[i * m->width + j].xyz[0] - , m->verts[i * m->width + j].xyz[1] - , m->verts[i * m->width + j].xyz[2] ); + , m->verts[i * m->width + j].xyz[0] + , m->verts[i * m->width + j].xyz[1] + , m->verts[i * m->width + j].xyz[2] ); } Sys_Printf( "\n" ); } @@ -349,7 +349,7 @@ mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ){ // if the span length is too long, force a subdivision if ( vector3_length( prevxyz ) > minLength - || vector3_length( nextxyz ) > minLength ) { + || vector3_length( nextxyz ) > minLength ) { break; } @@ -398,7 +398,7 @@ mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ){ // if the span length is too long, force a subdivision if ( vector3_length( prevxyz ) > minLength - || vector3_length( nextxyz ) > minLength ) { + || vector3_length( nextxyz ) > minLength ) { break; } // see if this midpoint is off far enough to subdivide diff --git a/tools/quake3/q3map2/minimap.cpp b/tools/quake3/q3map2/minimap.cpp index b14b75d6..81d4651c 100644 --- a/tools/quake3/q3map2/minimap.cpp +++ b/tools/quake3/q3map2/minimap.cpp @@ -165,9 +165,9 @@ static void MiniMapRandomlySupersampled( int y ){ { RandomVector2f( uv ); thisval = MiniMapSample( - xmin + ( uv[0] + 0.5 ) * dx, /* exaggerated random pattern for better results */ - ymin + ( uv[1] + 0.5 ) * dy /* exaggerated random pattern for better results */ - ); + xmin + ( uv[0] + 0.5 ) * dx, /* exaggerated random pattern for better results */ + ymin + ( uv[1] + 0.5 ) * dy /* exaggerated random pattern for better results */ + ); val += thisval; } val /= minimap.samples * minimap.size[2]; @@ -190,9 +190,9 @@ static void MiniMapSupersampled( int y ){ for ( i = 0; i < minimap.samples; ++i ) { float thisval = MiniMapSample( - xmin + minimap.sample_offsets[2 * i + 0] * dx, - ymin + minimap.sample_offsets[2 * i + 1] * dy - ); + xmin + minimap.sample_offsets[2 * i + 0] * dx, + ymin + minimap.sample_offsets[2 * i + 1] * dy + ); val += thisval; } val /= minimap.samples * minimap.size[2]; diff --git a/tools/quake3/q3map2/model.cpp b/tools/quake3/q3map2/model.cpp index 815ca0b7..74aa643e 100644 --- a/tools/quake3/q3map2/model.cpp +++ b/tools/quake3/q3map2/model.cpp @@ -102,8 +102,8 @@ picoModel_t *FindModel( const char *name, int frame ){ for ( i = 0; i < MAX_MODELS; i++ ) { if ( picoModels[ i ] != NULL && - strEqual( PicoGetModelName( picoModels[ i ] ), name ) && - PicoGetModelFrameNum( picoModels[ i ] ) == frame ) { + strEqual( PicoGetModelName( picoModels[ i ] ), name ) && + PicoGetModelFrameNum( picoModels[ i ] ) == frame ) { return picoModels[ i ]; } } @@ -475,26 +475,26 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor /* ydnar: giant hack land: generate clipping brushes for model triangles */ if ( ( si->clipModel && !( spf ) ) || //default CLIPMODEL - ( ( spawnFlags & 8090 ) == 2 ) || //default CLIPMODEL - ( spf == 8 ) || //EXTRUDE_FACE_NORMALS - ( spf == 16 ) || //EXTRUDE_TERRAIN - ( spf == 128 ) || //EXTRUDE_VERTEX_NORMALS - ( spf == 256 ) || //PYRAMIDAL_CLIP - ( spf == 512 ) || //EXTRUDE_DOWNWARDS - ( spf == 1024 ) || //EXTRUDE_UPWARDS - ( spf == 4096 ) || //default CLIPMODEL + AXIAL_BACKPLANE - ( spf == 264 ) || //EXTRUDE_FACE_NORMALS+PYRAMIDAL_CLIP (extrude 45) - ( spf == 2064 ) || //EXTRUDE_TERRAIN+MAX_EXTRUDE - ( spf == 4112 ) || //EXTRUDE_TERRAIN+AXIAL_BACKPLANE - ( spf == 384 ) || //EXTRUDE_VERTEX_NORMALS + PYRAMIDAL_CLIP - vertex normals + don't check for sides, sticking outwards - ( spf == 4352 ) || //PYRAMIDAL_CLIP+AXIAL_BACKPLANE - ( spf == 1536 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS - ( spf == 2560 ) || //EXTRUDE_DOWNWARDS+MAX_EXTRUDE - ( spf == 4608 ) || //EXTRUDE_DOWNWARDS+AXIAL_BACKPLANE - ( spf == 3584 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+MAX_EXTRUDE - ( spf == 5632 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+AXIAL_BACKPLANE - ( spf == 3072 ) || //EXTRUDE_UPWARDS+MAX_EXTRUDE - ( spf == 5120 ) ){ //EXTRUDE_UPWARDS+AXIAL_BACKPLANE + ( ( spawnFlags & 8090 ) == 2 ) || //default CLIPMODEL + ( spf == 8 ) || //EXTRUDE_FACE_NORMALS + ( spf == 16 ) || //EXTRUDE_TERRAIN + ( spf == 128 ) || //EXTRUDE_VERTEX_NORMALS + ( spf == 256 ) || //PYRAMIDAL_CLIP + ( spf == 512 ) || //EXTRUDE_DOWNWARDS + ( spf == 1024 ) || //EXTRUDE_UPWARDS + ( spf == 4096 ) || //default CLIPMODEL + AXIAL_BACKPLANE + ( spf == 264 ) || //EXTRUDE_FACE_NORMALS+PYRAMIDAL_CLIP (extrude 45) + ( spf == 2064 ) || //EXTRUDE_TERRAIN+MAX_EXTRUDE + ( spf == 4112 ) || //EXTRUDE_TERRAIN+AXIAL_BACKPLANE + ( spf == 384 ) || //EXTRUDE_VERTEX_NORMALS + PYRAMIDAL_CLIP - vertex normals + don't check for sides, sticking outwards + ( spf == 4352 ) || //PYRAMIDAL_CLIP+AXIAL_BACKPLANE + ( spf == 1536 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS + ( spf == 2560 ) || //EXTRUDE_DOWNWARDS+MAX_EXTRUDE + ( spf == 4608 ) || //EXTRUDE_DOWNWARDS+AXIAL_BACKPLANE + ( spf == 3584 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+MAX_EXTRUDE + ( spf == 5632 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+AXIAL_BACKPLANE + ( spf == 3072 ) || //EXTRUDE_UPWARDS+MAX_EXTRUDE + ( spf == 5120 ) ){ //EXTRUDE_UPWARDS+AXIAL_BACKPLANE Vector3 points[ 4 ], cnt, bestNormal, nrm, Vnorm[3], Enorm[3]; Plane3f plane, reverse, p[3]; double normalEpsilon_save; @@ -654,7 +654,7 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor const double lengthsSquared = vector3_length_squared( d1 ) * vector3_length_squared( d2 ); if ( lengthsSquared == 0 || fabs( vector3_length_squared( normaL ) / lengthsSquared ) < 1e-8 ) { Sys_Warning( "triangle (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) of %s was not autoclipped: points on line\n", - points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); + points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); continue; } } @@ -712,7 +712,7 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor currdist = reverse.dist() - vector3_dot( reverse.normal(), points[ (j+2)%3 ] ); currangle = vector3_dot( reverse.normal(), plane.normal() ); if ( ( ( currdist > 0.1 ) && ( currdist < bestdist ) && ( currangle < 0 ) ) || - ( ( currangle >= 0 ) && ( currangle <= bestangle ) ) ){ + ( ( currangle >= 0 ) && ( currangle <= bestangle ) ) ){ bestangle = currangle; if ( currangle < 0 ) bestdist = currdist; p[j] = reverse; @@ -758,19 +758,19 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor } - else if ( ( spf == 16 ) || //EXTRUDE_TERRAIN - ( spf == 512 ) || //EXTRUDE_DOWNWARDS - ( spf == 1024 ) || //EXTRUDE_UPWARDS - ( spf == 4096 ) || //default CLIPMODEL + AXIAL_BACKPLANE - ( spf == 2064 ) || //EXTRUDE_TERRAIN+MAX_EXTRUDE - ( spf == 4112 ) || //EXTRUDE_TERRAIN+AXIAL_BACKPLANE - ( spf == 1536 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS - ( spf == 2560 ) || //EXTRUDE_DOWNWARDS+MAX_EXTRUDE - ( spf == 4608 ) || //EXTRUDE_DOWNWARDS+AXIAL_BACKPLANE - ( spf == 3584 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+MAX_EXTRUDE - ( spf == 5632 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+AXIAL_BACKPLANE - ( spf == 3072 ) || //EXTRUDE_UPWARDS+MAX_EXTRUDE - ( spf == 5120 ) ){ //EXTRUDE_UPWARDS+AXIAL_BACKPLANE + else if ( ( spf == 16 ) || //EXTRUDE_TERRAIN + ( spf == 512 ) || //EXTRUDE_DOWNWARDS + ( spf == 1024 ) || //EXTRUDE_UPWARDS + ( spf == 4096 ) || //default CLIPMODEL + AXIAL_BACKPLANE + ( spf == 2064 ) || //EXTRUDE_TERRAIN+MAX_EXTRUDE + ( spf == 4112 ) || //EXTRUDE_TERRAIN+AXIAL_BACKPLANE + ( spf == 1536 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS + ( spf == 2560 ) || //EXTRUDE_DOWNWARDS+MAX_EXTRUDE + ( spf == 4608 ) || //EXTRUDE_DOWNWARDS+AXIAL_BACKPLANE + ( spf == 3584 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+MAX_EXTRUDE + ( spf == 5632 ) || //EXTRUDE_DOWNWARDS+EXTRUDE_UPWARDS+AXIAL_BACKPLANE + ( spf == 3072 ) || //EXTRUDE_UPWARDS+MAX_EXTRUDE + ( spf == 5120 ) ){ //EXTRUDE_UPWARDS+AXIAL_BACKPLANE if ( spawnFlags & 16 ){ //autodirection bestNormal = avgDirection; @@ -953,8 +953,8 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor } - else if ( ( spf == 128 ) || //EXTRUDE_VERTEX_NORMALS - ( spf == 384 ) ){ //EXTRUDE_VERTEX_NORMALS + PYRAMIDAL_CLIP - vertex normals + don't check for sides, sticking outwards + else if ( ( spf == 128 ) || //EXTRUDE_VERTEX_NORMALS + ( spf == 384 ) ){ //EXTRUDE_VERTEX_NORMALS + PYRAMIDAL_CLIP - vertex normals + don't check for sides, sticking outwards /* get vertex normals */ for ( j = 0; j < 3; j++ ) { @@ -1106,19 +1106,19 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor /* make 3 more planes */ if( PlaneFromPoints( p[0], points[ 2 ], points[ 1 ], cnt ) && - PlaneFromPoints( p[1], points[ 1 ], points[ 0 ], cnt ) && - PlaneFromPoints( p[2], points[ 0 ], points[ 2 ], cnt ) ) { + PlaneFromPoints( p[1], points[ 1 ], points[ 0 ], cnt ) && + PlaneFromPoints( p[2], points[ 0 ], points[ 2 ], cnt ) ) { //check for dangerous planes while( (( p[0].a != 0.0 || p[0].b != 0.0 ) && fabs( p[0].a ) < 0.00025 && fabs( p[0].b ) < 0.00025) || - (( p[0].a != 0.0 || p[0].c != 0.0 ) && fabs( p[0].a ) < 0.00025 && fabs( p[0].c ) < 0.00025) || - (( p[0].c != 0.0 || p[0].b != 0.0 ) && fabs( p[0].c ) < 0.00025 && fabs( p[0].b ) < 0.00025) || - (( p[1].a != 0.0 || p[1].b != 0.0 ) && fabs( p[1].a ) < 0.00025 && fabs( p[1].b ) < 0.00025) || - (( p[1].a != 0.0 || p[1].c != 0.0 ) && fabs( p[1].a ) < 0.00025 && fabs( p[1].c ) < 0.00025) || - (( p[1].c != 0.0 || p[1].b != 0.0 ) && fabs( p[1].c ) < 0.00025 && fabs( p[1].b ) < 0.00025) || - (( p[2].a != 0.0 || p[2].b != 0.0 ) && fabs( p[2].a ) < 0.00025 && fabs( p[2].b ) < 0.00025) || - (( p[2].a != 0.0 || p[2].c != 0.0 ) && fabs( p[2].a ) < 0.00025 && fabs( p[2].c ) < 0.00025) || - (( p[2].c != 0.0 || p[2].b != 0.0 ) && fabs( p[2].c ) < 0.00025 && fabs( p[2].b ) < 0.00025) ) { + (( p[0].a != 0.0 || p[0].c != 0.0 ) && fabs( p[0].a ) < 0.00025 && fabs( p[0].c ) < 0.00025) || + (( p[0].c != 0.0 || p[0].b != 0.0 ) && fabs( p[0].c ) < 0.00025 && fabs( p[0].b ) < 0.00025) || + (( p[1].a != 0.0 || p[1].b != 0.0 ) && fabs( p[1].a ) < 0.00025 && fabs( p[1].b ) < 0.00025) || + (( p[1].a != 0.0 || p[1].c != 0.0 ) && fabs( p[1].a ) < 0.00025 && fabs( p[1].c ) < 0.00025) || + (( p[1].c != 0.0 || p[1].b != 0.0 ) && fabs( p[1].c ) < 0.00025 && fabs( p[1].b ) < 0.00025) || + (( p[2].a != 0.0 || p[2].b != 0.0 ) && fabs( p[2].a ) < 0.00025 && fabs( p[2].b ) < 0.00025) || + (( p[2].a != 0.0 || p[2].c != 0.0 ) && fabs( p[2].a ) < 0.00025 && fabs( p[2].c ) < 0.00025) || + (( p[2].c != 0.0 || p[2].b != 0.0 ) && fabs( p[2].c ) < 0.00025 && fabs( p[2].b ) < 0.00025) ) { cnt -= plane.normal() * 0.1f; // Sys_Printf( "shifting pyramid point\n" ); PlaneFromPoints( p[0], points[ 2 ], points[ 1 ], cnt ); @@ -1159,7 +1159,7 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor else { Sys_Warning( "triangle (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) of %s was not autoclipped\n", - points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); + points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); free( buildBrush ); continue; } @@ -1168,7 +1168,7 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor else if ( ( si->clipModel && !( spf ) ) || ( ( spawnFlags & 8090 ) == 2 ) ){ //default CLIPMODEL - default_CLIPMODEL: +default_CLIPMODEL: // axial normal bestNormal = plane.normal(); for ( j = 0; j < 3; j++ ){ @@ -1235,7 +1235,7 @@ void InsertModel( const char *name, int skin, int frame, const Matrix4& transfor } else{ Sys_Warning( "triangle (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) of %s was not autoclipped\n", - points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); + points[0][0], points[0][1], points[0][2], points[1][0], points[1][1], points[1][2], points[2][0], points[2][1], points[2][2], name ); free( buildBrush ); } } @@ -1325,7 +1325,7 @@ void AddTriangleModels( entity_t *eparent ){ const char *value; Vector3 angles( 0 ); if ( !e->read_keyvalue( value, "angles" ) || - 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) + 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) e->read_keyvalue( angles[ 2 ], "angle" ); /* set transform matrix (thanks spog) */ @@ -1374,7 +1374,7 @@ void AddTriangleModels( entity_t *eparent ){ /* ydnar: cel shader support */ shaderInfo_t *celShader; if( e->read_keyvalue( value, "_celshader" ) || - entities[ 0 ].read_keyvalue( value, "_celshader" ) ){ + entities[ 0 ].read_keyvalue( value, "_celshader" ) ){ celShader = ShaderInfoForShader( String64()( "textures/", value ) ); } else{ diff --git a/tools/quake3/q3map2/patch.cpp b/tools/quake3/q3map2/patch.cpp index 569ae9b5..bd5d4121 100644 --- a/tools/quake3/q3map2/patch.cpp +++ b/tools/quake3/q3map2/patch.cpp @@ -140,9 +140,9 @@ static void ExpandMaxIterations( int *maxIterations, int maxError, const Vector3 points[ j ] = points[ j - 2 ]; /* insert new points */ - points[ i + 1 ] = prev; - points[ i + 2 ] = mid; - points[ i + 3 ] = next; + points[ i + 1 ] = prev; + points[ i + 2 ] = mid; + points[ i + 3 ] = next; /* back up and recheck this set again, it may need more subdivision */ i -= 2; @@ -431,12 +431,12 @@ void PatchMapDrawSurfs( entity_t *e ){ if ( i != c1 ) { // we have a connection bordering[k * patchCount + l] = - bordering[l * patchCount + k] = 1; + bordering[l * patchCount + k] = 1; } else { // no connection bordering[k * patchCount + l] = - bordering[l * patchCount + k] = 0; + bordering[l * patchCount + k] = 0; } } diff --git a/tools/quake3/q3map2/path_init.cpp b/tools/quake3/q3map2/path_init.cpp index 0fd66a76..af1eca60 100644 --- a/tools/quake3/q3map2/path_init.cpp +++ b/tools/quake3/q3map2/path_init.cpp @@ -203,12 +203,12 @@ game_t *GetGame( char *arg ){ /* joke */ if ( striEqual( arg, "quake1" ) || - striEqual( arg, "quake2" ) || - striEqual( arg, "unreal" ) || - striEqual( arg, "ut2k3" ) || - striEqual( arg, "dn3d" ) || - striEqual( arg, "dnf" ) || - striEqual( arg, "hl" ) ) { + striEqual( arg, "quake2" ) || + striEqual( arg, "unreal" ) || + striEqual( arg, "ut2k3" ) || + striEqual( arg, "dn3d" ) || + striEqual( arg, "dnf" ) || + striEqual( arg, "hl" ) ) { Sys_Printf( "April fools, silly rabbit!\n" ); exit( 0 ); } diff --git a/tools/quake3/q3map2/portals.cpp b/tools/quake3/q3map2/portals.cpp index aee70e01..9769c5ad 100644 --- a/tools/quake3/q3map2/portals.cpp +++ b/tools/quake3/q3map2/portals.cpp @@ -68,7 +68,7 @@ bool PortalPassable( portal_t *p ){ /* this should never happen */ if ( p->nodes[ 0 ]->planenum != PLANENUM_LEAF || - p->nodes[ 1 ]->planenum != PLANENUM_LEAF ) { + p->nodes[ 1 ]->planenum != PLANENUM_LEAF ) { Error( "Portal_EntityFlood: not a leaf" ); } @@ -162,8 +162,8 @@ void PrintPortal( portal_t *p ){ w = p->winding; for ( i = 0 ; i < w->numpoints ; i++ ) - Sys_Printf( "(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] - , w->p[i][1], w->p[i][2] ); + Sys_Printf( "(%5.0f,%5.0f,%5.0f)\n", w->p[i][0] + , w->p[i][1], w->p[i][2] ); } /* @@ -257,7 +257,7 @@ winding_t *BaseWindingForNode( node_t *node ){ ChopWindingInPlace( &w, plane.plane, BASE_WINDING_EPSILON ); } else - { // take back + { // take back ChopWindingInPlace( &w, plane3_flipped( plane.plane ), BASE_WINDING_EPSILON ); } node = n; @@ -369,7 +369,7 @@ void SplitNodePortals( node_t *node ){ // cut the portal into two portals, one on each side of the cut plane // ClipWindingEpsilon( p->winding, plane.plane, - SPLIT_WINDING_EPSILON, &frontwinding, &backwinding ); /* not strict, we want to always keep one of them even if coplanar */ + SPLIT_WINDING_EPSILON, &frontwinding, &backwinding ); /* not strict, we want to always keep one of them even if coplanar */ if ( frontwinding && WindingIsTiny( frontwinding ) ) { if ( !f->tinyportals ) { @@ -475,12 +475,12 @@ void MakeTreePortals_r( node_t *node ){ CalcNodeBounds( node ); if ( !node->minmax.valid() ) { Sys_Warning( "node without a volume\n" - "node has %d tiny portals\n" - "node reference point %1.2f %1.2f %1.2f\n", - node->tinyportals, - node->referencepoint[0], - node->referencepoint[1], - node->referencepoint[2] ); + "node has %d tiny portals\n" + "node reference point %1.2f %1.2f %1.2f\n", + node->tinyportals, + node->referencepoint[0], + node->referencepoint[1], + node->referencepoint[2] ); } if ( !c_worldMinmax.surrounds( node->minmax ) ) { @@ -639,7 +639,7 @@ EFloodEntities FloodEntities( tree_t *tree ){ /* get "angle" (yaw) or "angles" (pitch yaw roll), store as (roll pitch yaw) */ Vector3 angles( 0 ); if ( !e.read_keyvalue( value, "angles" ) || - 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) + 3 != sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ) ) e.read_keyvalue( angles[ 2 ], "angle" ); /* set transform matrix (thanks spog) */ diff --git a/tools/quake3/q3map2/q3map2.h b/tools/quake3/q3map2/q3map2.h index 2df34e45..f1229870 100644 --- a/tools/quake3/q3map2/q3map2.h +++ b/tools/quake3/q3map2/q3map2.h @@ -1953,45 +1953,45 @@ Q_EXTERN game_t games[] #else = { - #include "game_quake3.h" + #include "game_quake3.h" , - #include "game_quakelive.h" /* must be after game_quake3.h as they share defines! */ + #include "game_quakelive.h" /* must be after game_quake3.h as they share defines! */ , - #include "game_nexuiz.h" /* must be after game_quake3.h as they share defines! */ + #include "game_nexuiz.h" /* must be after game_quake3.h as they share defines! */ , - #include "game_xonotic.h" /* must be after game_quake3.h as they share defines! */ + #include "game_xonotic.h" /* must be after game_quake3.h as they share defines! */ , - #include "game_tremulous.h" /*LinuxManMikeC: must be after game_quake3.h, depends on #define's set in it */ + #include "game_tremulous.h" /*LinuxManMikeC: must be after game_quake3.h, depends on #define's set in it */ , - #include "game_unvanquished.h" + #include "game_unvanquished.h" , - #include "game_tenebrae.h" + #include "game_tenebrae.h" , - #include "game_wolf.h" + #include "game_wolf.h" , - #include "game_wolfet.h" /* must be after game_wolf.h as they share defines! */ + #include "game_wolfet.h" /* must be after game_wolf.h as they share defines! */ , - #include "game_etut.h" + #include "game_etut.h" , - #include "game_ef.h" + #include "game_ef.h" , - #include "game_sof2.h" + #include "game_sof2.h" , - #include "game_jk2.h" /* must be after game_sof2.h as they share defines! */ + #include "game_jk2.h" /* must be after game_sof2.h as they share defines! */ , - #include "game_ja.h" /* must be after game_jk2.h as they share defines! */ + #include "game_ja.h" /* must be after game_jk2.h as they share defines! */ , - #include "game_qfusion.h" /* qfusion game */ + #include "game_qfusion.h" /* qfusion game */ , - #include "game_reaction.h" /* must be after game_quake3.h */ + #include "game_reaction.h" /* must be after game_quake3.h */ , - #include "game_darkplaces.h" /* vortex: darkplaces q1 engine */ + #include "game_darkplaces.h" /* vortex: darkplaces q1 engine */ , - #include "game_dq.h" /* vortex: deluxe quake game ( darkplaces q1 engine) */ + #include "game_dq.h" /* vortex: deluxe quake game ( darkplaces q1 engine) */ , - #include "game_prophecy.h" /* vortex: prophecy game ( darkplaces q1 engine) */ + #include "game_prophecy.h" /* vortex: prophecy game ( darkplaces q1 engine) */ , - #include "game__null.h" /* null game (must be last item) */ + #include "game__null.h" /* null game (must be last item) */ }; #endif Q_EXTERN game_t *game Q_ASSIGN( &games[ 0 ] ); diff --git a/tools/quake3/q3map2/shaders.cpp b/tools/quake3/q3map2/shaders.cpp index f1227328..4c837783 100644 --- a/tools/quake3/q3map2/shaders.cpp +++ b/tools/quake3/q3map2/shaders.cpp @@ -352,10 +352,10 @@ void WriteMapShaderFile( void ){ /* print header */ fprintf( file, - "// Custom shader file for %s.bsp\n" - "// Generated by Q3Map2 (ydnar)\n" - "// Do not edit! This file is overwritten on recompiles.\n\n", - mapName.c_str() ); + "// Custom shader file for %s.bsp\n" + "// Generated by Q3Map2 (ydnar)\n" + "// Do not edit! This file is overwritten on recompiles.\n\n", + mapName.c_str() ); /* walk the shader list */ for ( i = 0, num = 0; i < numShaderInfo; i++ ) @@ -412,86 +412,86 @@ shaderInfo_t *CustomShader( shaderInfo_t *si, const char *find, char *replace ){ if ( si->implicitMap == EImplicitMap::Opaque ) { srcShaderText = temp; sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitMap)\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->implicitImagePath.c_str() ); + "{ // Q3Map2 defaulted (implicitMap)\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->implicitImagePath.c_str() ); } /* et: implicitMask */ else if ( si->implicitMap == EImplicitMap::Masked ) { srcShaderText = temp; sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitMask)\n" - "\tcull none\n" - "\t{\n" - "\t\tmap %s\n" - "\t\talphaFunc GE128\n" - "\t\tdepthWrite\n" - "\t}\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t\tdepthFunc equal\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\tdepthFunc equal\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->implicitImagePath.c_str(), - si->implicitImagePath.c_str() ); + "{ // Q3Map2 defaulted (implicitMask)\n" + "\tcull none\n" + "\t{\n" + "\t\tmap %s\n" + "\t\talphaFunc GE128\n" + "\t\tdepthWrite\n" + "\t}\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t\tdepthFunc equal\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\tdepthFunc equal\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->implicitImagePath.c_str(), + si->implicitImagePath.c_str() ); } /* et: implicitBlend */ else if ( si->implicitMap == EImplicitMap::Blend ) { srcShaderText = temp; sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitBlend)\n" - "\tcull none\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA\n" - "\t}\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t}\n" - "\tq3map_styleMarker\n" - "}\n", - si->implicitImagePath.c_str() ); + "{ // Q3Map2 defaulted (implicitBlend)\n" + "\tcull none\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA\n" + "\t}\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t}\n" + "\tq3map_styleMarker\n" + "}\n", + si->implicitImagePath.c_str() ); } /* default shader text */ else if ( srcShaderText == NULL ) { srcShaderText = temp; sprintf( temp, "\n" - "{ // Q3Map2 defaulted\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s.tga\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->shader.c_str() ); + "{ // Q3Map2 defaulted\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s.tga\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->shader.c_str() ); } /* error check */ @@ -520,8 +520,8 @@ shaderInfo_t *CustomShader( shaderInfo_t *si, const char *find, char *replace ){ /* mangle hash into a shader name */ sprintf( shader, "%s/%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mapName.c_str(), - digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], - digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ], digest[ 15 ] ); + digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], + digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ], digest[ 15 ] ); /* get shader */ csi = ShaderInfoForShader( shader ); @@ -569,8 +569,8 @@ void EmitVertexRemapShader( char *from, char *to ){ /* make key (this is annoying, as vertexremapshader is precisely 17 characters, which is one too long, so we leave off the last byte of the md5 digest) */ sprintf( key, "vertexremapshader%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", - digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], - digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ] ); /* no: digest[ 15 ] */ + digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], + digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ] ); /* no: digest[ 15 ] */ /* add key/value pair to worldspawn */ entities[ 0 ].setKeyValue( key, value ); @@ -745,7 +745,7 @@ static void LoadShaderImages( shaderInfo_t *si ){ si->normalImage = ImageLoad( si->normalImagePath ); if ( si->normalImage != NULL ) { Sys_FPrintf( SYS_VRB, "Shader %s has\n" - " NM %s\n", si->shader.c_str(), si->normalImagePath.c_str() ); + " NM %s\n", si->shader.c_str(), si->normalImagePath.c_str() ); } } @@ -970,11 +970,11 @@ static void ParseShaderFile( const char *filename ){ if ( !strEqual( token, "{" ) ) { if ( si != NULL ) { Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s\nLast known shader: %s\nFile location be: %s\n", - filename, scriptline, token, si->shader.c_str(), g_strLoadedFileLocation ); + filename, scriptline, token, si->shader.c_str(), g_strLoadedFileLocation ); } else{ Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s\nFile location be: %s\n", - filename, scriptline, token, g_strLoadedFileLocation ); + filename, scriptline, token, g_strLoadedFileLocation ); } } @@ -1009,11 +1009,11 @@ static void ParseShaderFile( const char *filename ){ if ( si->editorImagePath.empty() && si->lightImagePath.empty() && si->implicitImagePath.empty() ) { /* digest any images */ if ( striEqual( token, "map" ) || - striEqual( token, "clampMap" ) || - striEqual( token, "animMap" ) || - striEqual( token, "clampAnimMap" ) || - striEqual( token, "mapComp" ) || - striEqual( token, "mapNoComp" ) ) { + striEqual( token, "clampMap" ) || + striEqual( token, "animMap" ) || + striEqual( token, "clampAnimMap" ) || + striEqual( token, "mapComp" ) || + striEqual( token, "mapNoComp" ) ) { /* skip one token for animated stages */ if ( striEqual( token, "animMap" ) || striEqual( token, "clampAnimMap" ) ) { GetTokenAppend( shaderText, false ); @@ -1496,9 +1496,9 @@ static void ParseShaderFile( const char *filename ){ /* must be a power of 2 */ if ( ( ( si->lmCustomWidth - 1 ) & si->lmCustomWidth ) || - ( ( si->lmCustomHeight - 1 ) & si->lmCustomHeight ) ) { + ( ( si->lmCustomHeight - 1 ) & si->lmCustomHeight ) ) { Sys_Warning( "Non power-of-two lightmap size specified (%d, %d)\n", - si->lmCustomWidth, si->lmCustomHeight ); + si->lmCustomWidth, si->lmCustomHeight ); si->lmCustomWidth = lmCustomSizeW; si->lmCustomHeight = lmCustomSizeH; } @@ -1644,8 +1644,8 @@ static void ParseShaderFile( const char *filename ){ /* ydnar: gs mods: q3map_[color|rgb|alpha][Gen|Mod]