Revert partially (manual) "reformat code! now the code is only ugly on the *inside*" 116/head
authorThomas Debesse <dev@illwieckz.net>
Mon, 11 Feb 2019 01:31:14 +0000 (02:31 +0100)
committerThomas Debesse <dev@illwieckz.net>
Mon, 11 Feb 2019 04:28:00 +0000 (05:28 +0100)
This reverts commit 9dfae1c9b270ee369c6362903a9205b30751b95f.
But only for files whose changes that were manually reverted.

22 files changed:
contrib/bobtoolz/DEntity.cpp
plugins/imagepng/plugin.cpp
plugins/iqmmodel/iqm.h
plugins/iqmmodel/plugin.h
plugins/mapq3/plugin.cpp
plugins/mapq3/write.cpp
plugins/mapq3/write.h
plugins/mapxml/plugin.cpp
plugins/shaders/shaders.cpp
radiant/brush.h
radiant/brushmanip.cpp
radiant/csg.cpp
radiant/csg.h
radiant/entity.cpp
radiant/environment.cpp
radiant/mainframe.cpp
radiant/map.cpp
radiant/multimon.cpp
radiant/qe3.cpp
radiant/referencecache.cpp
radiant/renderstate.cpp
radiant/texwindow.cpp

index d764c31..5a4d8e5 100644 (file)
 #include "scenelib.h"
 
 
-const char *brushEntityList[] = {
-        "worldspawn",
-        "trigger_always",
-        "trigger_hurt",
-        "trigger_multiple",
-        "trigger_push",
-        "trigger_teleport",
-        "func_bobbing",
-        "func_button",
-        "func_door",
-        "func_group",
-        "func_pendulum",
-        "func_plat",
-        "func_rotating",
-        "func_static",
-        "func_timer",
-        "func_train",
-        0
+const charbrushEntityList[] = {
+       "worldspawn",
+       "trigger_always",
+       "trigger_hurt",
+       "trigger_multiple",
+       "trigger_push",
+       "trigger_teleport",
+       "func_bobbing",
+       "func_button",
+       "func_door",
+       "func_group",
+       "func_pendulum",
+       "func_plat",
+       "func_rotating",
+       "func_static",
+       "func_timer",
+       "func_train",
+       0
 };
 
 //////////////////////////////////////////////////////////////////////
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
 
-DEntity::DEntity(const char *classname, int ID)
-{
-    SetClassname(classname);
-    m_nID = ID;
-    QER_Entity = NULL;
+DEntity::DEntity( const char *classname, int ID ){
+       SetClassname( classname );
+       m_nID = ID;
+       QER_Entity = NULL;
 }
 
-DEntity::~DEntity()
-{
-    ClearPatches();
-    ClearBrushes();
-    ClearEPairs();
+DEntity::~DEntity(){
+       ClearPatches();
+       ClearBrushes();
+       ClearEPairs();
 }
 
 //////////////////////////////////////////////////////////////////////
 // Implementation
 //////////////////////////////////////////////////////////////////////
 
-void DEntity::ClearBrushes()
-{
-    for (std::list<DBrush *>::const_iterator deadBrush = brushList.begin(); deadBrush != brushList.end(); deadBrush++) {
-        delete *deadBrush;
-    }
-    brushList.clear();
+void DEntity::ClearBrushes(){
+       for ( std::list<DBrush *>::const_iterator deadBrush = brushList.begin(); deadBrush != brushList.end(); deadBrush++ )
+       {
+               delete *deadBrush;
+       }
+       brushList.clear();
 }
 
-void DEntity::ClearPatches()
-{
-    for (std::list<DPatch *>::const_iterator deadPatch = patchList.begin(); deadPatch != patchList.end(); deadPatch++) {
-        delete *deadPatch;
-    }
-    patchList.clear();
-}
+void DEntity::ClearPatches(){
+       for ( std::list<DPatch *>::const_iterator deadPatch = patchList.begin(); deadPatch != patchList.end(); deadPatch++ )
+       {
+               delete *deadPatch;
+       }
+       patchList.clear();
+}
+
+DPatch* DEntity::NewPatch(){
+       DPatch* newPatch = new DPatch;
+
+       patchList.push_back( newPatch );
+
+       return newPatch;
+}
 
-DPatch *DEntity::NewPatch()
-{
-    DPatch *newPatch = new DPatch;
+DBrush* DEntity::NewBrush( int ID ){
+       DBrush* newBrush = new DBrush( ID );
 
-    patchList.push_back(newPatch);
+       brushList.push_back( newBrush );
 
-    return newPatch;
+       return newBrush;
 }
 
-DBrush *DEntity::NewBrush(int ID)
-{
-    DBrush *newBrush = new DBrush(ID);
-
-    brushList.push_back(newBrush);
+char* getNextBracket( char* s ){
+       char* p = s;
+       while ( *p )
+       {
+               p++;
+               if ( *p == '(' ) {
+                       break;
+               }
+       }
 
-    return newBrush;
+       return p;
 }
 
-char *getNextBracket(char *s)
-{
-    char *p = s;
-    while (*p) {
-        p++;
-        if (*p == '(') {
-            break;
-        }
-    }
+bool DEntity::LoadFromPrt( char *filename ){
+       CPortals portals;
+       strcpy( portals.fn, filename );
+       portals.Load();
 
-    return p;
-}
+       if ( portals.node_count == 0 ) {
+               return false;
+       }
 
-bool DEntity::LoadFromPrt(char *filename)
-{
-    CPortals portals;
-    strcpy(portals.fn, filename);
-    portals.Load();
-
-    if (portals.node_count == 0) {
-        return false;
-    }
-
-    ClearBrushes();
-    ClearEPairs();
-
-    bool build = false;
-    for (unsigned int i = 0; i < portals.node_count; i++) {
-        build = false;
-        DBrush *brush = NewBrush();
-
-        for (unsigned int j = 0; j < portals.node[i].portal_count; j++) {
-            for (unsigned int k = 0; k < portals.node[i].portal[j].point_count - 2; k++) {
-                vec3_t v1{}, v2{}, normal{}, n{};
-                VectorSubtract(portals.node[i].portal[j].point[k + 2].p, portals.node[i].portal[j].point[k + 1].p, v1);
-                VectorSubtract(portals.node[i].portal[j].point[k].p, portals.node[i].portal[j].point[k + 1].p, v2);
-                CrossProduct(v1, v2, n);
-                VectorNormalize(n, v2);
-
-                if (k == 0) {
-                    VectorCopy(v2, normal);
-                } else {
-                    VectorSubtract(v2, normal, v1);
-                    if (VectorLength(v1) > 0.01) {
-                        build = true;
-                        break;
-                    }
-                }
-            }
-
-            if (!build) {
-                brush->AddFace(portals.node[i].portal[j].point[2].p, portals.node[i].portal[j].point[1].p,
-                               portals.node[i].portal[j].point[0].p, "textures/common/caulk", false);
-            } else {
-                brush->AddFace(portals.node[i].portal[j].point[0].p, portals.node[i].portal[j].point[1].p,
-                               portals.node[i].portal[j].point[2].p, "textures/common/caulk", false);
-            }
-        }
-        if (build) {
-            brush->BuildInRadiant(false, NULL);
-        }
-    }
-
-    return true;
-}
-
-DPlane *DEntity::AddFaceToBrush(vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData *faceData, int ID)
-{
-    DBrush *buildBrush = GetBrushForID(ID);
-    return buildBrush->AddFace(va, vb, vc, faceData);
-    // slow, dont use much
+       ClearBrushes();
+       ClearEPairs();
+
+       bool build = false;
+       for ( unsigned int i = 0; i < portals.node_count; i++ )
+       {
+               build = false;
+               DBrush* brush = NewBrush();
+
+               for ( unsigned int j = 0; j < portals.node[i].portal_count; j++ )
+               {
+                       for ( unsigned int k = 0; k < portals.node[i].portal[j].point_count - 2; k++ )
+                       {
+                               vec3_t v1{}, v2{}, normal{}, n{};
+                               VectorSubtract( portals.node[i].portal[j].point[k + 2].p, portals.node[i].portal[j].point[k + 1].p, v1 );
+                               VectorSubtract( portals.node[i].portal[j].point[k].p, portals.node[i].portal[j].point[k + 1].p, v2 );
+                               CrossProduct( v1, v2, n );
+                               VectorNormalize( n, v2 );
+
+                               if ( k == 0 ) {
+                                       VectorCopy( v2, normal );
+                               }
+                               else
+                               {
+                                       VectorSubtract( v2, normal, v1 );
+                                       if ( VectorLength( v1 ) > 0.01 ) {
+                                               build = true;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       if ( !build ) {
+                               brush->AddFace( portals.node[i].portal[j].point[2].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[0].p, "textures/common/caulk", false );
+                       }
+                       else{
+                               brush->AddFace( portals.node[i].portal[j].point[0].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[2].p, "textures/common/caulk", false );
+                       }
+               }
+               if ( build ) {
+                       brush->BuildInRadiant( false, NULL );
+               }
+       }
+
+       return true;
 }
 
-DBrush *DEntity::GetBrushForID(int ID)
-{
-    DBrush *buildBrush = NULL;
+DPlane* DEntity::AddFaceToBrush( vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID ){
+       DBrush* buildBrush = GetBrushForID( ID );
+       return buildBrush->AddFace( va, vb, vc, faceData );
+       // slow, dont use much
+}
 
-    for (std::list<DBrush *>::const_iterator chkBrush = brushList.begin(); chkBrush != brushList.end(); chkBrush++) {
-        if ((*chkBrush)->m_nBrushID == ID) {
-            buildBrush = (*chkBrush);
-            break;
-        }
-    }
+DBrush* DEntity::GetBrushForID( int ID ){
+       DBrush* buildBrush = NULL;
 
-    if (!buildBrush) {
-        buildBrush = NewBrush(ID);
-    }
+       for ( std::list<DBrush *>::const_iterator chkBrush = brushList.begin(); chkBrush != brushList.end(); chkBrush++ )
+       {
+               if ( ( *chkBrush )->m_nBrushID == ID ) {
+                       buildBrush = ( *chkBrush );
+                       break;
+               }
+       }
 
-    return buildBrush;
+       if ( !buildBrush ) {
+               buildBrush = NewBrush( ID );
+       }
+
+       return buildBrush;
 }
 
 template<typename Functor>
-class BrushSelectedVisitor : public SelectionSystem::Visitor {
-    const Functor &m_functor;
+class BrushSelectedVisitor : public SelectionSystem::Visitor
+{
+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<typename Functor>
-inline const Functor &Scene_forEachSelectedBrush(const Functor &functor)
-{
-    GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor<Functor>(functor));
-    return functor;
+inline const Functor& Scene_forEachSelectedBrush( const Functor& functor ){
+       GlobalSelectionSystem().foreachSelected( BrushSelectedVisitor<Functor>( functor ) );
+       return functor;
 }
 
-void DEntity_loadBrush(DEntity &entity, scene::Instance &brush)
-{
-    DBrush *loadBrush = entity.NewBrush(static_cast<int>( entity.brushList.size()));
-    loadBrush->LoadFromBrush(brush, true);
+void DEntity_loadBrush( DEntity& entity, scene::Instance& brush ){
+       DBrush* loadBrush = entity.NewBrush( static_cast<int>( entity.brushList.size() ) );
+       loadBrush->LoadFromBrush( brush, true );
 }
 
-typedef ReferenceCaller<DEntity, void(scene::Instance &), DEntity_loadBrush> DEntityLoadBrushCaller;
+typedef ReferenceCaller<DEntity, void ( scene::Instance & ), DEntity_loadBrush> DEntityLoadBrushCaller;
 
-void DEntity::LoadSelectedBrushes()
-{
-    ClearBrushes();
-    ClearEPairs();
+void DEntity::LoadSelectedBrushes(){
+       ClearBrushes();
+       ClearEPairs();
 
-    Scene_forEachSelectedBrush(DEntityLoadBrushCaller(*this));
+       Scene_forEachSelectedBrush( DEntityLoadBrushCaller( *this ) );
 }
 
 template<typename Functor>
-class PatchSelectedVisitor : public SelectionSystem::Visitor {
-    const Functor &m_functor;
+class PatchSelectedVisitor : public SelectionSystem::Visitor
+{
+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<typename Functor>
-inline const Functor &Scene_forEachSelectedPatch(const Functor &functor)
-{
-    GlobalSelectionSystem().foreachSelected(PatchSelectedVisitor<Functor>(functor));
-    return functor;
+inline const Functor& Scene_forEachSelectedPatch( const Functor& functor ){
+       GlobalSelectionSystem().foreachSelected( PatchSelectedVisitor<Functor>( functor ) );
+       return functor;
 }
 
-void DEntity_loadPatch(DEntity &entity, scene::Instance &patch)
-{
-    DPatch *loadPatch = entity.NewPatch();
-    loadPatch->LoadFromPatch(patch);
+void DEntity_loadPatch( DEntity& entity, scene::Instance& patch ){
+       DPatch* loadPatch = entity.NewPatch();
+       loadPatch->LoadFromPatch( patch );
 }
 
-typedef ReferenceCaller<DEntity, void(scene::Instance &), DEntity_loadPatch> DEntityLoadPatchCaller;
+typedef ReferenceCaller<DEntity, void ( scene::Instance & ), DEntity_loadPatch> DEntityLoadPatchCaller;
 
-void DEntity::LoadSelectedPatches()
-{
-    ClearPatches();
-    ClearEPairs();
+void DEntity::LoadSelectedPatches(){
+       ClearPatches();
+       ClearEPairs();
 
-    Scene_forEachSelectedPatch(DEntityLoadPatchCaller(*this));
+       Scene_forEachSelectedPatch( DEntityLoadPatchCaller( *this ) );
 }
 
-bool *DEntity::BuildIntersectList()
-{
-    int max = GetIDMax();
-    if (max == 0) {
-        return NULL;
-    }
+bool* DEntity::BuildIntersectList(){
+       int max = GetIDMax();
+       if ( max == 0 ) {
+               return NULL;
+       }
 
-    bool *pbIntList = new bool[max];
-    memset(pbIntList, 0, sizeof(bool) * (max));
+       bool* pbIntList = new bool[max];
+       memset( pbIntList, 0, sizeof( bool ) * ( max ) );
 
-    for (std::list<DBrush *>::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++) {
-        std::list<DBrush *>::const_iterator pB2 = pB1;
-        for (pB2++; pB2 != brushList.end(); pB2++) {
-            if ((*pB1)->IntersectsWith((*pB2))) {
-                pbIntList[(*pB1)->m_nBrushID] = true;
-                pbIntList[(*pB2)->m_nBrushID] = true;
-            }
-        }
-    }
+       for ( std::list<DBrush *>::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++ )
+       {
+               std::list<DBrush *>::const_iterator pB2 = pB1;
+               for ( pB2++; pB2 != brushList.end(); pB2++ )
+               {
+                       if ( ( *pB1 )->IntersectsWith( ( *pB2 ) ) ) {
+                               pbIntList[( *pB1 )->m_nBrushID] = true;
+                               pbIntList[( *pB2 )->m_nBrushID] = true;
+                       }
+               }
+       }
 
-    return pbIntList;
+       return pbIntList;
 }
 
-bool *DEntity::BuildDuplicateList()
-{
-    int max = GetIDMax();
-    if (max == 0) {
-        return NULL;
-    }
+bool* DEntity::BuildDuplicateList(){
+       int max = GetIDMax();
+       if ( max == 0 ) {
+               return NULL;
+       }
 
-    bool *pbDupList = new bool[max];
-    memset(pbDupList, 0, sizeof(bool) * (max));
+       bool* pbDupList = new bool[max];
+       memset( pbDupList, 0, sizeof( bool ) * ( max ) );
 
-    for (std::list<DBrush *>::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++) {
-        std::list<DBrush *>::const_iterator pB2 = pB1;
-        for (pB2++; pB2 != brushList.end(); pB2++) {
-            if (**pB1 == *pB2) {
-                pbDupList[(*pB1)->m_nBrushID] = true;
-                pbDupList[(*pB2)->m_nBrushID] = true;
-            }
-        }
-    }
+       for ( std::list<DBrush *>::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++ )
+       {
+               std::list<DBrush *>::const_iterator pB2 = pB1;
+               for ( pB2++; pB2 != brushList.end(); pB2++ )
+               {
+                       if ( **pB1 == *pB2 ) {
+                               pbDupList[( *pB1 )->m_nBrushID] = true;
+                               pbDupList[( *pB2 )->m_nBrushID] = true;
+                       }
+               }
+       }
 
-    return pbDupList;
+       return pbDupList;
 }
 
-void DEntity::SelectBrushes(bool *selectList)
-{
-    if (selectList == NULL) {
-        return;
-    }
+void DEntity::SelectBrushes( bool *selectList ){
+       if ( selectList == NULL ) {
+               return;
+       }
 
-    GlobalSelectionSystem().setSelectedAll(false);
+       GlobalSelectionSystem().setSelectedAll( false );
 
-    scene::Path path(NodeReference(GlobalSceneGraph().root()));
-    path.push(NodeReference(*QER_Entity));
+       scene::Path path( NodeReference( GlobalSceneGraph().root() ) );
+       path.push( NodeReference( *QER_Entity ) );
 
-    for (std::list<DBrush *>::const_iterator pBrush = brushList.begin(); pBrush != brushList.end(); pBrush++) {
-        if (selectList[(*pBrush)->m_nBrushID]) {
-            path.push(NodeReference(*(*pBrush)->QER_brush));
-            Instance_getSelectable(*GlobalSceneGraph().find(path))->setSelected(true);
-            path.pop();
-        }
-    }
+       for ( std::list<DBrush *>::const_iterator pBrush = brushList.begin(); pBrush != brushList.end(); pBrush++ )
+       {
+               if ( selectList[( *pBrush )->m_nBrushID] ) {
+                       path.push( NodeReference( *( *pBrush )->QER_brush ) );
+                       Instance_getSelectable( *GlobalSceneGraph().find( path ) )->setSelected( true );
+                       path.pop();
+               }
+       }
 }
 
-bool DEntity::LoadFromEntity(scene::Node &ent, bool bLoadPatches)
-{
-    ClearPatches();
-    ClearBrushes();
-    ClearEPairs();
-
-    QER_Entity = &ent;
-
-    LoadEPairList(Node_getEntity(ent));
-
-    bool keep = false;
-    int i;
-    for (i = 0; brushEntityList[i]; i++) {
-        if (string_equal_nocase(brushEntityList[i], m_Classname)) {
-            keep = true;
-            break;
-        }
-    }
-
-    if (!keep) {
-        return false;
-    }
-
-    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, "");
-
-                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;
-            }
-        } load_brushes(this);
-
-        Node_getTraversable(ent)->traverse(load_brushes);
-    }
-
-    return true;
-}
-
-void DEntity::RemoveNonCheckBrushes(std::list<Str> *exclusionList, bool useDetail)
-{
-    std::list<DBrush *>::iterator chkBrush = brushList.begin();
-
-    while (chkBrush != brushList.end()) {
-        if (!useDetail) {
-            if ((*chkBrush)->IsDetail()) {
-                delete *chkBrush;
-                chkBrush = brushList.erase(chkBrush);
-                continue;
-            }
-        }
-
-        std::list<Str>::iterator eTexture;
-
-        for (eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++) {
-            if ((*chkBrush)->HasTexture((*eTexture).GetBuffer())) {
-                delete *chkBrush;
-                chkBrush = brushList.erase(chkBrush);
-                break;
-            }
-        }
-
-        if (eTexture == exclusionList->end()) {
-            chkBrush++;
-        }
-    }
-}
-
-void DEntity::ResetChecks(std::list<Str> *exclusionList)
-{
-    for (std::list<DBrush *>::const_iterator resetBrush = brushList.begin();
-         resetBrush != brushList.end(); resetBrush++) {
-        (*resetBrush)->ResetChecks(exclusionList);
-    }
-}
+bool DEntity::LoadFromEntity( scene::Node& ent, bool bLoadPatches ) {
+       ClearPatches();
+       ClearBrushes();
+       ClearEPairs();
 
-int DEntity::FixBrushes()
-{
-    int count = 0;
+       QER_Entity = &ent;
 
-    for (std::list<DBrush *>::const_iterator fixBrush = brushList.begin(); fixBrush != brushList.end(); fixBrush++) {
-        count += (*fixBrush)->RemoveRedundantPlanes();
-    }
+       LoadEPairList( Node_getEntity( ent ) );
 
-    return count;
-}
+       bool keep = false;
+       int i;
+       for ( i = 0; brushEntityList[i]; i++ )
+       {
+               if ( string_equal_nocase( brushEntityList[i], m_Classname ) ) {
+                       keep = true;
+                       break;
+               }
+       }
+
+       if ( !keep ) {
+               return false;
+       }
+
+       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, "" );
 
-void DEntity::BuildInRadiant(bool allowDestruction)
-{
-    bool makeEntity = strcmp(m_Classname, "worldspawn") ? true : false;
+                       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;
+               }
+               } load_brushes( this );
 
-    if (makeEntity) {
-        NodeSmartReference node(GlobalEntityCreator().createEntity(
-                GlobalEntityClassManager().findOrInsert(m_Classname.GetBuffer(),
-                                                        !brushList.empty() || !patchList.empty())));
+               Node_getTraversable( ent )->traverse( load_brushes );
+       }
 
-        for (std::list<DEPair *>::const_iterator buildEPair = epairList.begin();
-             buildEPair != epairList.end(); buildEPair++) {
-            Node_getEntity(node)->setKeyValue((*buildEPair)->key, (*buildEPair)->value);
-        }
+       return true;
+}
 
-        Node_getTraversable(GlobalSceneGraph().root())->insert(node);
+void DEntity::RemoveNonCheckBrushes( std::list<Str>* exclusionList, bool useDetail ){
+       std::list<DBrush *>::iterator chkBrush = brushList.begin();
 
-        for (std::list<DBrush *>::const_iterator buildBrush = brushList.begin();
-             buildBrush != brushList.end(); buildBrush++) {
-                 (*buildBrush)->BuildInRadiant(allowDestruction, NULL, node.get_pointer());
-        }
+       while ( chkBrush != brushList.end() )
+       {
+               if ( !useDetail ) {
+                       if ( ( *chkBrush )->IsDetail() ) {
+                               delete *chkBrush;
+                               chkBrush = brushList.erase( chkBrush );
+                               continue;
+                       }
+               }
 
-        for (std::list<DPatch *>::const_iterator buildPatch = patchList.begin();
-             buildPatch != patchList.end(); buildPatch++) {
-                 (*buildPatch)->BuildInRadiant(node.get_pointer());
-        }
+               std::list<Str>::iterator eTexture;
 
-        QER_Entity = node.get_pointer();
-    } else {
-        for (std::list<DBrush *>::const_iterator buildBrush = brushList.begin();
-             buildBrush != brushList.end(); buildBrush++) {
-                 (*buildBrush)->BuildInRadiant(allowDestruction, NULL);
-        }
+               for ( eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++ )
+               {
+                       if ( ( *chkBrush )->HasTexture( ( *eTexture ).GetBuffer() ) ) {
+                               delete *chkBrush;
+                               chkBrush = brushList.erase( chkBrush );
+                               break;
+                       }
+               }
 
-        for (std::list<DPatch *>::const_iterator buildPatch = patchList.begin();
-             buildPatch != patchList.end(); buildPatch++) {
-                 (*buildPatch)->BuildInRadiant();
-        }
-    }
+               if ( eTexture == exclusionList->end() ) {
+                       chkBrush++;
+               }
+       }
 }
 
-
-int DEntity::GetIDMax(void)
-{
-    int max = -1;
-    for (std::list<DBrush *>::const_iterator cntBrush = brushList.begin(); cntBrush != brushList.end(); cntBrush++) {
-        if ((*cntBrush)->m_nBrushID > max) {
-            max = (*cntBrush)->m_nBrushID;
-        }
-    }
-    return max + 1;
+void DEntity::ResetChecks( std::list<Str>* exclusionList ){
+       for ( std::list<DBrush *>::const_iterator resetBrush = brushList.begin(); resetBrush != brushList.end(); resetBrush++ )
+       {
+               ( *resetBrush )->ResetChecks( exclusionList );
+       }
 }
 
-void DEntity::SetClassname(const char *classname)
-{
-    m_Classname = classname;
+int DEntity::FixBrushes(){
+       int count = 0;
+
+       for ( std::list<DBrush *>::const_iterator fixBrush = brushList.begin(); fixBrush != brushList.end(); fixBrush++ )
+       {
+               count += ( *fixBrush )->RemoveRedundantPlanes();
+       }
+
+       return count;
 }
 
-void DEntity::SaveToFile(FILE *pFile)
-{
-    fprintf(pFile, "{\n");
+void DEntity::BuildInRadiant( bool allowDestruction ){
+       bool makeEntity = strcmp( m_Classname, "worldspawn" ) ? true : false;
+
+       if ( makeEntity ) {
+               NodeSmartReference node( GlobalEntityCreator().createEntity( GlobalEntityClassManager().findOrInsert( m_Classname.GetBuffer(), !brushList.empty() || !patchList.empty() ) ) );
+
+               for ( std::list<DEPair* >::const_iterator buildEPair = epairList.begin(); buildEPair != epairList.end(); buildEPair++ )
+               {
+                       Node_getEntity( node )->setKeyValue( ( *buildEPair )->key, ( *buildEPair )->value );
+               }
 
-    fprintf(pFile, "\"classname\" \"%s\"\n", (const char *) m_Classname);
+               Node_getTraversable( GlobalSceneGraph().root() )->insert( node );
 
-    for (std::list<DEPair *>::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++) {
-        fprintf(pFile, "\"%s\" \"%s\"\n", (const char *) (*ep)->key, (const char *) (*ep)->value);
-    }
+               for ( std::list<DBrush *>::const_iterator buildBrush = brushList.begin(); buildBrush != brushList.end(); buildBrush++ )
+                       ( *buildBrush )->BuildInRadiant( allowDestruction, NULL, node.get_pointer() );
 
-    for (std::list<DBrush *>::const_iterator bp = brushList.begin(); bp != brushList.end(); bp++) {
-        (*bp)->SaveToFile(pFile);
-    }
+               for ( std::list<DPatch *>::const_iterator buildPatch = patchList.begin(); buildPatch != patchList.end(); buildPatch++ )
+                       ( *buildPatch )->BuildInRadiant( node.get_pointer() );
 
-    fprintf(pFile, "}\n");
+               QER_Entity = node.get_pointer();
+       }
+       else
+       {
+               for ( std::list<DBrush *>::const_iterator buildBrush = brushList.begin(); buildBrush != brushList.end(); buildBrush++ )
+                       ( *buildBrush )->BuildInRadiant( allowDestruction, NULL );
+
+               for ( std::list<DPatch *>::const_iterator buildPatch = patchList.begin(); buildPatch != patchList.end(); buildPatch++ )
+                       ( *buildPatch )->BuildInRadiant();
+       }
 }
 
-void DEntity::ClearEPairs()
-{
-    for (std::list<DEPair *>::const_iterator deadEPair = epairList.begin(); deadEPair != epairList.end(); deadEPair++) {
-        delete (*deadEPair);
-    }
-    epairList.clear();
+int DEntity::GetIDMax( void ) {
+       int max = -1;
+       for ( std::list<DBrush *>::const_iterator cntBrush = brushList.begin(); cntBrush != brushList.end(); cntBrush++ ) {
+               if ( ( *cntBrush )->m_nBrushID > max ) {
+                       max = ( *cntBrush )->m_nBrushID;
+               }
+       }
+       return max + 1;
 }
 
-void DEntity::AddEPair(const char *key, const char *value)
-{
-    DEPair *newEPair;
-    newEPair = FindEPairByKey(key);
-    if (!newEPair) {
-        newEPair = new DEPair;
-        newEPair->Build(key, value);
-        epairList.push_back(newEPair);
-    } else {
-        newEPair->Build(key, 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);
-            } else {
-                m_entity->AddEPair(key, value);
-            }
-        }
-
-    } load_epairs(this);
-
-    epl->forEachKeyValue(load_epairs);
-}
-
-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)
-{
-    bool reset = false;
-
-    for (std::list<DBrush *>::const_iterator resetBrush = brushList.begin();
-         resetBrush != brushList.end(); resetBrush++) {
-        bool tmp = (*resetBrush)->ResetTextures(textureName, fScale, fShift, rotation, newTextureName,
-                                                bResetTextureName, bResetScale, bResetShift, bResetRotation);
-
-        if (tmp) {
-            reset = true;
-            if (rebuild) {
-                Node_getTraversable(*(*resetBrush)->QER_entity)->erase(*(*resetBrush)->QER_brush);
-                (*resetBrush)->BuildInRadiant(false, NULL, (*resetBrush)->QER_entity);
-            }
-        }
-    }
-
-    if (bResetTextureName) {
-        for (std::list<DPatch *>::const_iterator resetPatch = patchList.begin();
-             resetPatch != patchList.end(); resetPatch++) {
-            bool tmp = (*resetPatch)->ResetTextures(textureName, newTextureName);
-
-            if (tmp) {
-                reset = true;
-                if (rebuild) {
-                    Node_getTraversable(*(*resetPatch)->QER_entity)->erase(*(*resetPatch)->QER_brush);
-                    (*resetPatch)->BuildInRadiant((*resetPatch)->QER_entity);
-                }
-            }
-        }
-    }
-
-    return reset;
-}
-
-DEPair *DEntity::FindEPairByKey(const char *keyname)
-{
-    for (std::list<DEPair *>::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++) {
-        char *c = (*ep)->key;
-        if (!strcmp(c, keyname)) {
-            return *ep;
-        }
-    }
-    return NULL;
+void DEntity::SetClassname( const char *classname ) {
+       m_Classname = classname;
 }
 
-void DEntity::RemoveFromRadiant()
-{
-    Node_getTraversable(GlobalSceneGraph().root())->erase(*QER_Entity);
+void DEntity::SaveToFile( FILE *pFile ){
+       fprintf( pFile, "{\n" );
 
-    QER_Entity = NULL;
-}
+       fprintf( pFile, "\"classname\" \"%s\"\n", (const char *)m_Classname );
 
-void DEntity::SpawnString(const char *key, const char *defaultstring, const char **out)
-{
-    DEPair *pEP = FindEPairByKey(key);
-    if (pEP) {
-        *out = pEP->value;
-    } else {
-        *out = defaultstring;
-    }
-}
+       for ( std::list<DEPair *>::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++ )
+       {
+               fprintf( pFile, "\"%s\" \"%s\"\n", (const char *)( *ep )->key, (const char *)( *ep )->value );
+       }
 
-void DEntity::SpawnInt(const char *key, const char *defaultstring, int *out)
-{
-    DEPair *pEP = FindEPairByKey(key);
-    if (pEP) {
-        *out = atoi(pEP->value);
-    } else {
-        *out = atoi(defaultstring);
-    }
-}
+       for ( std::list<DBrush *>::const_iterator bp = brushList.begin(); bp != brushList.end(); bp++ )
+       {
+               ( *bp )->SaveToFile( pFile );
+       }
 
-void DEntity::SpawnFloat(const char *key, const char *defaultstring, float *out)
-{
-    DEPair *pEP = FindEPairByKey(key);
-    if (pEP) {
-        *out = static_cast<float>( atof(pEP->value));
-    } else {
-        *out = static_cast<float>( atof(defaultstring));
-    }
+       fprintf( pFile, "}\n" );
 }
 
-void DEntity::SpawnVector(const char *key, const char *defaultstring, vec_t *out)
-{
-    DEPair *pEP = FindEPairByKey(key);
-    if (pEP) {
-        sscanf(pEP->value, "%f %f %f", &out[0], &out[1], &out[2]);
-    } else {
-        sscanf(defaultstring, "%f %f %f", &out[0], &out[1], &out[2]);
-    }
+void DEntity::ClearEPairs(){
+       for ( std::list<DEPair *>::const_iterator deadEPair = epairList.begin(); deadEPair != epairList.end(); deadEPair++ )
+       {
+               delete ( *deadEPair );
+       }
+       epairList.clear();
 }
 
-int DEntity::GetBrushCount(void)
-{
-    return static_cast<int>( brushList.size());
+void DEntity::AddEPair( const char *key, const char *value ) {
+       DEPair* newEPair;
+       newEPair = FindEPairByKey( key );
+       if ( !newEPair ) {
+               newEPair = new DEPair;
+               newEPair->Build( key, value );
+               epairList.push_back( newEPair );
+       }
+       else {
+               newEPair->Build( key, value );
+       }
 }
 
-DBrush *DEntity::FindBrushByPointer(scene::Node &brush)
-{
-    for (std::list<DBrush *>::const_iterator listBrush = brushList.begin(); listBrush != brushList.end(); listBrush++) {
-        DBrush *pBrush = (*listBrush);
-        if (pBrush->QER_brush == &brush) {
-            return pBrush;
-        }
-    }
-    return NULL;
+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 );
+               }
+               else{
+                       m_entity->AddEPair( key, value );
+               }
+       }
+
+       } load_epairs( this );
+
+       epl->forEachKeyValue( load_epairs );
+}
+
+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 ){
+       bool reset = false;
+
+       for ( std::list<DBrush *>::const_iterator resetBrush = brushList.begin(); resetBrush != brushList.end(); resetBrush++ )
+       {
+               bool tmp = ( *resetBrush )->ResetTextures( textureName,        fScale,       fShift,       rotation, newTextureName,
+                                                                                                  bResetTextureName,  bResetScale,  bResetShift,  bResetRotation );
+
+               if ( tmp ) {
+                       reset = true;
+                       if ( rebuild ) {
+                               Node_getTraversable( *( *resetBrush )->QER_entity )->erase( *( *resetBrush )->QER_brush );
+                               ( *resetBrush )->BuildInRadiant( false, NULL, ( *resetBrush )->QER_entity );
+                       }
+               }
+       }
+
+       if ( bResetTextureName ) {
+               for ( std::list<DPatch *>::const_iterator resetPatch = patchList.begin(); resetPatch != patchList.end(); resetPatch++ )
+               {
+                       bool tmp = ( *resetPatch )->ResetTextures( textureName, newTextureName );
+
+                       if ( tmp ) {
+                               reset = true;
+                               if ( rebuild ) {
+                                       Node_getTraversable( *( *resetPatch )->QER_entity )->erase( *( *resetPatch )->QER_brush );
+                                       ( *resetPatch )->BuildInRadiant( ( *resetPatch )->QER_entity );
+                               }
+                       }
+               }
+       }
+
+       return reset;
+}
+
+DEPair* DEntity::FindEPairByKey( const char* keyname ){
+       for ( std::list<DEPair *>::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++ )
+       {
+               char* c = ( *ep )->key;
+               if ( !strcmp( c, keyname ) ) {
+                       return *ep;
+               }
+       }
+       return NULL;
+}
+
+void DEntity::RemoveFromRadiant(){
+       Node_getTraversable( GlobalSceneGraph().root() )->erase( *QER_Entity );
+
+       QER_Entity = NULL;
+}
+
+void DEntity::SpawnString( const char* key, const char* defaultstring, const char** out ){
+       DEPair* pEP = FindEPairByKey( key );
+       if ( pEP ) {
+               *out = pEP->value;
+       }
+       else {
+               *out = defaultstring;
+       }
+}
+
+void DEntity::SpawnInt( const char* key, const char* defaultstring, int* out ){
+       DEPair* pEP = FindEPairByKey( key );
+       if ( pEP ) {
+               *out = atoi( pEP->value );
+       }
+       else {
+               *out = atoi( defaultstring );
+       }
+}
+
+void DEntity::SpawnFloat( const char* key, const char* defaultstring, float* out ){
+       DEPair* pEP = FindEPairByKey( key );
+       if ( pEP ) {
+               *out = static_cast<float>( atof( pEP->value ) );
+       }
+       else {
+               *out = static_cast<float>( atof( defaultstring ) );
+       }
+}
+
+void DEntity::SpawnVector( const char* key, const char* defaultstring, vec_t* out ){
+       DEPair* pEP = FindEPairByKey( key );
+       if ( pEP ) {
+               sscanf( pEP->value, "%f %f %f", &out[0], &out[1], &out[2] );
+       }
+       else {
+               sscanf( defaultstring, "%f %f %f", &out[0], &out[1], &out[2] );
+       }
+}
+
+int DEntity::GetBrushCount( void ) {
+       return static_cast<int>( brushList.size() );
+}
+
+DBrush* DEntity::FindBrushByPointer( scene::Node& brush ) {
+       for ( std::list<DBrush *>::const_iterator listBrush = brushList.begin(); listBrush != brushList.end(); listBrush++ ) {
+               DBrush* pBrush = ( *listBrush );
+               if ( pBrush->QER_brush == &brush ) {
+                       return pBrush;
+               }
+       }
+       return NULL;
 }
index 65ae595..281193f 100644 (file)
 #include "png.h"
 #include <stdlib.h>
 
-void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
-{
-    globalErrorStream() << "libpng warning: " << warning_msg << "\n";
+void user_warning_fn( png_structp png_ptr, png_const_charp warning_msg ){
+       globalErrorStream() << "libpng warning: " << warning_msg << "\n";
 }
 
-void user_error_fn(png_structp png_ptr, png_const_charp error_msg)
-{
-    globalErrorStream() << "libpng error: " << error_msg << "\n";
-    longjmp(png_jmpbuf(png_ptr), 0);
+void user_error_fn( png_structp png_ptr, png_const_charp error_msg ){
+       globalErrorStream() << "libpng error: " << error_msg << "\n";
+       longjmp( png_jmpbuf(png_ptr), 0 );
 }
 
-void user_read_data(png_structp png_ptr, png_bytep data, png_uint_32 length)
-{
-    png_bytep *p_p_fbuffer = (png_bytep *) png_get_io_ptr(png_ptr);
-    memcpy(data, *p_p_fbuffer, length);
-    *p_p_fbuffer += length;
+void user_read_data( png_structp png_ptr, png_bytep data, png_uint_32 length ){
+       png_bytep *p_p_fbuffer = (png_bytep*)png_get_io_ptr( png_ptr );
+       memcpy( data, *p_p_fbuffer, length );
+       *p_p_fbuffer += length;
 }
 
-Image *LoadPNGBuff(unsigned char *fbuffer)
-{
-    png_byte **row_pointers;
-    png_bytep p_fbuffer;
-
-    p_fbuffer = fbuffer;
-
-    // the reading glue
-    // 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);
-    if (!png_ptr) {
-        globalErrorStream() << "libpng error: png_create_read_struct\n";
-        return 0;
-    }
-
-    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);
-        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);
-        globalErrorStream() << "libpng error: png_create_info_struct (end_info)\n";
-        return 0;
-    }
-
-    // configure the read function
-    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);
-        return 0;
-    }
-
-    png_read_info(png_ptr, info_ptr);
-
-    int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
-    int color_type = png_get_color_type(png_ptr, info_ptr);
-
-    // we want to treat all images the same way
-    //   The following code transforms grayscale images of less than 8 to 8 bits,
-    //   changes paletted images to RGB, and adds a full alpha channel if there is
-    //   transparency information in a tRNS chunk.
-
-    if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
-        png_set_gray_to_rgb(png_ptr);
-    } else if (color_type == PNG_COLOR_TYPE_PALETTE) {
-        png_set_palette_to_rgb(png_ptr);
-    }
-
-    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
-        png_set_expand_gray_1_2_4_to_8(png_ptr);
-    }
-
-    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
-        png_set_tRNS_to_alpha(png_ptr);
-    } else if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
-        // Set the background color to draw transparent and alpha images over.
-        png_color_16 my_background, *image_background;
-
-        if (png_get_bKGD(png_ptr, info_ptr, &image_background)) {
-            png_set_background(png_ptr, image_background,
-                               PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
-        } else {
-            png_set_background(png_ptr, &my_background,
-                               PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
-        }
-
-        // Add alpha byte after each RGB triplet
-        png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
-    }
-
-    // read the sucker in one chunk
-    png_read_update_info(png_ptr, info_ptr);
-
-    color_type = png_get_color_type(png_ptr, info_ptr);
-    bit_depth = png_get_bit_depth(png_ptr, info_ptr);
-
-    int width = png_get_image_width(png_ptr, info_ptr);
-    int height = png_get_image_height(png_ptr, info_ptr);
-
-    // allocate the pixel buffer, and the row pointers
-    RGBAImage *image = new RGBAImage(width, height);
-
-    row_pointers = (png_byte **) malloc((height) * sizeof(png_byte *));
-
-    int i;
-    for (i = 0; i < (height); i++) {
-        row_pointers[i] = (png_byte *) (image->getRGBAPixels()) + i * 4 * (width);
-    }
-
-    // actual read
-    png_read_image(png_ptr, row_pointers);
-
-    /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
-    png_read_end(png_ptr, info_ptr);
-
-    /* free up the memory structure */
-    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
-
-    free(row_pointers);
-
-    return image;
+Image* LoadPNGBuff( unsigned char* fbuffer ){
+       png_byte** row_pointers;
+       png_bytep p_fbuffer;
+
+       p_fbuffer = fbuffer;
+
+       // the reading glue
+       // 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 );
+       if ( !png_ptr ) {
+               globalErrorStream() << "libpng error: png_create_read_struct\n";
+               return 0;
+       }
+
+       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 );
+               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 );
+               globalErrorStream() << "libpng error: png_create_info_struct (end_info)\n";
+               return 0;
+       }
+
+       // configure the read function
+       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 );
+               return 0;
+       }
+
+       png_read_info( png_ptr, info_ptr );
+
+       int bit_depth = png_get_bit_depth( png_ptr, info_ptr );
+       int color_type = png_get_color_type( png_ptr, info_ptr );
+
+       // we want to treat all images the same way
+       //   The following code transforms grayscale images of less than 8 to 8 bits,
+       //   changes paletted images to RGB, and adds a full alpha channel if there is
+       //   transparency information in a tRNS chunk.
+
+       if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) {
+               png_set_gray_to_rgb( png_ptr );
+       }
+       else if ( color_type == PNG_COLOR_TYPE_PALETTE ) {
+               png_set_palette_to_rgb( png_ptr );
+       }
+
+       if ( color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8 ) {
+               png_set_expand_gray_1_2_4_to_8( png_ptr );
+       }
+
+       if ( png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS ) ) {
+               png_set_tRNS_to_alpha( png_ptr );
+       }
+
+       if ( !( color_type & PNG_COLOR_MASK_ALPHA ) ) {
+               // Set the background color to draw transparent and alpha images over.
+               png_color_16 my_background, *image_background;
+
+               if ( png_get_bKGD( png_ptr, info_ptr, &image_background ) ) {
+                       png_set_background( png_ptr, image_background,
+                                                               PNG_BACKGROUND_GAMMA_FILE, 1, 1.0 );
+               }
+               else{
+                       png_set_background( png_ptr, &my_background,
+                                                               PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0 );
+               }
+
+               // Add alpha byte after each RGB triplet
+               png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER );
+       }
+
+       // read the sucker in one chunk
+       png_read_update_info( png_ptr, info_ptr );
+
+       color_type = png_get_color_type( png_ptr, info_ptr );
+       bit_depth = png_get_bit_depth( png_ptr, info_ptr );
+
+       int width = png_get_image_width( png_ptr, info_ptr );
+       int height = png_get_image_height( png_ptr, info_ptr );
+
+       // allocate the pixel buffer, and the row pointers
+       RGBAImage* image = new RGBAImage( width, height );
+
+       row_pointers = (png_byte**) malloc( ( height ) * sizeof( png_byte* ) );
+
+       int i;
+       for ( i = 0; i < ( height ); i++ )
+               row_pointers[i] = (png_byte*)( image->getRGBAPixels() ) + i * 4 * ( width );
+
+       // actual read
+       png_read_image( png_ptr, row_pointers );
+
+       /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
+       png_read_end( png_ptr, info_ptr );
+
+       /* free up the memory structure */
+       png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
+
+       free( row_pointers );
+
+       return image;
 }
 
-Image *LoadPNG(ArchiveFile &file)
-{
-    ScopedArchiveBuffer buffer(file);
-    return LoadPNGBuff(buffer.buffer);
+Image* LoadPNG( ArchiveFile& file ){
+       ScopedArchiveBuffer buffer( file );
+       return LoadPNGBuff( buffer.buffer );
 }
 
 
 #include "modulesystem/singletonmodule.h"
 
 
-class ImageDependencies : public GlobalFileSystemModuleRef {
+class ImageDependencies : public GlobalFileSystemModuleRef
+{
 };
 
-class ImagePNGAPI {
-    _QERPlugImageTable m_imagepng;
+class ImagePNGAPI
+{
+_QERPlugImageTable m_imagepng;
 public:
-    typedef _QERPlugImageTable Type;
+typedef _QERPlugImageTable Type;
 
-    STRING_CONSTANT(Name, "png");
+STRING_CONSTANT( Name, "png" );
 
-    ImagePNGAPI()
-    {
-        m_imagepng.loadImage = LoadPNG;
-    }
+ImagePNGAPI(){
+       m_imagepng.loadImage = LoadPNG;
+}
 
-    _QERPlugImageTable *getTable()
-    {
-        return &m_imagepng;
-    }
+_QERPlugImageTable* getTable(){
+       return &m_imagepng;
+}
 };
 
 typedef SingletonModule<ImagePNGAPI, ImageDependencies> ImagePNGModule;
@@ -199,9 +197,8 @@ typedef SingletonModule<ImagePNGAPI, ImageDependencies> ImagePNGModule;
 ImagePNGModule g_ImagePNGModule;
 
 
-extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer &server)
-{
-    initialiseModule(server);
+extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){
+       initialiseModule( server );
 
-    g_ImagePNGModule.selfRegister();
+       g_ImagePNGModule.selfRegister();
 }
index 8f48f3b..5e6a014 100644 (file)
@@ -27,5 +27,4 @@ class ArchiveFile;
 
 scene::Node &loadIQMModel( ArchiveFile &file );
 
-
 #endif
index c6bfe6c..c94ee67 100644 (file)
@@ -21,5 +21,4 @@
 
 #if !defined( INCLUDED_SAMPLE_H )
 #define INCLUDED_SAMPLE_H
-
 #endif
index af04cea..8b427d4 100644 (file)
 
 
 class MapDoom3Dependencies :
-        public GlobalRadiantModuleRef,
-        public GlobalFiletypesModuleRef,
-        public GlobalScripLibModuleRef,
-        public GlobalEntityClassManagerModuleRef,
-        public GlobalSceneGraphModuleRef,
-        public GlobalBrushModuleRef {
-    PatchModuleRef m_patchDef2Doom3Module;
-    PatchModuleRef m_patchDoom3Module;
+       public GlobalRadiantModuleRef,
+       public GlobalFiletypesModuleRef,
+       public GlobalScripLibModuleRef,
+       public GlobalEntityClassManagerModuleRef,
+       public GlobalSceneGraphModuleRef,
+       public GlobalBrushModuleRef
+{
+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 GlobalBrushModule::getTable();
-    }
-
-    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 GlobalBrushModule::getTable();
+}
+
+PatchCreator& getPatchDoom3(){
+       return *m_patchDoom3Module.getTable();
+}
+
+PatchCreator& getPatchDef2Doom3(){
+       return *m_patchDef2Doom3Module.getTable();
+}
 };
 
-class MapDoom3API : public TypeSystemRef, public MapFormat, public PrimitiveParser {
-    MapDoom3Dependencies &m_dependencies;
+class MapDoom3API : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
+MapDoom3Dependencies& m_dependencies;
 public:
-    typedef MapFormat Type;
-
-    STRING_CONSTANT(Name, "mapdoom3");
-
-    UINT_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();
-            }
-        }
-
-        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;
-        }
-        std::size_t version;
-        if (!Tokeniser_getSize(tokeniser, version)) {
-            return;
-        }
-        if (version != MapVersion()) {
-            globalErrorStream() << "Doom 3 map version " << MapVersion() << " supported, version is "
-                                << Unsigned(version) << "\n";
-            return;
-        }
-        tokeniser.nextLine();
-        Map_Read(root, tokeniser, entityTable, *this);
-        tokeniser.release();
-    }
-
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        writer.writeToken("Version");
-        writer.writeInteger(MapVersion());
-        writer.nextLine();
-        Map_Write(root, traverse, writer, false, writeComments);
-        writer.release();
-    }
+typedef MapFormat Type;
+
+STRING_CONSTANT( Name, "mapdoom3" );
+
+UINT_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();
+               }
+       }
+
+       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;
+       }
+       std::size_t version;
+       if ( !Tokeniser_getSize( tokeniser, version ) ) {
+               return;
+       }
+       if ( version != MapVersion() ) {
+               globalErrorStream() << "Doom 3 map version " << MapVersion() << " supported, version is " << Unsigned( version ) << "\n";
+               return;
+       }
+       tokeniser.nextLine();
+       Map_Read( root, tokeniser, entityTable, *this );
+       tokeniser.release();
+}
+
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       writer.writeToken( "Version" );
+       writer.writeInteger( MapVersion() );
+       writer.nextLine();
+       Map_Write( root, traverse, writer, false, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<
-        MapDoom3API,
-        MapDoom3Dependencies,
-        DependenciesAPIConstructor<MapDoom3API, MapDoom3Dependencies>
->
-        MapDoom3Module;
+       MapDoom3API,
+       MapDoom3Dependencies,
+       DependenciesAPIConstructor<MapDoom3API, MapDoom3Dependencies>
+       >
+MapDoom3Module;
 
 MapDoom3Module g_MapDoom3Module;
 
 
-class MapQuake4API : public TypeSystemRef, public MapFormat, public PrimitiveParser {
-    MapDoom3Dependencies &m_dependencies;
+class MapQuake4API : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
+MapDoom3Dependencies& m_dependencies;
 public:
-    typedef MapFormat Type;
-
-    STRING_CONSTANT(Name, "mapquake4");
-
-    UINT_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();
-            }
-        }
-
-        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;
-        }
-        std::size_t version;
-        if (!Tokeniser_getSize(tokeniser, version)) {
-            return;
-        }
-        if (version != MapVersion()) {
-            globalErrorStream() << "Quake 4 map version " << MapVersion() << " supported, version is "
-                                << Unsigned(version) << "\n";
-            return;
-        }
-        tokeniser.nextLine();
-        Map_Read(root, tokeniser, entityTable, *this);
-        tokeniser.release();
-    }
-
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        writer.writeToken("Version");
-        writer.writeInteger(MapVersion());
-        writer.nextLine();
-        Map_Write(root, traverse, writer, false, writeComments);
-        writer.release();
-    }
+typedef MapFormat Type;
+
+STRING_CONSTANT( Name, "mapquake4" );
+
+UINT_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();
+               }
+       }
+
+       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;
+       }
+       std::size_t version;
+       if ( !Tokeniser_getSize( tokeniser, version ) ) {
+               return;
+       }
+       if ( version != MapVersion() ) {
+               globalErrorStream() << "Quake 4 map version " << MapVersion() << " supported, version is " << Unsigned( version ) << "\n";
+               return;
+       }
+       tokeniser.nextLine();
+       Map_Read( root, tokeniser, entityTable, *this );
+       tokeniser.release();
+}
+
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       writer.writeToken( "Version" );
+       writer.writeInteger( MapVersion() );
+       writer.nextLine();
+       Map_Write( root, traverse, writer, false, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<
-        MapQuake4API,
-        MapDoom3Dependencies,
-        DependenciesAPIConstructor<MapQuake4API, MapDoom3Dependencies>
->
-        MapQuake4Module;
+       MapQuake4API,
+       MapDoom3Dependencies,
+       DependenciesAPIConstructor<MapQuake4API, MapDoom3Dependencies>
+       >
+MapQuake4Module;
 
 MapQuake4Module g_MapQuake4Module;
 
 
 class MapDependencies :
-        public GlobalRadiantModuleRef,
-        public GlobalBrushModuleRef,
-        public GlobalPatchModuleRef,
-        public GlobalFiletypesModuleRef,
-        public GlobalScripLibModuleRef,
-        public GlobalEntityClassManagerModuleRef,
-        public GlobalSceneGraphModuleRef {
+       public GlobalRadiantModuleRef,
+       public GlobalBrushModuleRef,
+       public GlobalPatchModuleRef,
+       public GlobalFiletypesModuleRef,
+       public GlobalScripLibModuleRef,
+       public GlobalEntityClassManagerModuleRef,
+       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 : public TypeSystemRef, public MapFormat, public PrimitiveParser {
-    mutable bool detectedFormat;
+class MapQ3API : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
+mutable bool detectedFormat;
 public:
-    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 (GlobalBrushModule::getTable().useAlternativeTextureProjection()) {
-                if (string_equal(primitive, "brushDef")) {
-                    detectedFormat = true;
-                    return GlobalBrushModule::getTable().createBrush();
-                } else if (!detectedFormat && string_equal(primitive, "(")) {
-                    detectedFormat = true;
-                    wrongFormat = true;
-                    Tokeniser_unexpectedError(tokeniser, primitive, "#quake3-switch-to-texdef");
-                    return g_nullNode;
-                }
-            } else {
-                if (string_equal(primitive, "(")) {
-                    detectedFormat = true;
-                    tokeniser.ungetToken(); // (
-                    return GlobalBrushModule::getTable().createBrush();
-                } else if (!detectedFormat && string_equal(primitive, "brushDef")) {
-                    detectedFormat = true;
-                    wrongFormat = true;
-                    Tokeniser_unexpectedError(tokeniser, primitive, "#quake3-switch-to-brush-primitives");
-                    return g_nullNode;
-                }
-            }
-        }
-
-        Tokeniser_unexpectedError(tokeniser, primitive, "#quake3-primitive");
-        return g_nullNode;
-    }
-
-    void readGraph(scene::Node &root, TextInputStream &inputStream, EntityCreator &entityTable) const
-    {
-        detectedFormat = false;
-        wrongFormat = false;
-        Tokeniser &tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser(inputStream);
-        Map_Read(root, tokeniser, entityTable, *this);
-        tokeniser.release();
-    }
-
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        Map_Write(root, traverse, writer, false, writeComments);
-        writer.release();
-    }
+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 ( GlobalBrushModule::getTable().useAlternativeTextureProjection() ) {
+                       if ( string_equal( primitive, "brushDef" ) ) {
+                               detectedFormat = true;
+                               return GlobalBrushModule::getTable().createBrush();
+                       }
+                       else if ( !detectedFormat && string_equal( primitive, "(" ) ) {
+                               detectedFormat = true;
+                               wrongFormat = true;
+                               Tokeniser_unexpectedError( tokeniser, primitive, "#quake3-switch-to-texdef" );
+                               return g_nullNode;
+                       }
+               }
+               else
+               {
+                       if ( string_equal( primitive, "(" ) ) {
+                               detectedFormat = true;
+                               tokeniser.ungetToken(); // (
+                               return GlobalBrushModule::getTable().createBrush();
+                       }
+                       else if ( !detectedFormat && string_equal( primitive, "brushDef" ) ) {
+                               detectedFormat = true;
+                               wrongFormat = true;
+                               Tokeniser_unexpectedError( tokeniser, primitive, "#quake3-switch-to-brush-primitives" );
+                               return g_nullNode;
+                       }
+               }
+       }
+
+       Tokeniser_unexpectedError( tokeniser, primitive, "#quake3-primitive" );
+       return g_nullNode;
+}
+
+void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const {
+       detectedFormat = false;
+       wrongFormat = false;
+       Tokeniser &tokeniser = GlobalScripLibModule::getTable().m_pfnNewSimpleTokeniser( inputStream );
+       Map_Read( root, tokeniser, entityTable, *this );
+       tokeniser.release();
+}
+
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       Map_Write( root, traverse, writer, false, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<MapQ3API, MapDependencies> MapQ3Module;
@@ -325,50 +311,45 @@ typedef SingletonModule<MapQ3API, MapDependencies> MapQ3Module;
 MapQ3Module g_MapQ3Module;
 
 
-class MapQ1API : public TypeSystemRef, public MapFormat, public PrimitiveParser {
+class MapQ1API : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
 public:
-    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 (string_equal(primitive, "(")) {
-                tokeniser.ungetToken(); // (
-                return GlobalBrushModule::getTable().createBrush();
-            }
-        }
-
-        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);
-        Map_Read(root, tokeniser, entityTable, *this);
-        tokeniser.release();
-    }
-
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        Map_Write(root, traverse, writer, true, writeComments);
-        writer.release();
-    }
+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 ( string_equal( primitive, "(" ) ) {
+                       tokeniser.ungetToken(); // (
+                       return GlobalBrushModule::getTable().createBrush();
+               }
+       }
+
+       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 );
+       Map_Read( root, tokeniser, entityTable, *this );
+       tokeniser.release();
+}
+
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       Map_Write( root, traverse, writer, true, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<MapQ1API, MapDependencies> MapQ1Module;
@@ -376,50 +357,46 @@ typedef SingletonModule<MapQ1API, MapDependencies> MapQ1Module;
 MapQ1Module g_MapQ1Module;
 
 
-class MapHalfLifeAPI : public TypeSystemRef, public MapFormat, public PrimitiveParser {
+class MapHalfLifeAPI : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
 public:
-    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 GlobalBrushModule::getTable().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, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        Map_Write(root, traverse, writer, true, writeComments);
-        writer.release();
-    }
+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 GlobalBrushModule::getTable().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, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       Map_Write( root, traverse, writer, true, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<MapHalfLifeAPI, MapDependencies> MapHalfLifeModule;
@@ -427,50 +404,44 @@ typedef SingletonModule<MapHalfLifeAPI, MapDependencies> MapHalfLifeModule;
 MapHalfLifeModule g_MapHalfLifeModule;
 
 
-class MapQ2API : public TypeSystemRef, public MapFormat, public PrimitiveParser {
+class MapQ2API : public TypeSystemRef, public MapFormat, public PrimitiveParser
+{
 public:
-    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 (string_equal(primitive, "(")) {
-                tokeniser.ungetToken(); // (
-                return GlobalBrushModule::getTable().createBrush();
-            }
-        }
-
-        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);
-        Map_Read(root, tokeniser, entityTable, *this);
-        tokeniser.release();
-    }
-
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        TokenWriter &writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter(outputStream);
-        Map_Write(root, traverse, writer, true, writeComments);
-        writer.release();
-    }
+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 ( string_equal( primitive, "(" ) ) {
+                       tokeniser.ungetToken(); // (
+                       return GlobalBrushModule::getTable().createBrush();
+               }
+       }
+
+       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 );
+       Map_Read( root, tokeniser, entityTable, *this );
+       tokeniser.release();
+}
+
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       TokenWriter& writer = GlobalScripLibModule::getTable().m_pfnNewSimpleTokenWriter( outputStream );
+       Map_Write( root, traverse, writer, true, writeComments );
+       writer.release();
+}
 };
 
 typedef SingletonModule<MapQ2API, MapDependencies> MapQ2Module;
@@ -480,9 +451,8 @@ MapQ2Module g_MapQ2Module;
 
 const char *PARSE_ERROR = "error parsing VMF";
 
-inline void parseToken(Tokeniser &tokeniser, const char *token)
-{
-    ASSERT_MESSAGE(Tokeniser_parseToken(tokeniser, token), "error parsing vmf: token not found: " << makeQuoted(token));
+inline void parseToken( Tokeniser& tokeniser, const char* token ){
+       ASSERT_MESSAGE( Tokeniser_parseToken( tokeniser, token ), "error parsing vmf: token not found: " << makeQuoted( token ) );
 }
 
 #include "generic/arrayrange.h"
@@ -492,75 +462,67 @@ class VMFBlock;
 typedef ArrayConstRange<VMFBlock> VMFBlockArrayRange;
 
 
-class VMFBlock {
+class VMFBlock
+{
 public:
-    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;
-    }
+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;
+}
 };
 
-const VMFBlock c_vmfNormals("normals");
-const VMFBlock c_vmfDistances("distances");
-const VMFBlock c_vmfOffsets("offsets");
-const VMFBlock c_vmfOffsetNormals("offset_normals");
-const VMFBlock c_vmfAlphas("alphas");
-const VMFBlock c_vmfTriangleTags("triangle_tags");
-const VMFBlock c_vmfAllowedVerts("allowed_verts");
-const VMFBlock c_vmfDispInfoChildren[] = {c_vmfNormals, c_vmfDistances, c_vmfOffsets, c_vmfOffsetNormals, c_vmfAlphas,
-                                          c_vmfTriangleTags, c_vmfAllowedVerts};
-const VMFBlock c_vmfDispInfo("dispinfo", ARRAY_RANGE(c_vmfDispInfoChildren));
-const VMFBlock c_vmfSideChildren[] = {c_vmfDispInfo};
-const VMFBlock c_vmfSide("side", ARRAY_RANGE(c_vmfSideChildren));
-const VMFBlock c_vmfEditor("editor");
-const VMFBlock c_vmfVersionInfo("versioninfo");
-const VMFBlock c_vmfViewSettings("viewsettings");
-const VMFBlock c_vmfCordon("cordon");
-const VMFBlock c_vmfGroupChildren[] = {c_vmfEditor};
-const VMFBlock c_vmfGroup("group", ARRAY_RANGE(c_vmfGroupChildren));
-const VMFBlock c_vmfCamera("camera");
-const VMFBlock c_vmfCamerasChildren[] = {c_vmfCamera};
-const VMFBlock c_vmfCameras("cameras", ARRAY_RANGE(c_vmfCamerasChildren));
-VMFBlock c_vmfVisGroup("visgroup");
-VMFBlock c_vmfVisGroups("visgroups", VMFBlockArrayRange(&c_vmfVisGroup, &c_vmfVisGroup + 1));
-const VMFBlock c_vmfSolidChildren[] = {c_vmfSide, c_vmfEditor};
-const VMFBlock c_vmfSolid("solid", ARRAY_RANGE(c_vmfSolidChildren));
-const VMFBlock c_vmfConnections("connections");
-const VMFBlock c_vmfEntityChildren[] = {c_vmfEditor, c_vmfSolid, c_vmfGroup, c_vmfConnections};
-const VMFBlock c_vmfEntity("entity", ARRAY_RANGE(c_vmfEntityChildren));
-const VMFBlock c_vmfWorldChildren[] = {c_vmfEditor, c_vmfSolid, c_vmfGroup};
-const VMFBlock c_vmfWorld("world", ARRAY_RANGE(c_vmfWorldChildren));
-const VMFBlock c_vmfRootChildren[] = {c_vmfVersionInfo, c_vmfViewSettings, c_vmfVisGroups, c_vmfWorld, c_vmfEntity,
-                                      c_vmfCameras, c_vmfCordon};
-const VMFBlock c_vmfRoot("", ARRAY_RANGE(c_vmfRootChildren));
-
-class VMFInit {
+const VMFBlock c_vmfNormals( "normals" );
+const VMFBlock c_vmfDistances( "distances" );
+const VMFBlock c_vmfOffsets( "offsets" );
+const VMFBlock c_vmfOffsetNormals( "offset_normals" );
+const VMFBlock c_vmfAlphas( "alphas" );
+const VMFBlock c_vmfTriangleTags( "triangle_tags" );
+const VMFBlock c_vmfAllowedVerts( "allowed_verts" );
+const VMFBlock c_vmfDispInfoChildren[] = { c_vmfNormals, c_vmfDistances, c_vmfOffsets, c_vmfOffsetNormals, c_vmfAlphas, c_vmfTriangleTags, c_vmfAllowedVerts };
+const VMFBlock c_vmfDispInfo( "dispinfo", ARRAY_RANGE( c_vmfDispInfoChildren ) );
+const VMFBlock c_vmfSideChildren[] = { c_vmfDispInfo };
+const VMFBlock c_vmfSide( "side", ARRAY_RANGE( c_vmfSideChildren ) );
+const VMFBlock c_vmfEditor( "editor" );
+const VMFBlock c_vmfVersionInfo( "versioninfo" );
+const VMFBlock c_vmfViewSettings( "viewsettings" );
+const VMFBlock c_vmfCordon( "cordon" );
+const VMFBlock c_vmfGroupChildren[] = { c_vmfEditor };
+const VMFBlock c_vmfGroup( "group", ARRAY_RANGE( c_vmfGroupChildren ) );
+const VMFBlock c_vmfCamera( "camera" );
+const VMFBlock c_vmfCamerasChildren[] = { c_vmfCamera };
+const VMFBlock c_vmfCameras( "cameras", ARRAY_RANGE( c_vmfCamerasChildren ) );
+VMFBlock c_vmfVisGroup( "visgroup" );
+VMFBlock c_vmfVisGroups( "visgroups", VMFBlockArrayRange( &c_vmfVisGroup, &c_vmfVisGroup + 1 ) );
+const VMFBlock c_vmfSolidChildren[] = { c_vmfSide, c_vmfEditor };
+const VMFBlock c_vmfSolid( "solid", ARRAY_RANGE( c_vmfSolidChildren ) );
+const VMFBlock c_vmfConnections( "connections" );
+const VMFBlock c_vmfEntityChildren[] = { c_vmfEditor, c_vmfSolid, c_vmfGroup, c_vmfConnections };
+const VMFBlock c_vmfEntity( "entity", ARRAY_RANGE( c_vmfEntityChildren ) );
+const VMFBlock c_vmfWorldChildren[] = { c_vmfEditor, c_vmfSolid, c_vmfGroup };
+const VMFBlock c_vmfWorld( "world", ARRAY_RANGE( c_vmfWorldChildren ) );
+const VMFBlock c_vmfRootChildren[] = { c_vmfVersionInfo, c_vmfViewSettings, c_vmfVisGroups, c_vmfWorld, c_vmfEntity, c_vmfCameras, c_vmfCordon };
+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;
@@ -568,82 +530,79 @@ VMFInit g_VMFInit;
 int g_vmf_entities;
 int g_vmf_brushes;
 
-inline VMFBlock::const_iterator VMFBlock_find(const VMFBlock &block, const char *name)
-{
-    for (VMFBlock::const_iterator i = block.begin(); i != block.end(); ++i) {
-        if (string_equal(name, (*i).name())) {
-            return i;
-        }
-    }
-    return block.end();
+inline VMFBlock::const_iterator VMFBlock_find( const VMFBlock& block, const char* name ){
+       for ( VMFBlock::const_iterator i = block.begin(); i != block.end(); ++i )
+       {
+               if ( string_equal( name, ( *i ).name() ) ) {
+                       return i;
+               }
+       }
+       return block.end();
 }
 
-void VMF_parseBlock(Tokeniser &tokeniser, const VMFBlock &block)
-{
-    for (;;) {
-        const char *key = tokeniser.getToken();
-        if (key == 0 || string_equal(key, "}")) {
-            tokeniser.ungetToken();
-            break;
-        }
-        CopiedString tmp(key);
-        tokeniser.nextLine();
-        const char *value = tokeniser.getToken();
-        tokeniser.nextLine();
-        if (string_equal(value, "{")) {
-            VMFBlock::const_iterator i = VMFBlock_find(block, tmp.c_str());
-            ASSERT_MESSAGE(i != block.end(),
-                           "error parsing vmf block " << makeQuoted(block.name()) << ": unknown block: "
-                                                      << makeQuoted(tmp.c_str()));
-            if (string_equal(tmp.c_str(), "solid")) {
-                ++g_vmf_brushes;
-            } else if (string_equal(tmp.c_str(), "entity") || string_equal(tmp.c_str(), "world")) {
-                ++g_vmf_entities;
-            }
-            VMF_parseBlock(tokeniser, *i);
-            parseToken(tokeniser, "}");
-            tokeniser.nextLine();
-        } else {
-            // was a pair
-        }
-    }
-}
-
-void VMF_Read(scene::Node &root, Tokeniser &tokeniser, EntityCreator &entityTable)
-{
-    g_vmf_entities = g_vmf_brushes = 0;
-    VMF_parseBlock(tokeniser, c_vmfRoot);
-    globalOutputStream() << g_vmf_entities << " entities\n";
-    globalOutputStream() << g_vmf_brushes << " brushes\n";
+void VMF_parseBlock( Tokeniser& tokeniser, const VMFBlock& block ){
+       for (;; )
+       {
+               const char* key = tokeniser.getToken();
+               if ( key == 0 || string_equal( key, "}" ) ) {
+                       tokeniser.ungetToken();
+                       break;
+               }
+               CopiedString tmp( key );
+               tokeniser.nextLine();
+               const char* value = tokeniser.getToken();
+               tokeniser.nextLine();
+               if ( string_equal( value, "{" ) ) {
+                       VMFBlock::const_iterator i = VMFBlock_find( block, tmp.c_str() );
+                       ASSERT_MESSAGE( i != block.end(), "error parsing vmf block " << makeQuoted( block.name() ) << ": unknown block: " << makeQuoted( tmp.c_str() ) );
+                       if ( string_equal( tmp.c_str(), "solid" ) ) {
+                               ++g_vmf_brushes;
+                       }
+                       else if ( string_equal( tmp.c_str(), "entity" ) || string_equal( tmp.c_str(), "world" ) ) {
+                               ++g_vmf_entities;
+                       }
+                       VMF_parseBlock( tokeniser, *i );
+                       parseToken( tokeniser, "}" );
+                       tokeniser.nextLine();
+               }
+               else
+               {
+                       // was a pair
+               }
+       }
+}
+
+void VMF_Read( scene::Node& root, Tokeniser& tokeniser, EntityCreator& entityTable ){
+       g_vmf_entities = g_vmf_brushes = 0;
+       VMF_parseBlock( tokeniser, c_vmfRoot );
+       globalOutputStream() << g_vmf_entities << " entities\n";
+       globalOutputStream() << g_vmf_brushes << " brushes\n";
 }
 
-class MapVMFAPI : public TypeSystemRef, public MapFormat {
+class MapVMFAPI : public TypeSystemRef, public MapFormat
+{
 public:
-    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;
-    }
-
-    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, bool writeComments) const
-    {
-    }
+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;
+}
+
+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, bool writeComments ) const {
+}
 };
 
 typedef SingletonModule<MapVMFAPI, MapDependencies> MapVMFModule;
@@ -651,15 +610,14 @@ typedef SingletonModule<MapVMFAPI, MapDependencies> MapVMFModule;
 MapVMFModule g_MapVMFModule;
 
 
-extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer &server)
-{
-    initialiseModule(server);
-
-    g_MapDoom3Module.selfRegister();
-    g_MapQuake4Module.selfRegister();
-    g_MapQ3Module.selfRegister();
-    g_MapQ1Module.selfRegister();
-    g_MapQ2Module.selfRegister();
-    g_MapHalfLifeModule.selfRegister();
-    g_MapVMFModule.selfRegister();
+extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){
+       initialiseModule( server );
+
+       g_MapDoom3Module.selfRegister();
+       g_MapQuake4Module.selfRegister();
+       g_MapQ3Module.selfRegister();
+       g_MapQ1Module.selfRegister();
+       g_MapQ2Module.selfRegister();
+       g_MapHalfLifeModule.selfRegister();
+       g_MapVMFModule.selfRegister();
 }
index 9cf9c48..4bfbbe7 100644 (file)
@@ -25,9 +25,8 @@
 #include "iscriplib.h"
 #include "scenelib.h"
 
-inline MapExporter *Node_getMapExporter(scene::Node &node)
-{
-    return NodeTypeCast<MapExporter>::cast(node);
+inline MapExporter* Node_getMapExporter( scene::Node& node ){
+       return NodeTypeCast<MapExporter>::cast( node );
 }
 
 
@@ -35,89 +34,86 @@ static std::size_t g_count_entities;
 static std::size_t g_count_brushes;
 
 
-void Entity_ExportTokens(const Entity &entity, TokenWriter &writer)
-{
-    g_count_brushes = 0;
-
-    class WriteKeyValue : public Entity::Visitor {
-        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();
-        }
-
-    } visitor(writer);
-
-    entity.forEachKeyValue(visitor);
+void Entity_ExportTokens( const Entity& entity, TokenWriter& writer ){
+       g_count_brushes = 0;
+
+       class WriteKeyValue : public Entity::Visitor
+       {
+       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();
+       }
+
+       } visitor( writer );
+
+       entity.forEachKeyValue( visitor );
 }
 
-class WriteTokensWalker : public scene::Traversable::Walker {
-    mutable Stack<bool> m_stack;
-    TokenWriter &m_writer;
-    bool m_ignorePatches;
-    bool m_writeComments;
+class WriteTokensWalker : public scene::Traversable::Walker
+{
+mutable Stack<bool> m_stack;
+TokenWriter& m_writer;
+bool m_ignorePatches;
+bool m_writeComments;
 public:
-    WriteTokensWalker(TokenWriter &writer, bool ignorePatches, bool writeComments)
-            : m_writer(writer), m_ignorePatches(ignorePatches), m_writeComments(writeComments)
-    {
-    }
-
-    bool pre(scene::Node &node) const
-    {
-        m_stack.push(false);
-
-        Entity *entity = Node_getEntity(node);
-        if (entity != 0) {
-            if (m_writeComments) {
-                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);
-        } else {
-            MapExporter *exporter = Node_getMapExporter(node);
-            if (exporter != 0
-                && !(m_ignorePatches && Node_isPatch(node))) {
-                if (m_writeComments) {
-                    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();
-    }
+WriteTokensWalker( TokenWriter& writer, bool ignorePatches, bool writeComments )
+       : m_writer( writer ), m_ignorePatches( ignorePatches ), m_writeComments( writeComments ){
+}
+
+bool pre( scene::Node &node ) const {
+       m_stack.push( false );
+
+       Entity* entity = Node_getEntity( node );
+       if ( entity != 0 ) {
+               if ( m_writeComments ) {
+                       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 );
+       }
+       else
+       {
+               MapExporter* exporter = Node_getMapExporter( node );
+               if ( exporter != 0
+                       && !( m_ignorePatches && Node_isPatch( node ) ) ) {
+                       if ( m_writeComments ) {
+                               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();
+}
 };
 
-void Map_Write(scene::Node &root, GraphTraversalFunc traverse, TokenWriter &writer, bool ignorePatches, bool writeComments)
-{
-    g_count_entities = 0;
-    traverse(root, WriteTokensWalker(writer, ignorePatches, writeComments));
+void Map_Write( scene::Node& root, GraphTraversalFunc traverse, TokenWriter& writer, bool ignorePatches, bool writeComments ){
+       g_count_entities = 0;
+       traverse( root, WriteTokensWalker( writer, ignorePatches, writeComments ) );
 }
index fbc131c..ae07784 100644 (file)
@@ -24,6 +24,6 @@
 
 #include "imap.h"
 
-void Map_Write(scene::Node &root, GraphTraversalFunc traverse, TokenWriter &writer, bool ignorePatches, bool writeComments);
+void Map_Write( scene::Node& root, GraphTraversalFunc traverse, TokenWriter& writer, bool ignorePatches, bool writeComments );
 
 #endif
index 73bccb1..516e06b 100644 (file)
 
 
 class MapXMLDependencies :
-        public GlobalRadiantModuleRef,
-        public GlobalBrushModuleRef,
-        public GlobalFiletypesModuleRef,
-        public GlobalEntityClassManagerModuleRef,
-        public GlobalSceneGraphModuleRef {
-    PatchModuleRef m_patchDef2Doom3Module;
-    PatchModuleRef m_patchDoom3Module;
+       public GlobalRadiantModuleRef,
+       public GlobalBrushModuleRef,
+       public GlobalFiletypesModuleRef,
+       public GlobalEntityClassManagerModuleRef,
+       public GlobalSceneGraphModuleRef
+{
+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 : public TypeSystemRef, public MapFormat {
+class MapXMLAPI : public TypeSystemRef, public MapFormat
+{
 public:
-    typedef MapFormat Type;
+typedef MapFormat Type;
 
-    STRING_CONSTANT(Name, "xmldoom3");
+STRING_CONSTANT( Name, "xmldoom3" );
 
-    MapXMLAPI()
-    {
-        GlobalFiletypesModule::getTable().addType(Type::Name(), Name(), filetype_t("xml doom3 maps", "*.xmap"));
-    }
+MapXMLAPI(){
+       GlobalFiletypesModule::getTable().addType( Type::Name(), Name(), filetype_t( "xml doom3 maps", "*.xmap" ) );
+}
 
-    MapFormat *getTable()
-    {
-        return this;
-    }
+MapFormat* getTable(){
+       return this;
+}
 
-    void readGraph(scene::Node &root, TextInputStream &inputStream, EntityCreator &entityTable) const
-    {
-        Map_Read(root, inputStream, entityTable);
-    }
+void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const {
+       Map_Read( root, inputStream, entityTable );
+}
 
-    void writeGraph(scene::Node &root, GraphTraversalFunc traverse, TextOutputStream &outputStream, bool writeComments) const
-    {
-        Map_Write(root, traverse, outputStream);
-    }
+void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream, bool writeComments ) const {
+       Map_Write( root, traverse, outputStream );
+}
 };
 
 typedef SingletonModule<MapXMLAPI, MapXMLDependencies> MapXMLModule;
@@ -97,12 +91,11 @@ typedef SingletonModule<MapXMLAPI, MapXMLDependencies> MapXMLModule;
 MapXMLModule g_MapXMLModule;
 
 
-extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer &server)
-{
-    GlobalErrorStream::instance().setOutputStream(server.getErrorStream());
-    GlobalOutputStream::instance().setOutputStream(server.getOutputStream());
-    GlobalDebugMessageHandler::instance().setHandler(server.getDebugMessageHandler());
-    GlobalModuleServer::instance().set(server);
+extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){
+       GlobalErrorStream::instance().setOutputStream( server.getErrorStream() );
+       GlobalOutputStream::instance().setOutputStream( server.getOutputStream() );
+       GlobalDebugMessageHandler::instance().setHandler( server.getDebugMessageHandler() );
+       GlobalModuleServer::instance().set( server );
 
-    g_MapXMLModule.selfRegister();
+       g_MapXMLModule.selfRegister();
 }
index a88fe2e..f982605 100644 (file)
@@ -31,7 +31,7 @@
 //
 // Shaders Manager Plugin
 //
-// Leonardo Zide (leo@lokigames.com)
+// Leonardo Zide ( leo@lokigames.com )
 //
 
 #include "defaults.h"
 #include "archivelib.h"
 #include "imagelib.h"
 
-const char *g_shadersExtension = "";
-const char *g_shadersDirectory = "";
+const charg_shadersExtension = "";
+const charg_shadersDirectory = "";
 bool g_enableDefaultShaders = true;
 ShaderLanguage g_shaderLanguage = SHADERLANGUAGE_QUAKE3;
 bool g_useShaderList = true;
-_QERPlugImageTable *g_bitmapModule = 0;
-const char *g_texturePrefix = DEFAULT_TEXTURE_DIRNAME;
+_QERPlugImageTableg_bitmapModule = 0;
+const charg_texturePrefix = DEFAULT_TEXTURE_DIRNAME;
 
 void ActiveShaders_IteratorBegin();
 
@@ -91,9 +91,9 @@ Callback<void()> g_ActiveShadersChangedNotify;
 
 void FreeShaders();
 
-void LoadShaderFile(const char *filename);
+void LoadShaderFile( const char *filename );
 
-qtexture_t *Texture_ForName(const char *filename);
+qtexture_t *Texture_ForName( const char *filename );
 
 
 /*!
@@ -103,49 +103,47 @@ qtexture_t *Texture_ForName(const char *filename);
    this was in the initial design of the shader code since early GtkRadiant alpha, and got sort of foxed in 1.2 and put back in
  */
 
-Image *loadBitmap(void *environment, const char *name)
-{
-    DirectoryArchiveFile file(name, name);
-    if (!file.failed()) {
-        return g_bitmapModule->loadImage(file);
-    }
-    return 0;
+Image* loadBitmap( void* environment, const char* name ){
+       DirectoryArchiveFile file( name, name );
+       if ( !file.failed() ) {
+               return g_bitmapModule->loadImage( file );
+       }
+       return 0;
 }
 
-inline byte *getPixel(byte *pixels, int width, int height, int x, int y)
-{
-    return pixels + (((((y + height) % height) * width) + ((x + width) % width)) * 4);
+inline byte* getPixel( byte* pixels, int width, int height, int x, int y ){
+       return pixels + ( ( ( ( ( y + height ) % height ) * width ) + ( ( x + width ) % width ) ) * 4 );
 }
 
-class KernelElement {
+class KernelElement
+{
 public:
-    int x, y;
-    float w;
+int x, y;
+float w;
 };
 
-Image &convertHeightmapToNormalmap(Image &heightmap, float scale)
-{
-    int w = heightmap.getWidth();
-    int h = heightmap.getHeight();
+Image& convertHeightmapToNormalmap( Image& heightmap, float scale ){
+       int w = heightmap.getWidth();
+       int h = heightmap.getHeight();
 
-    Image &normalmap = *(new RGBAImage(heightmap.getWidth(), heightmap.getHeight()));
+       Image& normalmap = *( new RGBAImage( heightmap.getWidth(), heightmap.getHeight() ) );
 
-    byte *in = heightmap.getRGBAPixels();
-    byte *out = normalmap.getRGBAPixels();
+       byte* in = heightmap.getRGBAPixels();
+       byte* out = normalmap.getRGBAPixels();
 
 #if 1
-    // no filtering
-    const int kernelSize = 2;
-    KernelElement kernel_du[kernelSize] = {
-            {-1, 0, -0.5f},
-            {1,  0, 0.5f}
-    };
-    KernelElement kernel_dv[kernelSize] = {
-            {0, 1, 0.5f},
-            {0, -1, -0.5f}
-    };
+       // no filtering
+       const int kernelSize = 2;
+       KernelElement kernel_du[kernelSize] = {
+               {-1, 0,-0.5f },
+               { 1, 0, 0.5f }
+       };
+       KernelElement kernel_dv[kernelSize] = {
+               { 0, 1, 0.5f },
+               { 0,-1,-0.5f }
+       };
 #else
-                                                                                                                            // 3x3 Prewitt
+       // 3x3 Prewitt
        const int kernelSize = 6;
        KernelElement kernel_du[kernelSize] = {
                {-1, 1,-1.0f },
@@ -165,52 +163,56 @@ Image &convertHeightmapToNormalmap(Image &heightmap, float scale)
        };
 #endif
 
-    int x, y = 0;
-    while (y < h) {
-        x = 0;
-        while (x < w) {
-            float du = 0;
-            for (KernelElement *i = kernel_du; i != kernel_du + kernelSize; ++i) {
-                du += (getPixel(in, w, h, x + (*i).x, y + (*i).y)[0] / 255.0) * (*i).w;
-            }
-            float dv = 0;
-            for (KernelElement *i = kernel_dv; i != kernel_dv + kernelSize; ++i) {
-                dv += (getPixel(in, w, h, x + (*i).x, y + (*i).y)[0] / 255.0) * (*i).w;
-            }
-
-            float nx = -du * scale;
-            float ny = -dv * scale;
-            float nz = 1.0;
-
-            // Normalize
-            float norm = 1.0 / sqrt(nx * nx + ny * ny + nz * nz);
-            out[0] = float_to_integer(((nx * norm) + 1) * 127.5);
-            out[1] = float_to_integer(((ny * norm) + 1) * 127.5);
-            out[2] = float_to_integer(((nz * norm) + 1) * 127.5);
-            out[3] = 255;
-
-            x++;
-            out += 4;
-        }
-
-        y++;
-    }
-
-    return normalmap;
-}
-
-Image *loadHeightmap(void *environment, const char *name)
-{
-    Image *heightmap = GlobalTexturesCache().loadImage(name);
-    if (heightmap != 0) {
-        Image &normalmap = convertHeightmapToNormalmap(*heightmap, *reinterpret_cast<float *>( environment ));
-        heightmap->release();
-        return &normalmap;
-    }
-    return 0;
+       int x, y = 0;
+       while ( y < h )
+       {
+               x = 0;
+               while ( x < w )
+               {
+                       float du = 0;
+                       for ( KernelElement* i = kernel_du; i != kernel_du + kernelSize; ++i )
+                       {
+                               du += ( getPixel( in, w, h, x + ( *i ).x, y + ( *i ).y )[0] / 255.0 ) * ( *i ).w;
+                       }
+                       float dv = 0;
+                       for ( KernelElement* i = kernel_dv; i != kernel_dv + kernelSize; ++i )
+                       {
+                               dv += ( getPixel( in, w, h, x + ( *i ).x, y + ( *i ).y )[0] / 255.0 ) * ( *i ).w;
+                       }
+
+                       float nx = -du * scale;
+                       float ny = -dv * scale;
+                       float nz = 1.0;
+
+                       // Normalize
+                       float norm = 1.0 / sqrt( nx * nx + ny * ny + nz * nz );
+                       out[0] = float_to_integer( ( ( nx * norm ) + 1 ) * 127.5 );
+                       out[1] = float_to_integer( ( ( ny * norm ) + 1 ) * 127.5 );
+                       out[2] = float_to_integer( ( ( nz * norm ) + 1 ) * 127.5 );
+                       out[3] = 255;
+
+                       x++;
+                       out += 4;
+               }
+
+               y++;
+       }
+
+       return normalmap;
+}
+
+Image* loadHeightmap( void* environment, const char* name ){
+       Image* heightmap = GlobalTexturesCache().loadImage( name );
+       if ( heightmap != 0 ) {
+               Image& normalmap = convertHeightmapToNormalmap( *heightmap, *reinterpret_cast<float*>( environment ) );
+               heightmap->release();
+               return &normalmap;
+       }
+       return 0;
 }
 
-class ShaderPoolContext {
+class ShaderPoolContext
+{
 };
 
 typedef Static<StringPool, ShaderPoolContext> ShaderPool;
@@ -225,45 +227,40 @@ typedef CopiedString TextureExpression;
 // we compare as case insensitive. That is Radiant is case insensitive, but knows that the engine is case sensitive.
 //++timo FIXME: we need to put code somewhere to detect when two shaders that are case insensitive equal are present
 template<typename StringType>
-void parseTextureName(StringType &name, const char *token)
-{
-    StringOutputStream cleaned(256);
-    cleaned << PathCleaned(token);
-    name = CopiedString(
-            StringRange(cleaned.c_str(), path_get_filename_base_end(cleaned.c_str()))).c_str(); // remove extension
+void parseTextureName( StringType& name, const char* token ){
+       StringOutputStream cleaned( 256 );
+       cleaned << PathCleaned( token );
+       name = CopiedString( StringRange( cleaned.c_str(), path_get_filename_base_end( cleaned.c_str() ) ) ).c_str(); // remove extension
 }
 
-bool Tokeniser_parseTextureName(Tokeniser &tokeniser, TextureExpression &name)
-{
-    const char *token = tokeniser.getToken();
-    if (token == 0) {
-        Tokeniser_unexpectedError(tokeniser, token, "#texture-name");
-        return false;
-    }
-    parseTextureName(name, token);
-    return true;
+bool Tokeniser_parseTextureName( Tokeniser& tokeniser, TextureExpression& name ){
+       const char* token = tokeniser.getToken();
+       if ( token == 0 ) {
+               Tokeniser_unexpectedError( tokeniser, token, "#texture-name" );
+               return false;
+       }
+       parseTextureName( name, token );
+       return true;
 }
 
-bool Tokeniser_parseShaderName(Tokeniser &tokeniser, CopiedString &name)
-{
-    const char *token = tokeniser.getToken();
-    if (token == 0) {
-        Tokeniser_unexpectedError(tokeniser, token, "#shader-name");
-        return false;
-    }
-    parseTextureName(name, token);
-    return true;
+bool Tokeniser_parseShaderName( Tokeniser& tokeniser, CopiedString& name ){
+       const char* token = tokeniser.getToken();
+       if ( token == 0 ) {
+               Tokeniser_unexpectedError( tokeniser, token, "#shader-name" );
+               return false;
+       }
+       parseTextureName( name, token );
+       return true;
 }
 
-bool Tokeniser_parseString(Tokeniser &tokeniser, ShaderString &string)
-{
-    const char *token = tokeniser.getToken();
-    if (token == 0) {
-        Tokeniser_unexpectedError(tokeniser, token, "#string");
-        return false;
-    }
-    string = token;
-    return true;
+bool Tokeniser_parseString( Tokeniser& tokeniser, ShaderString& string ){
+       const char* token = tokeniser.getToken();
+       if ( token == 0 ) {
+               Tokeniser_unexpectedError( tokeniser, token, "#string" );
+               return false;
+       }
+       string = token;
+       return true;
 }
 
 
@@ -272,393 +269,414 @@ typedef std::list<ShaderVariable> ShaderArguments;
 
 typedef std::pair<ShaderVariable, ShaderVariable> BlendFuncExpression;
 
-class ShaderTemplate {
-    std::size_t m_refcount;
-    CopiedString m_Name;
+class ShaderTemplate
+{
+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;
-
-    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;
-        }
-    }
-
-    std::size_t refcount()
-    {
-        return m_refcount;
-    }
-
-    const char *getName() const
-    {
-        return m_Name.c_str();
-    }
-
-    void setName(const char *name)
-    {
-        m_Name = name;
-    }
+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;
+       }
+}
+
+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);
-
-
-    void CreateDefault(const char *name)
-    {
-        if (g_enableDefaultShaders) {
-            m_textureName = name;
-        } else {
-            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<MapLayerTemplate> MapLayers;
-    MapLayers m_layers;
-};
+bool parseDoom3( Tokeniser& tokeniser );
 
+bool parseQuake3( Tokeniser& tokeniser );
 
-bool Doom3Shader_parseHeightmap(Tokeniser &tokeniser, TextureExpression &bump, ShaderValue &heightmapScale)
-{
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "("));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, bump));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ","));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseString(tokeniser, heightmapScale));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")"));
-    return true;
+bool parseTemplate( Tokeniser& tokeniser );
+
+
+void CreateDefault( const char *name ){
+       if ( g_enableDefaultShaders ) {
+               m_textureName = name;
+       }
+       else
+       {
+               m_textureName = "";
+       }
+       setName( name );
 }
 
-bool Doom3Shader_parseAddnormals(Tokeniser &tokeniser, TextureExpression &bump)
-{
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "("));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, bump));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ","));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "heightmap"));
-    TextureExpression heightmapName;
-    ShaderValue heightmapScale;
-    RETURN_FALSE_IF_FAIL(Doom3Shader_parseHeightmap(tokeniser, heightmapName, heightmapScale));
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")"));
-    return true;
-}
-
-bool Doom3Shader_parseBumpmap(Tokeniser &tokeniser, TextureExpression &bump, ShaderValue &heightmapScale)
+
+class MapLayerTemplate
 {
-    const char *token = tokeniser.getToken();
-    if (token == 0) {
-        Tokeniser_unexpectedError(tokeniser, token, "#bumpmap");
-        return false;
-    }
-    if (string_equal(token, "heightmap")) {
-        RETURN_FALSE_IF_FAIL(Doom3Shader_parseHeightmap(tokeniser, bump, heightmapScale));
-    } else if (string_equal(token, "addnormals")) {
-        RETURN_FALSE_IF_FAIL(Doom3Shader_parseAddnormals(tokeniser, bump));
-    } else {
-        parseTextureName(bump, token);
-    }
-    return true;
-}
-
-enum LayerTypeId {
-    LAYER_NONE,
-    LAYER_BLEND,
-    LAYER_DIFFUSEMAP,
-    LAYER_BUMPMAP,
-    LAYER_SPECULARMAP
+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;
+}
 };
 
-class LayerTemplate {
-public:
-    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")
-    {
-    }
+typedef std::vector<MapLayerTemplate> MapLayers;
+MapLayers m_layers;
 };
 
-bool parseShaderParameters(Tokeniser &tokeniser, ShaderParameters &params)
+
+bool Doom3Shader_parseHeightmap( Tokeniser& tokeniser, TextureExpression& bump, ShaderValue& heightmapScale ){
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "(" ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, bump ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "," ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseString( tokeniser, heightmapScale ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, ")" ) );
+       return true;
+}
+
+bool Doom3Shader_parseAddnormals( Tokeniser& tokeniser, TextureExpression& bump ){
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "(" ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, bump ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "," ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "heightmap" ) );
+       TextureExpression heightmapName;
+       ShaderValue heightmapScale;
+       RETURN_FALSE_IF_FAIL( Doom3Shader_parseHeightmap( tokeniser, heightmapName, heightmapScale ) );
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, ")" ) );
+       return true;
+}
+
+bool Doom3Shader_parseBumpmap( Tokeniser& tokeniser, TextureExpression& bump, ShaderValue& heightmapScale ){
+       const char* token = tokeniser.getToken();
+       if ( token == 0 ) {
+               Tokeniser_unexpectedError( tokeniser, token, "#bumpmap" );
+               return false;
+       }
+       if ( string_equal( token, "heightmap" ) ) {
+               RETURN_FALSE_IF_FAIL( Doom3Shader_parseHeightmap( tokeniser, bump, heightmapScale ) );
+       }
+       else if ( string_equal( token, "addnormals" ) ) {
+               RETURN_FALSE_IF_FAIL( Doom3Shader_parseAddnormals( tokeniser, bump ) );
+       }
+       else
+       {
+               parseTextureName( bump, token );
+       }
+       return true;
+}
+
+enum LayerTypeId
 {
-    Tokeniser_parseToken(tokeniser, "(");
-    for (;;) {
-        const char *param = tokeniser.getToken();
-        if (string_equal(param, ")")) {
-            break;
-        }
-        params.push_back(param);
-        const char *comma = tokeniser.getToken();
-        if (string_equal(comma, ")")) {
-            break;
-        }
-        if (!string_equal(comma, ",")) {
-            Tokeniser_unexpectedError(tokeniser, comma, ",");
-            return false;
-        }
-    }
-    return true;
-}
-
-bool ShaderTemplate::parseTemplate(Tokeniser &tokeniser)
+       LAYER_NONE,
+       LAYER_BLEND,
+       LAYER_DIFFUSEMAP,
+       LAYER_BUMPMAP,
+       LAYER_SPECULARMAP
+};
+
+class LayerTemplate
 {
-    m_Name = tokeniser.getToken();
-    if (!parseShaderParameters(tokeniser, m_params)) {
-        globalErrorStream() << "shader template: " << makeQuoted(m_Name.c_str()) << ": parameter parse failed\n";
-        return false;
-    }
+public:
+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" ){
+}
+};
 
-    return parseDoom3(tokeniser);
+bool parseShaderParameters( Tokeniser& tokeniser, ShaderParameters& params ){
+       Tokeniser_parseToken( tokeniser, "(" );
+       for (;; )
+       {
+               const char* param = tokeniser.getToken();
+               if ( string_equal( param, ")" ) ) {
+                       break;
+               }
+               params.push_back( param );
+               const char* comma = tokeniser.getToken();
+               if ( string_equal( comma, ")" ) ) {
+                       break;
+               }
+               if ( !string_equal( comma, "," ) ) {
+                       Tokeniser_unexpectedError( tokeniser, comma, "," );
+                       return false;
+               }
+       }
+       return true;
 }
 
-bool ShaderTemplate::parseDoom3(Tokeniser &tokeniser)
-{
-    LayerTemplate currentLayer;
-    bool isFog = false;
-
-    // we need to read until we hit a balanced }
-    int depth = 0;
-    for (;;) {
-        tokeniser.nextLine();
-        const char *token = tokeniser.getToken();
-
-        if (token == 0) {
-            return false;
-        }
-
-        if (string_equal(token, "{")) {
-            ++depth;
-            continue;
-        } else if (string_equal(token, "}")) {
-            --depth;
-            if (depth < 0) { // error
-                return false;
-            }
-            if (depth == 0) { // end of shader
-                break;
-            }
-            if (depth == 1) { // end of layer
-                if (currentLayer.m_type == LAYER_DIFFUSEMAP) {
-                    m_diffuse = currentLayer.m_texture;
-                } else if (currentLayer.m_type == LAYER_BUMPMAP) {
-                    m_bump = currentLayer.m_texture;
-                } else if (currentLayer.m_type == LAYER_SPECULARMAP) {
-                    m_specular = currentLayer.m_texture;
-                } 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_type = LAYER_NONE;
-                currentLayer.m_texture = "";
-            }
-            continue;
-        }
-
-        if (depth == 2) { // in layer
-            if (string_equal_nocase(token, "blend")) {
-                const char *blend = tokeniser.getToken();
-
-                if (blend == 0) {
-                    Tokeniser_unexpectedError(tokeniser, blend, "#blend");
-                    return false;
-                }
-
-                if (string_equal_nocase(blend, "diffusemap")) {
-                    currentLayer.m_type = LAYER_DIFFUSEMAP;
-                } else if (string_equal_nocase(blend, "bumpmap")) {
-                    currentLayer.m_type = LAYER_BUMPMAP;
-                } else if (string_equal_nocase(blend, "specularmap")) {
-                    currentLayer.m_type = LAYER_SPECULARMAP;
-                } else {
-                    currentLayer.m_blendFunc.first = blend;
-
-                    const char *comma = tokeniser.getToken();
-
-                    if (comma == 0) {
-                        Tokeniser_unexpectedError(tokeniser, comma, "#comma");
-                        return false;
-                    }
-
-                    if (string_equal(comma, ",")) {
-                        RETURN_FALSE_IF_FAIL(Tokeniser_parseString(tokeniser, currentLayer.m_blendFunc.second));
-                    } else {
-                        currentLayer.m_blendFunc.second = "";
-                        tokeniser.ungetToken();
-                    }
-                }
-            } else if (string_equal_nocase(token, "map")) {
-                if (currentLayer.m_type == LAYER_BUMPMAP) {
-                    RETURN_FALSE_IF_FAIL(
-                            Doom3Shader_parseBumpmap(tokeniser, currentLayer.m_texture, currentLayer.m_heightmapScale));
-                } else {
-                    const char *map = tokeniser.getToken();
-
-                    if (map == 0) {
-                        Tokeniser_unexpectedError(tokeniser, map, "#map");
-                        return false;
-                    }
-
-                    if (string_equal(map, "makealpha")) {
-                        RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "("));
-                        const char *texture = tokeniser.getToken();
-                        if (texture == 0) {
-                            Tokeniser_unexpectedError(tokeniser, texture, "#texture");
-                            return false;
-                        }
-                        currentLayer.m_texture = texture;
-                        RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")"));
-                    } else {
-                        parseTextureName(currentLayer.m_texture, map);
-                    }
-                }
-            } else if (string_equal_nocase(token, "zeroclamp")) {
-                currentLayer.m_clampToBorder = true;
-            }
+bool ShaderTemplate::parseTemplate( Tokeniser& tokeniser ){
+       m_Name = tokeniser.getToken();
+       if ( !parseShaderParameters( tokeniser, m_params ) ) {
+               globalErrorStream() << "shader template: " << makeQuoted( m_Name.c_str() ) << ": parameter parse failed\n";
+               return false;
+       }
+
+       return parseDoom3( tokeniser );
+}
+
+bool ShaderTemplate::parseDoom3( Tokeniser& tokeniser ){
+       LayerTemplate currentLayer;
+       bool isFog = false;
+
+       // we need to read until we hit a balanced }
+       int depth = 0;
+       for (;; )
+       {
+               tokeniser.nextLine();
+               const char* token = tokeniser.getToken();
+
+               if ( token == 0 ) {
+                       return false;
+               }
+
+               if ( string_equal( token, "{" ) ) {
+                       ++depth;
+                       continue;
+               }
+               else if ( string_equal( token, "}" ) ) {
+                       --depth;
+                       if ( depth < 0 ) { // error
+                               return false;
+                       }
+                       if ( depth == 0 ) { // end of shader
+                               break;
+                       }
+                       if ( depth == 1 ) { // end of layer
+                               if ( currentLayer.m_type == LAYER_DIFFUSEMAP ) {
+                                       m_diffuse = currentLayer.m_texture;
+                               }
+                               else if ( currentLayer.m_type == LAYER_BUMPMAP ) {
+                                       m_bump = currentLayer.m_texture;
+                               }
+                               else if ( currentLayer.m_type == LAYER_SPECULARMAP ) {
+                                       m_specular = currentLayer.m_texture;
+                               }
+                               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_type = LAYER_NONE;
+                               currentLayer.m_texture = "";
+                       }
+                       continue;
+               }
+
+               if ( depth == 2 ) { // in layer
+                       if ( string_equal_nocase( token, "blend" ) ) {
+                               const char* blend = tokeniser.getToken();
+
+                               if ( blend == 0 ) {
+                                       Tokeniser_unexpectedError( tokeniser, blend, "#blend" );
+                                       return false;
+                               }
+
+                               if ( string_equal_nocase( blend, "diffusemap" ) ) {
+                                       currentLayer.m_type = LAYER_DIFFUSEMAP;
+                               }
+                               else if ( string_equal_nocase( blend, "bumpmap" ) ) {
+                                       currentLayer.m_type = LAYER_BUMPMAP;
+                               }
+                               else if ( string_equal_nocase( blend, "specularmap" ) ) {
+                                       currentLayer.m_type = LAYER_SPECULARMAP;
+                               }
+                               else
+                               {
+                                       currentLayer.m_blendFunc.first = blend;
+
+                                       const char* comma = tokeniser.getToken();
+
+                                       if ( comma == 0 ) {
+                                               Tokeniser_unexpectedError( tokeniser, comma, "#comma" );
+                                               return false;
+                                       }
+
+                                       if ( string_equal( comma, "," ) ) {
+                                               RETURN_FALSE_IF_FAIL( Tokeniser_parseString( tokeniser, currentLayer.m_blendFunc.second ) );
+                                       }
+                                       else
+                                       {
+                                               currentLayer.m_blendFunc.second = "";
+                                               tokeniser.ungetToken();
+                                       }
+                               }
+                       }
+                       else if ( string_equal_nocase( token, "map" ) ) {
+                               if ( currentLayer.m_type == LAYER_BUMPMAP ) {
+                                       RETURN_FALSE_IF_FAIL( Doom3Shader_parseBumpmap( tokeniser, currentLayer.m_texture, currentLayer.m_heightmapScale ) );
+                               }
+                               else
+                               {
+                                       const char* map = tokeniser.getToken();
+
+                                       if ( map == 0 ) {
+                                               Tokeniser_unexpectedError( tokeniser, map, "#map" );
+                                               return false;
+                                       }
+
+                                       if ( string_equal( map, "makealpha" ) ) {
+                                               RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "(" ) );
+                                               const char* texture = tokeniser.getToken();
+                                               if ( texture == 0 ) {
+                                                       Tokeniser_unexpectedError( tokeniser, texture, "#texture" );
+                                                       return false;
+                                               }
+                                               currentLayer.m_texture = texture;
+                                               RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, ")" ) );
+                                       }
+                                       else
+                                       {
+                                               parseTextureName( currentLayer.m_texture, map );
+                                       }
+                               }
+                       }
+                       else if ( string_equal_nocase( token, "zeroclamp" ) ) {
+                               currentLayer.m_clampToBorder = true;
+                       }
 #if 0
-                                                                                                                                    else if ( string_equal_nocase( token, "alphaTest" ) ) {
+                       else if ( string_equal_nocase( token, "alphaTest" ) ) {
                                Tokeniser_getFloat( tokeniser, currentLayer.m_alphaTest );
                        }
 #endif
-        } else if (depth == 1) {
-            if (string_equal_nocase(token, "qer_editorimage")) {
-                RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, m_textureName));
-            } else if (string_equal_nocase(token, "qer_trans")) {
-                m_fTrans = string_read_float(tokeniser.getToken());
-                m_nFlags |= QER_TRANS;
-            } else if (string_equal_nocase(token, "translucent")) {
-                m_fTrans = 1;
-                m_nFlags |= QER_TRANS;
-            } else if (string_equal(token, "DECAL_MACRO")) {
-                m_fTrans = 1;
-                m_nFlags |= QER_TRANS;
-            } else if (string_equal_nocase(token, "bumpmap")) {
-                RETURN_FALSE_IF_FAIL(Doom3Shader_parseBumpmap(tokeniser, m_bump, m_heightmapScale));
-            } else if (string_equal_nocase(token, "diffusemap")) {
-                RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, m_diffuse));
-            } else if (string_equal_nocase(token, "specularmap")) {
-                RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, m_specular));
-            } else if (string_equal_nocase(token, "twosided")) {
-                m_Cull = IShader::eCullNone;
-                m_nFlags |= QER_CULL;
-            } else if (string_equal_nocase(token, "nodraw")) {
-                m_nFlags |= QER_NODRAW;
-            } else if (string_equal_nocase(token, "nonsolid")) {
-                m_nFlags |= QER_NONSOLID;
-            } else if (string_equal_nocase(token, "liquid")) {
-                m_nFlags |= QER_WATER;
-            } else if (string_equal_nocase(token, "areaportal")) {
-                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")) {
-                m_nFlags |= QER_CLIP;
-            }
-            if (string_equal_nocase(token, "fogLight")) {
-                isFog = true;
-            } else if (!isFog && string_equal_nocase(token, "lightFalloffImage")) {
-                const char *lightFalloffImage = tokeniser.getToken();
-                if (lightFalloffImage == 0) {
-                    Tokeniser_unexpectedError(tokeniser, lightFalloffImage, "#lightFalloffImage");
-                    return false;
-                }
-                if (string_equal_nocase(lightFalloffImage, "makeintensity")) {
-                    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "("));
-                    TextureExpression name;
-                    RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, name));
-                    m_lightFalloffImage = name;
-                    RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")"));
-                } else {
-                    m_lightFalloffImage = lightFalloffImage;
-                }
-            }
-        }
-    }
-
-    if (string_empty(m_textureName.c_str())) {
-        m_textureName = m_diffuse;
-    }
-
-    return true;
+               }
+               else if ( depth == 1 ) {
+                       if ( string_equal_nocase( token, "qer_editorimage" ) ) {
+                               RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, m_textureName ) );
+                       }
+                       else if ( string_equal_nocase( token, "qer_trans" ) ) {
+                               m_fTrans = string_read_float( tokeniser.getToken() );
+                               m_nFlags |= QER_TRANS;
+                       }
+                       else if ( string_equal_nocase( token, "translucent" ) ) {
+                               m_fTrans = 1;
+                               m_nFlags |= QER_TRANS;
+                       }
+                       else if ( string_equal( token, "DECAL_MACRO" ) ) {
+                               m_fTrans = 1;
+                               m_nFlags |= QER_TRANS;
+                       }
+                       else if ( string_equal_nocase( token, "bumpmap" ) ) {
+                               RETURN_FALSE_IF_FAIL( Doom3Shader_parseBumpmap( tokeniser, m_bump, m_heightmapScale ) );
+                       }
+                       else if ( string_equal_nocase( token, "diffusemap" ) ) {
+                               RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, m_diffuse ) );
+                       }
+                       else if ( string_equal_nocase( token, "specularmap" ) ) {
+                               RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, m_specular ) );
+                       }
+                       else if ( string_equal_nocase( token, "twosided" ) ) {
+                               m_Cull = IShader::eCullNone;
+                               m_nFlags |= QER_CULL;
+                       }
+                       else if ( string_equal_nocase( token, "nodraw" ) ) {
+                               m_nFlags |= QER_NODRAW;
+                       }
+                       else if ( string_equal_nocase( token, "nonsolid" ) ) {
+                               m_nFlags |= QER_NONSOLID;
+                       }
+                       else if ( string_equal_nocase( token, "liquid" ) ) {
+                               m_nFlags |= QER_WATER;
+                       }
+                       else if ( string_equal_nocase( token, "areaportal" ) ) {
+                               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" ) ) {
+                               m_nFlags |= QER_CLIP;
+                       }
+                       if ( string_equal_nocase( token, "fogLight" ) ) {
+                               isFog = true;
+                       }
+                       else if ( !isFog && string_equal_nocase( token, "lightFalloffImage" ) ) {
+                               const char* lightFalloffImage = tokeniser.getToken();
+                               if ( lightFalloffImage == 0 ) {
+                                       Tokeniser_unexpectedError( tokeniser, lightFalloffImage, "#lightFalloffImage" );
+                                       return false;
+                               }
+                               if ( string_equal_nocase( lightFalloffImage, "makeintensity" ) ) {
+                                       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, "(" ) );
+                                       TextureExpression name;
+                                       RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, name ) );
+                                       m_lightFalloffImage = name;
+                                       RETURN_FALSE_IF_FAIL( Tokeniser_parseToken( tokeniser, ")" ) );
+                               }
+                               else
+                               {
+                                       m_lightFalloffImage = lightFalloffImage;
+                               }
+                       }
+               }
+       }
+
+       if ( string_empty( m_textureName.c_str() ) ) {
+               m_textureName = m_diffuse;
+       }
+
+       return true;
 }
 
 typedef SmartPointer<ShaderTemplate> ShaderTemplatePointer;
@@ -667,476 +685,439 @@ typedef std::map<CopiedString, ShaderTemplatePointer> ShaderTemplateMap;
 ShaderTemplateMap g_shaders;
 ShaderTemplateMap g_shaderTemplates;
 
-ShaderTemplate *findTemplate(const char *name)
-{
-    ShaderTemplateMap::iterator i = g_shaderTemplates.find(name);
-    if (i != g_shaderTemplates.end()) {
-        return (*i).second.get();
-    }
-    return 0;
+ShaderTemplate* findTemplate( const char* name ){
+       ShaderTemplateMap::iterator i = g_shaderTemplates.find( name );
+       if ( i != g_shaderTemplates.end() ) {
+               return ( *i ).second.get();
+       }
+       return 0;
 }
 
-class ShaderDefinition {
+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<CopiedString, ShaderDefinition> ShaderDefinitionMap;
 
 ShaderDefinitionMap g_shaderDefinitions;
 
-bool parseTemplateInstance(Tokeniser &tokeniser, const char *filename)
-{
-    CopiedString name;
-    RETURN_FALSE_IF_FAIL(Tokeniser_parseShaderName(tokeniser, name));
-    const char *templateName = tokeniser.getToken();
-    ShaderTemplate *shaderTemplate = findTemplate(templateName);
-    if (shaderTemplate == 0) {
-        globalErrorStream() << "shader instance: " << makeQuoted(name.c_str()) << ": shader template not found: "
-                            << makeQuoted(templateName) << "\n";
-    }
-
-    ShaderArguments args;
-    if (!parseShaderParameters(tokeniser, args)) {
-        globalErrorStream() << "shader instance: " << makeQuoted(name.c_str()) << ": argument parse failed\n";
-        return false;
-    }
-
-    if (shaderTemplate != 0) {
-        if (!g_shaderDefinitions.insert(
-                ShaderDefinitionMap::value_type(name, ShaderDefinition(shaderTemplate, args, filename))).second) {
-            globalErrorStream() << "shader instance: " << makeQuoted(name.c_str())
-                                << ": already exists, second definition ignored\n";
-        }
-    }
-    return true;
-}
-
-
-const char *evaluateShaderValue(const char *value, const ShaderParameters &params, const ShaderArguments &args)
-{
-    ShaderArguments::const_iterator j = args.begin();
-    for (ShaderParameters::const_iterator i = params.begin(); i != params.end(); ++i, ++j) {
-        const char *other = (*i).c_str();
-        if (string_equal(value, other)) {
-            return (*j).c_str();
-        }
-    }
-    return value;
+bool parseTemplateInstance( Tokeniser& tokeniser, const char* filename ){
+       CopiedString name;
+       RETURN_FALSE_IF_FAIL( Tokeniser_parseShaderName( tokeniser, name ) );
+       const char* templateName = tokeniser.getToken();
+       ShaderTemplate* shaderTemplate = findTemplate( templateName );
+       if ( shaderTemplate == 0 ) {
+               globalErrorStream() << "shader instance: " << makeQuoted( name.c_str() ) << ": shader template not found: " << makeQuoted( templateName ) << "\n";
+       }
+
+       ShaderArguments args;
+       if ( !parseShaderParameters( tokeniser, args ) ) {
+               globalErrorStream() << "shader instance: " << makeQuoted( name.c_str() ) << ": argument parse failed\n";
+               return false;
+       }
+
+       if ( shaderTemplate != 0 ) {
+               if ( !g_shaderDefinitions.insert( ShaderDefinitionMap::value_type( name, ShaderDefinition( shaderTemplate, args, filename ) ) ).second ) {
+                       globalErrorStream() << "shader instance: " << makeQuoted( name.c_str() ) << ": already exists, second definition ignored\n";
+               }
+       }
+       return true;
+}
+
+
+const char* evaluateShaderValue( const char* value, const ShaderParameters& params, const ShaderArguments& args ){
+       ShaderArguments::const_iterator j = args.begin();
+       for ( ShaderParameters::const_iterator i = params.begin(); i != params.end(); ++i, ++j )
+       {
+               const char* other = ( *i ).c_str();
+               if ( string_equal( value, other ) ) {
+                       return ( *j ).c_str();
+               }
+       }
+       return value;
 }
 
 ///\todo BlendFunc parsing
-BlendFunc
-evaluateBlendFunc(const BlendFuncExpression &blendFunc, const ShaderParameters &params, const ShaderArguments &args)
-{
-    return BlendFunc(BLEND_ONE, BLEND_ZERO);
+BlendFunc evaluateBlendFunc( const BlendFuncExpression& blendFunc, const ShaderParameters& params, const ShaderArguments& args ){
+       return BlendFunc( BLEND_ONE, BLEND_ZERO );
 }
 
-qtexture_t *
-evaluateTexture(const TextureExpression &texture, const ShaderParameters &params, const ShaderArguments &args,
-                const LoadImageCallback &loader = GlobalTexturesCache().defaultLoader())
-{
-    StringOutputStream result(64);
-    const char *expression = texture.c_str();
-    const char *end = expression + string_length(expression);
-    if (!string_empty(expression)) {
-        for (;;) {
-            const char *best = end;
-            const char *bestParam = 0;
-            const char *bestArg = 0;
-            ShaderArguments::const_iterator j = args.begin();
-            for (ShaderParameters::const_iterator i = params.begin(); i != params.end(); ++i, ++j) {
-                const char *found = strstr(expression, (*i).c_str());
-                if (found != 0 && found < best) {
-                    best = found;
-                    bestParam = (*i).c_str();
-                    bestArg = (*j).c_str();
-                }
-            }
-            if (best != end) {
-                result << StringRange(expression, best);
-                result << PathCleaned(bestArg);
-                expression = best + string_length(bestParam);
-            } else {
-                break;
-            }
-        }
-        result << expression;
-    }
-    return GlobalTexturesCache().capture(loader, result.c_str());
-}
-
-float evaluateFloat(const ShaderValue &value, const ShaderParameters &params, const ShaderArguments &args)
-{
-    const char *result = evaluateShaderValue(value.c_str(), params, args);
-    float f;
-    if (!string_parse_float(result, f)) {
-        globalErrorStream() << "parsing float value failed: " << makeQuoted(result) << "\n";
-    }
-    return f;
+qtexture_t* evaluateTexture( const TextureExpression& texture, const ShaderParameters& params, const ShaderArguments& args, const LoadImageCallback& loader = GlobalTexturesCache().defaultLoader() ){
+       StringOutputStream result( 64 );
+       const char* expression = texture.c_str();
+       const char* end = expression + string_length( expression );
+       if ( !string_empty( expression ) ) {
+               for (;; )
+               {
+                       const char* best = end;
+                       const char* bestParam = 0;
+                       const char* bestArg = 0;
+                       ShaderArguments::const_iterator j = args.begin();
+                       for ( ShaderParameters::const_iterator i = params.begin(); i != params.end(); ++i, ++j )
+                       {
+                               const char* found = strstr( expression, ( *i ).c_str() );
+                               if ( found != 0 && found < best ) {
+                                       best = found;
+                                       bestParam = ( *i ).c_str();
+                                       bestArg = ( *j ).c_str();
+                               }
+                       }
+                       if ( best != end ) {
+                               result << StringRange( expression, best );
+                               result << PathCleaned( bestArg );
+                               expression = best + string_length( bestParam );
+                       }
+                       else
+                       {
+                               break;
+                       }
+               }
+               result << expression;
+       }
+       return GlobalTexturesCache().capture( loader, result.c_str() );
+}
+
+float evaluateFloat( const ShaderValue& value, const ShaderParameters& params, const ShaderArguments& args ){
+       const char* result = evaluateShaderValue( value.c_str(), params, args );
+       float f;
+       if ( !string_parse_float( result, f ) ) {
+               globalErrorStream() << "parsing float value failed: " << makeQuoted( result ) << "\n";
+       }
+       return f;
 }
 
-BlendFactor evaluateBlendFactor(const ShaderValue &value, const ShaderParameters &params, const ShaderArguments &args)
+BlendFactor evaluateBlendFactor( const ShaderValue& value, const ShaderParameters& params, const ShaderArguments& args ){
+       const char* result = evaluateShaderValue( value.c_str(), params, args );
+
+       if ( string_equal_nocase( result, "gl_zero" ) ) {
+               return BLEND_ZERO;
+       }
+       if ( string_equal_nocase( result, "gl_one" ) ) {
+               return BLEND_ONE;
+       }
+       if ( string_equal_nocase( result, "gl_src_color" ) ) {
+               return BLEND_SRC_COLOUR;
+       }
+       if ( string_equal_nocase( result, "gl_one_minus_src_color" ) ) {
+               return BLEND_ONE_MINUS_SRC_COLOUR;
+       }
+       if ( string_equal_nocase( result, "gl_src_alpha" ) ) {
+               return BLEND_SRC_ALPHA;
+       }
+       if ( string_equal_nocase( result, "gl_one_minus_src_alpha" ) ) {
+               return BLEND_ONE_MINUS_SRC_ALPHA;
+       }
+       if ( string_equal_nocase( result, "gl_dst_color" ) ) {
+               return BLEND_DST_COLOUR;
+       }
+       if ( string_equal_nocase( result, "gl_one_minus_dst_color" ) ) {
+               return BLEND_ONE_MINUS_DST_COLOUR;
+       }
+       if ( string_equal_nocase( result, "gl_dst_alpha" ) ) {
+               return BLEND_DST_ALPHA;
+       }
+       if ( string_equal_nocase( result, "gl_one_minus_dst_alpha" ) ) {
+               return BLEND_ONE_MINUS_DST_ALPHA;
+       }
+       if ( string_equal_nocase( result, "gl_src_alpha_saturate" ) ) {
+               return BLEND_SRC_ALPHA_SATURATE;
+       }
+
+       globalErrorStream() << "parsing blend-factor value failed: " << makeQuoted( result ) << "\n";
+       return BLEND_ZERO;
+}
+
+class CShader : public IShader
 {
-    const char *result = evaluateShaderValue(value.c_str(), params, args);
-
-    if (string_equal_nocase(result, "gl_zero")) {
-        return BLEND_ZERO;
-    }
-    if (string_equal_nocase(result, "gl_one")) {
-        return BLEND_ONE;
-    }
-    if (string_equal_nocase(result, "gl_src_color")) {
-        return BLEND_SRC_COLOUR;
-    }
-    if (string_equal_nocase(result, "gl_one_minus_src_color")) {
-        return BLEND_ONE_MINUS_SRC_COLOUR;
-    }
-    if (string_equal_nocase(result, "gl_src_alpha")) {
-        return BLEND_SRC_ALPHA;
-    }
-    if (string_equal_nocase(result, "gl_one_minus_src_alpha")) {
-        return BLEND_ONE_MINUS_SRC_ALPHA;
-    }
-    if (string_equal_nocase(result, "gl_dst_color")) {
-        return BLEND_DST_COLOUR;
-    }
-    if (string_equal_nocase(result, "gl_one_minus_dst_color")) {
-        return BLEND_ONE_MINUS_DST_COLOUR;
-    }
-    if (string_equal_nocase(result, "gl_dst_alpha")) {
-        return BLEND_DST_ALPHA;
-    }
-    if (string_equal_nocase(result, "gl_one_minus_dst_alpha")) {
-        return BLEND_ONE_MINUS_DST_ALPHA;
-    }
-    if (string_equal_nocase(result, "gl_src_alpha_saturate")) {
-        return BLEND_SRC_ALPHA_SATURATE;
-    }
-
-    globalErrorStream() << "parsing blend-factor value failed: " << makeQuoted(result) << "\n";
-    return BLEND_ZERO;
-}
-
-class CShader : public IShader {
-    std::size_t m_refcount;
-
-    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;
-
-    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;
+std::size_t m_refcount;
 
+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;
 
-public:
-    static bool m_lightingEnabled;
+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;
 
-    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;
+bool m_bInUse;
 
-        m_notfound = 0;
 
-        realise();
-    }
+public:
+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;
+
+       m_notfound = 0;
+
+       realise();
+}
 
-    virtual ~CShader()
-    {
-        unrealise();
+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;
-        }
-    }
-
-    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;
+       }
+}
+
+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;
-    };
-
-// get shader file name (ie the file where this one is defined)
-    const char *getShaderFileName() const
-    {
-        return m_filename;
-    }
+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;
+}
 // -----------------------------------------
 
-    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;
-
-            {
-                m_pTexture = GlobalTexturesCache().capture(IsDefault() ? DEFAULT_NOTEX_NAME : DEFAULT_SHADERNOTEX_NAME);
-            }
-        }
-
-        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);
-
-                    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);
-
-            GlobalTexturesCache().release(m_pLightFalloffImage);
-
-            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);
-        }
-    }
+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;
+
+               {
+                       m_pTexture = GlobalTexturesCache().capture( IsDefault() ? DEFAULT_NOTEX_NAME : DEFAULT_SHADERNOTEX_NAME );
+               }
+       }
+
+       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 );
+
+                               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 );
+
+               GlobalTexturesCache().release( m_pLightFalloffImage );
+
+               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 );
+       }
+}
 
 // set shader 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;
-        }
-    };
-
-    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<MapLayer> MapLayers;
-    MapLayers m_layers;
-
-    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;
-    }
+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;
+}
+};
+
+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<MapLayer> MapLayers;
+MapLayers m_layers;
+
+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;
+}
 };
 
 bool CShader::m_lightingEnabled = false;
@@ -1148,378 +1129,396 @@ shaders_t g_ActiveShaders;
 
 static shaders_t::iterator g_ActiveShadersIterator;
 
-void ActiveShaders_IteratorBegin()
-{
-    g_ActiveShadersIterator = g_ActiveShaders.begin();
+void ActiveShaders_IteratorBegin(){
+       g_ActiveShadersIterator = g_ActiveShaders.begin();
 }
 
-bool ActiveShaders_IteratorAtEnd()
-{
-    return g_ActiveShadersIterator == g_ActiveShaders.end();
+bool ActiveShaders_IteratorAtEnd(){
+       return g_ActiveShadersIterator == g_ActiveShaders.end();
 }
 
-IShader *ActiveShaders_IteratorCurrent()
-{
-    return static_cast<CShader *>( g_ActiveShadersIterator->second );
+IShader *ActiveShaders_IteratorCurrent(){
+       return static_cast<CShader*>( g_ActiveShadersIterator->second );
 }
 
-void ActiveShaders_IteratorIncrement()
-{
-    ++g_ActiveShadersIterator;
+void ActiveShaders_IteratorIncrement(){
+       ++g_ActiveShadersIterator;
 }
 
-void debug_check_shaders(shaders_t &shaders)
-{
-    for (shaders_t::iterator i = shaders.begin(); i != shaders.end(); ++i) {
-        ASSERT_MESSAGE(i->second->refcount() == 1, "orphan shader still referenced");
-    }
+void debug_check_shaders( shaders_t& shaders ){
+       for ( shaders_t::iterator i = shaders.begin(); i != shaders.end(); ++i )
+       {
+               ASSERT_MESSAGE( i->second->refcount() == 1, "orphan shader still referenced" );
+       }
 }
 
 // will free all GL binded qtextures and shaders
 // NOTE: doesn't make much sense out of Radiant exit or called during a reload
-void FreeShaders()
-{
-    // reload shaders
-    // empty the actives shaders list
-    debug_check_shaders(g_ActiveShaders);
-    g_ActiveShaders.clear();
-    g_shaders.clear();
-    g_shaderTemplates.clear();
-    g_shaderDefinitions.clear();
-    g_ActiveShadersChangedNotify();
+void FreeShaders(){
+       // reload shaders
+       // empty the actives shaders list
+       debug_check_shaders( g_ActiveShaders );
+       g_ActiveShaders.clear();
+       g_shaders.clear();
+       g_shaderTemplates.clear();
+       g_shaderDefinitions.clear();
+       g_ActiveShadersChangedNotify();
+}
+
+bool ShaderTemplate::parseQuake3( Tokeniser& tokeniser ){
+       // name of the qtexture_t we'll use to represent this shader ( this one has the "textures\" before )
+       m_textureName = m_Name.c_str();
+
+       tokeniser.nextLine();
+
+       // we need to read until we hit a balanced }
+       int depth = 0;
+       for (;; )
+       {
+               tokeniser.nextLine();
+               const char* token = tokeniser.getToken();
+
+               if ( token == 0 ) {
+                       return false;
+               }
+
+               if ( string_equal( token, "{" ) ) {
+                       ++depth;
+                       continue;
+               }
+               else if ( string_equal( token, "}" ) ) {
+                       --depth;
+                       if ( depth < 0 ) { // underflow
+                               return false;
+                       }
+                       if ( depth == 0 ) { // end of shader
+                               break;
+                       }
+
+                       continue;
+               }
+
+               if ( depth == 1 ) {
+                       if ( string_equal_nocase( token, "qer_nocarve" ) ) {
+                               m_nFlags |= QER_NOCARVE;
+                       }
+                       else if ( string_equal_nocase( token, "qer_trans" ) ) {
+                               RETURN_FALSE_IF_FAIL( Tokeniser_getFloat( tokeniser, m_fTrans ) );
+                               m_nFlags |= QER_TRANS;
+                       }
+                       else if ( string_equal_nocase( token, "qer_editorimage" ) ) {
+                               RETURN_FALSE_IF_FAIL( Tokeniser_parseTextureName( tokeniser, m_textureName ) );
+                       }
+                       else if ( string_equal_nocase( token, "qer_alphafunc" ) ) {
+                               const char* alphafunc = tokeniser.getToken();
+
+                               if ( alphafunc == 0 ) {
+                                       Tokeniser_unexpectedError( tokeniser, alphafunc, "#alphafunc" );
+                                       return false;
+                               }
+
+                               if ( string_equal_nocase( alphafunc, "equal" ) ) {
+                                       m_AlphaFunc = IShader::eEqual;
+                               }
+                               else if ( string_equal_nocase( alphafunc, "greater" ) ) {
+                                       m_AlphaFunc = IShader::eGreater;
+                               }
+                               else if ( string_equal_nocase( alphafunc, "less" ) ) {
+                                       m_AlphaFunc = IShader::eLess;
+                               }
+                               else if ( string_equal_nocase( alphafunc, "gequal" ) ) {
+                                       m_AlphaFunc = IShader::eGEqual;
+                               }
+                               else if ( string_equal_nocase( alphafunc, "lequal" ) ) {
+                                       m_AlphaFunc = IShader::eLEqual;
+                               }
+                               else
+                               {
+                                       m_AlphaFunc = IShader::eAlways;
+                               }
+
+                               m_nFlags |= QER_ALPHATEST;
+
+                               RETURN_FALSE_IF_FAIL( Tokeniser_getFloat( tokeniser, m_AlphaRef ) );
+                       }
+                       else if ( string_equal_nocase( token, "cull" ) ) {
+                               const char* cull = tokeniser.getToken();
+
+                               if ( cull == 0 ) {
+                                       Tokeniser_unexpectedError( tokeniser, cull, "#cull" );
+                                       return false;
+                               }
+
+                               if ( string_equal_nocase( cull, "none" )
+                                        || 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" ) ) {
+                                       m_Cull = IShader::eCullBack;
+                               }
+                               else
+                               {
+                                       m_Cull = IShader::eCullBack;
+                               }
+
+                               m_nFlags |= QER_CULL;
+                       }
+                       else if ( string_equal_nocase( token, "surfaceparm" ) ) {
+                               const char* surfaceparm = tokeniser.getToken();
+
+                               if ( surfaceparm == 0 ) {
+                                       Tokeniser_unexpectedError( tokeniser, surfaceparm, "#surfaceparm" );
+                                       return false;
+                               }
+
+                               if ( string_equal_nocase( surfaceparm, "fog" ) ) {
+                                       m_nFlags |= QER_FOG;
+                                       if ( m_fTrans == 1.0f ) { // has not been explicitly set by qer_trans
+                                               m_fTrans = 0.35f;
+                                       }
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "nodraw" ) ) {
+                                       m_nFlags |= QER_NODRAW;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "nonsolid" ) ) {
+                                       m_nFlags |= QER_NONSOLID;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "water" ) ) {
+                                       m_nFlags |= QER_WATER;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "lava" ) ) {
+                                       m_nFlags |= QER_LAVA;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "areaportal" ) ) {
+                                       m_nFlags |= QER_AREAPORTAL;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "playerclip" ) ) {
+                                       m_nFlags |= QER_CLIP;
+                               }
+                               else if ( string_equal_nocase( surfaceparm, "botclip" ) ) {
+                                       m_nFlags |= QER_BOTCLIP;
+                               }
+                       }
+               }
+       }
+
+       return true;
 }
 
-bool ShaderTemplate::parseQuake3(Tokeniser &tokeniser)
+class Layer
 {
-    // name of the qtexture_t we'll use to represent this shader (this one has the "textures\" before)
-    m_textureName = m_Name.c_str();
-
-    tokeniser.nextLine();
-
-    // we need to read until we hit a balanced }
-    int depth = 0;
-    for (;;) {
-        tokeniser.nextLine();
-        const char *token = tokeniser.getToken();
-
-        if (token == 0) {
-            return false;
-        }
-
-        if (string_equal(token, "{")) {
-            ++depth;
-            continue;
-        } else if (string_equal(token, "}")) {
-            --depth;
-            if (depth < 0) { // underflow
-                return false;
-            }
-            if (depth == 0) { // end of shader
-                break;
-            }
-
-            continue;
-        }
-
-        if (depth == 1) {
-            if (string_equal_nocase(token, "qer_nocarve")) {
-                m_nFlags |= QER_NOCARVE;
-            } else if (string_equal_nocase(token, "qer_trans")) {
-                RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, m_fTrans));
-                m_nFlags |= QER_TRANS;
-            } else if (string_equal_nocase(token, "qer_editorimage")) {
-                RETURN_FALSE_IF_FAIL(Tokeniser_parseTextureName(tokeniser, m_textureName));
-            } else if (string_equal_nocase(token, "qer_alphafunc")) {
-                const char *alphafunc = tokeniser.getToken();
-
-                if (alphafunc == 0) {
-                    Tokeniser_unexpectedError(tokeniser, alphafunc, "#alphafunc");
-                    return false;
-                }
-
-                if (string_equal_nocase(alphafunc, "equal")) {
-                    m_AlphaFunc = IShader::eEqual;
-                } else if (string_equal_nocase(alphafunc, "greater")) {
-                    m_AlphaFunc = IShader::eGreater;
-                } else if (string_equal_nocase(alphafunc, "less")) {
-                    m_AlphaFunc = IShader::eLess;
-                } else if (string_equal_nocase(alphafunc, "gequal")) {
-                    m_AlphaFunc = IShader::eGEqual;
-                } else if (string_equal_nocase(alphafunc, "lequal")) {
-                    m_AlphaFunc = IShader::eLEqual;
-                } else {
-                    m_AlphaFunc = IShader::eAlways;
-                }
-
-                m_nFlags |= QER_ALPHATEST;
-
-                RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, m_AlphaRef));
-            } else if (string_equal_nocase(token, "cull")) {
-                const char *cull = tokeniser.getToken();
-
-                if (cull == 0) {
-                    Tokeniser_unexpectedError(tokeniser, cull, "#cull");
-                    return false;
-                }
-
-                if (string_equal_nocase(cull, "none")
-                    || 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")) {
-                    m_Cull = IShader::eCullBack;
-                } else {
-                    m_Cull = IShader::eCullBack;
-                }
-
-                m_nFlags |= QER_CULL;
-            } else if (string_equal_nocase(token, "surfaceparm")) {
-                const char *surfaceparm = tokeniser.getToken();
-
-                if (surfaceparm == 0) {
-                    Tokeniser_unexpectedError(tokeniser, surfaceparm, "#surfaceparm");
-                    return false;
-                }
-
-                if (string_equal_nocase(surfaceparm, "fog")) {
-                    m_nFlags |= QER_FOG;
-                    if (m_fTrans == 1.0f) { // has not been explicitly set by qer_trans
-                        m_fTrans = 0.35f;
-                    }
-                } else if (string_equal_nocase(surfaceparm, "nodraw")) {
-                    m_nFlags |= QER_NODRAW;
-                } else if (string_equal_nocase(surfaceparm, "nonsolid")) {
-                    m_nFlags |= QER_NONSOLID;
-                } else if (string_equal_nocase(surfaceparm, "water")) {
-                    m_nFlags |= QER_WATER;
-                } else if (string_equal_nocase(surfaceparm, "lava")) {
-                    m_nFlags |= QER_LAVA;
-                } else if (string_equal_nocase(surfaceparm, "areaportal")) {
-                    m_nFlags |= QER_AREAPORTAL;
-                } else if (string_equal_nocase(surfaceparm, "playerclip")) {
-                    m_nFlags |= QER_CLIP;
-                } else if (string_equal_nocase(surfaceparm, "botclip")) {
-                    m_nFlags |= QER_BOTCLIP;
-                }
-            }
-        }
-    }
-
-    return true;
-}
-
-class Layer {
 public:
-    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)
-    {
-    }
+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 ){
+}
 };
 
 std::list<CopiedString> g_shaderFilenames;
 
-void ParseShaderFile(Tokeniser &tokeniser, const char *filename)
-{
-    g_shaderFilenames.push_back(filename);
-    filename = g_shaderFilenames.back().c_str();
-    tokeniser.nextLine();
-    for (;;) {
-        const char *token = tokeniser.getToken();
-
-        if (token == 0) {
-            break;
-        }
-
-        if (string_equal(token, "table")) {
-            if (tokeniser.getToken() == 0) {
-                Tokeniser_unexpectedError(tokeniser, 0, "#table-name");
-                return;
-            }
-            if (!Tokeniser_parseToken(tokeniser, "{")) {
-                return;
-            }
-            for (;;) {
-                const char *option = tokeniser.getToken();
-                if (string_equal(option, "{")) {
-                    for (;;) {
-                        const char *value = tokeniser.getToken();
-                        if (string_equal(value, "}")) {
-                            break;
-                        }
-                    }
-
-                    if (!Tokeniser_parseToken(tokeniser, "}")) {
-                        return;
-                    }
-                    break;
-                }
-            }
-        } else {
-            if (string_equal(token, "guide")) {
-                parseTemplateInstance(tokeniser, filename);
-            } else {
-                if (!string_equal(token, "material")
-                    && !string_equal(token, "particle")
-                    && !string_equal(token, "skin")) {
-                    tokeniser.ungetToken();
-                }
-                // first token should be the path + name.. (from base)
-                CopiedString name;
-                if (!Tokeniser_parseShaderName(tokeniser, name)) {
-                }
-                ShaderTemplatePointer shaderTemplate(new ShaderTemplate());
-                shaderTemplate->setName(name.c_str());
-
-                g_shaders.insert(ShaderTemplateMap::value_type(shaderTemplate->getName(), shaderTemplate));
-
-                bool result = (g_shaderLanguage == SHADERLANGUAGE_QUAKE3)
-                              ? 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) {
+void ParseShaderFile( Tokeniser& tokeniser, const char* filename ){
+       g_shaderFilenames.push_back( filename );
+       filename = g_shaderFilenames.back().c_str();
+       tokeniser.nextLine();
+       for (;; )
+       {
+               const char* token = tokeniser.getToken();
+
+               if ( token == 0 ) {
+                       break;
+               }
+
+               if ( string_equal( token, "table" ) ) {
+                       if ( tokeniser.getToken() == 0 ) {
+                               Tokeniser_unexpectedError( tokeniser, 0, "#table-name" );
+                               return;
+                       }
+                       if ( !Tokeniser_parseToken( tokeniser, "{" ) ) {
+                               return;
+                       }
+                       for (;; )
+                       {
+                               const char* option = tokeniser.getToken();
+                               if ( string_equal( option, "{" ) ) {
+                                       for (;; )
+                                       {
+                                               const char* value = tokeniser.getToken();
+                                               if ( string_equal( value, "}" ) ) {
+                                                       break;
+                                               }
+                                       }
+
+                                       if ( !Tokeniser_parseToken( tokeniser, "}" ) ) {
+                                               return;
+                                       }
+                                       break;
+                               }
+                       }
+               }
+               else
+               {
+                       if ( string_equal( token, "guide" ) ) {
+                               parseTemplateInstance( tokeniser, filename );
+                       }
+                       else
+                       {
+                               if ( !string_equal( token, "material" )
+                                        && !string_equal( token, "particle" )
+                                        && !string_equal( token, "skin" ) ) {
+                                       tokeniser.ungetToken();
+                               }
+                               // first token should be the path + name.. ( from base )
+                               CopiedString name;
+                               if ( !Tokeniser_parseShaderName( tokeniser, name ) ) {
+                               }
+                               ShaderTemplatePointer shaderTemplate( new ShaderTemplate() );
+                               shaderTemplate->setName( name.c_str() );
+
+                               g_shaders.insert( ShaderTemplateMap::value_type( shaderTemplate->getName(), shaderTemplate ) );
+
+                               bool result = ( g_shaderLanguage == SHADERLANGUAGE_QUAKE3 )
+                                                         ? 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 ) {
 #if GDEF_DEBUG
-                        globalOutputStream() << "WARNING: shader " << shaderTemplate->getName()
-                                             << " is already in memory, definition in " << filename << " ignored.\n";
+                                               globalOutputStream() << "WARNING: shader " << shaderTemplate->getName() << " is already in memory, definition in " << filename << " ignored.\n";
 #endif
-                    }
-                } else {
-                    globalErrorStream() << "Error parsing shader " << shaderTemplate->getName() << "\n";
-                    return;
-                }
-            }
-        }
-    }
+                                       }
+                               }
+                               else
+                               {
+                                       globalErrorStream() << "Error parsing shader " << shaderTemplate->getName() << "\n";
+                                       return;
+                               }
+                       }
+               }
+       }
 }
 
-void parseGuideFile(Tokeniser &tokeniser, const char *filename)
-{
-    tokeniser.nextLine();
-    for (;;) {
-        const char *token = tokeniser.getToken();
-
-        if (token == 0) {
-            break;
-        }
-
-        if (string_equal(token, "guide")) {
-            // first token should be the path + name.. (from base)
-            ShaderTemplatePointer shaderTemplate(new ShaderTemplate);
-            shaderTemplate->parseTemplate(tokeniser);
-            if (!g_shaderTemplates.insert(
-                    ShaderTemplateMap::value_type(shaderTemplate->getName(), shaderTemplate)).second) {
-                globalErrorStream() << "guide " << makeQuoted(shaderTemplate->getName())
-                                    << ": already defined, second definition ignored\n";
-            }
-        } else if (string_equal(token, "inlineGuide")) {
-            // skip entire inlineGuide definition
-            std::size_t depth = 0;
-            for (;;) {
-                tokeniser.nextLine();
-                token = tokeniser.getToken();
-                if (string_equal(token, "{")) {
-                    ++depth;
-                } else if (string_equal(token, "}")) {
-                    if (--depth == 0) {
-                        break;
-                    }
-                }
-            }
-        }
-    }
-}
-
-void LoadShaderFile(const char *filename)
-{
-    ArchiveTextFile *file = GlobalFileSystem().openTextFile(filename);
+void parseGuideFile( Tokeniser& tokeniser, const char* filename ){
+       tokeniser.nextLine();
+       for (;; )
+       {
+               const char* token = tokeniser.getToken();
+
+               if ( token == 0 ) {
+                       break;
+               }
+
+               if ( string_equal( token, "guide" ) ) {
+                       // first token should be the path + name.. ( from base )
+                       ShaderTemplatePointer shaderTemplate( new ShaderTemplate );
+                       shaderTemplate->parseTemplate( tokeniser );
+                       if ( !g_shaderTemplates.insert( ShaderTemplateMap::value_type( shaderTemplate->getName(), shaderTemplate ) ).second ) {
+                               globalErrorStream() << "guide " << makeQuoted( shaderTemplate->getName() ) << ": already defined, second definition ignored\n";
+                       }
+               }
+               else if ( string_equal( token, "inlineGuide" ) ) {
+                       // skip entire inlineGuide definition
+                       std::size_t depth = 0;
+                       for (;; )
+                       {
+                               tokeniser.nextLine();
+                               token = tokeniser.getToken();
+                               if ( string_equal( token, "{" ) ) {
+                                       ++depth;
+                               }
+                               else if ( string_equal( token, "}" ) ) {
+                                       if ( --depth == 0 ) {
+                                               break;
+                                       }
+                               }
+                       }
+               }
+       }
+}
 
-    if (file != 0) {
-        globalOutputStream() << "Parsing shaderfile " << filename << "\n";
+void LoadShaderFile( const char* filename ){
+       ArchiveTextFile* file = GlobalFileSystem().openTextFile( filename );
 
-        Tokeniser &tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(file->getInputStream());
+       if ( file != 0 ) {
+               globalOutputStream() << "Parsing shaderfile " << filename << "\n";
 
-        ParseShaderFile(tokeniser, filename);
+               Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser( file->getInputStream() );
 
-        tokeniser.release();
-        file->release();
-    } else {
-        globalOutputStream() << "Unable to read shaderfile " << filename << "\n";
-    }
+               ParseShaderFile( tokeniser, filename );
+
+               tokeniser.release();
+               file->release();
+       }
+       else
+       {
+               globalOutputStream() << "Unable to read shaderfile " << filename << "\n";
+       }
 }
 
-void loadGuideFile(const char *filename)
-{
-    StringOutputStream fullname(256);
-    fullname << "guides/" << filename;
-    ArchiveTextFile *file = GlobalFileSystem().openTextFile(fullname.c_str());
+void loadGuideFile( const char* filename ){
+       StringOutputStream fullname( 256 );
+       fullname << "guides/" << filename;
+       ArchiveTextFile* file = GlobalFileSystem().openTextFile( fullname.c_str() );
 
-    if (file != 0) {
-        globalOutputStream() << "Parsing guide file " << fullname.c_str() << "\n";
+       if ( file != 0 ) {
+               globalOutputStream() << "Parsing guide file " << fullname.c_str() << "\n";
 
-        Tokeniser &tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(file->getInputStream());
+               Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser( file->getInputStream() );
 
-        parseGuideFile(tokeniser, fullname.c_str());
+               parseGuideFile( tokeniser, fullname.c_str() );
 
-        tokeniser.release();
-        file->release();
-    } else {
-        globalOutputStream() << "Unable to read guide file " << fullname.c_str() << "\n";
-    }
+               tokeniser.release();
+               file->release();
+       }
+       else
+       {
+               globalOutputStream() << "Unable to read guide file " << fullname.c_str() << "\n";
+       }
 }
 
-CShader *Try_Shader_ForName(const char *name)
-{
-    {
-        shaders_t::iterator i = g_ActiveShaders.find(name);
-        if (i != g_ActiveShaders.end()) {
-            return (*i).second;
-        }
-    }
-    // active shader was not found
-
-    // find matching shader definition
-    ShaderDefinitionMap::iterator i = g_shaderDefinitions.find(name);
-    if (i == g_shaderDefinitions.end()) {
-        // shader definition was not found
-
-        // create new shader definition from default shader template
-        ShaderTemplatePointer shaderTemplate(new ShaderTemplate());
-        shaderTemplate->CreateDefault(name);
-        g_shaderTemplates.insert(ShaderTemplateMap::value_type(shaderTemplate->getName(), shaderTemplate));
-
-        i = g_shaderDefinitions.insert(ShaderDefinitionMap::value_type(name, ShaderDefinition(shaderTemplate.get(),
-                                                                                              ShaderArguments(),
-                                                                                              ""))).first;
-    }
-
-    // create shader from existing definition
-    ShaderPointer pShader(new CShader((*i).second));
-    pShader->setName(name);
-    g_ActiveShaders.insert(shaders_t::value_type(name, pShader));
-    g_ActiveShadersChangedNotify();
-    return pShader;
-}
-
-IShader *Shader_ForName(const char *name)
-{
-    ASSERT_NOTNULL(name);
+CShader* Try_Shader_ForName( const char* name ){
+       {
+               shaders_t::iterator i = g_ActiveShaders.find( name );
+               if ( i != g_ActiveShaders.end() ) {
+                       return ( *i ).second;
+               }
+       }
+       // active shader was not found
+
+       // find matching shader definition
+       ShaderDefinitionMap::iterator i = g_shaderDefinitions.find( name );
+       if ( i == g_shaderDefinitions.end() ) {
+               // shader definition was not found
+
+               // create new shader definition from default shader template
+               ShaderTemplatePointer shaderTemplate( new ShaderTemplate() );
+               shaderTemplate->CreateDefault( name );
+               g_shaderTemplates.insert( ShaderTemplateMap::value_type( shaderTemplate->getName(), shaderTemplate ) );
+
+               i = g_shaderDefinitions.insert( ShaderDefinitionMap::value_type( name, ShaderDefinition( shaderTemplate.get(), ShaderArguments(), "" ) ) ).first;
+       }
+
+       // create shader from existing definition
+       ShaderPointer pShader( new CShader( ( *i ).second ) );
+       pShader->setName( name );
+       g_ActiveShaders.insert( shaders_t::value_type( name, pShader ) );
+       g_ActiveShadersChangedNotify();
+       return pShader;
+}
+
+IShader *Shader_ForName( const char *name ){
+       ASSERT_NOTNULL( name );
 
-    IShader *pShader = Try_Shader_ForName(name);
-    pShader->IncRef();
-    return pShader;
+       IShader *pShader = Try_Shader_ForName( name );
+       pShader->IncRef();
+       return pShader;
 }
 
 
@@ -1527,9 +1526,8 @@ IShader *Shader_ForName(const char *name)
 // those are listed in shaderlist file
 GSList *l_shaderfiles = 0;
 
-GSList *Shaders_getShaderFileList()
-{
-    return l_shaderfiles;
+GSList* Shaders_getShaderFileList(){
+       return l_shaderfiles;
 }
 
 /*
@@ -1538,49 +1536,48 @@ GSList *Shaders_getShaderFileList()
    usefull function: dumps the list of .shader files that are not referenced to the console
    ==================
  */
-void IfFound_dumpUnreferencedShader(bool &bFound, const char *filename)
-{
-    bool listed = false;
-
-    for (GSList *sh = l_shaderfiles; sh != 0; sh = g_slist_next(sh)) {
-        if (!strcmp((char *) sh->data, filename)) {
-            listed = true;
-            break;
-        }
-    }
-
-    if (!listed) {
-        if (!bFound) {
-            bFound = true;
-            globalOutputStream() << "Following shader files are not referenced in any shaderlist.txt:\n";
-        }
-        globalOutputStream() << "\t" << filename << "\n";
-    }
+void IfFound_dumpUnreferencedShader( bool& bFound, const char* filename ){
+       bool listed = false;
+
+       for ( GSList* sh = l_shaderfiles; sh != 0; sh = g_slist_next( sh ) )
+       {
+               if ( !strcmp( (char*)sh->data, filename ) ) {
+                       listed = true;
+                       break;
+               }
+       }
+
+       if ( !listed ) {
+               if ( !bFound ) {
+                       bFound = true;
+                       globalOutputStream() << "Following shader files are not referenced in any shaderlist.txt:\n";
+               }
+               globalOutputStream() << "\t" << filename << "\n";
+       }
 }
 
-typedef ReferenceCaller<bool, void(const char *), IfFound_dumpUnreferencedShader> IfFoundDumpUnreferencedShaderCaller;
+typedef ReferenceCaller<bool, void(const char*), IfFound_dumpUnreferencedShader> IfFoundDumpUnreferencedShaderCaller;
 
-void DumpUnreferencedShaders()
-{
-    bool bFound = false;
-    GlobalFileSystem().forEachFile(g_shadersDirectory, g_shadersExtension, IfFoundDumpUnreferencedShaderCaller(bFound));
+void DumpUnreferencedShaders(){
+       bool bFound = false;
+       GlobalFileSystem().forEachFile( g_shadersDirectory, g_shadersExtension, IfFoundDumpUnreferencedShaderCaller( bFound ) );
 }
 
-void ShaderList_addShaderFile(const char *dirstring)
-{
-    bool found = false;
-
-    for (GSList *tmp = l_shaderfiles; tmp != 0; tmp = tmp->next) {
-        if (string_equal_nocase(dirstring, (char *) tmp->data)) {
-            found = true;
-            globalOutputStream() << "duplicate entry \"" << (char *) tmp->data << "\" in shaderlist.txt\n";
-            break;
-        }
-    }
-
-    if (!found) {
-        l_shaderfiles = g_slist_append(l_shaderfiles, strdup(dirstring));
-    }
+void ShaderList_addShaderFile( const char* dirstring ){
+       bool found = false;
+
+       for ( GSList* tmp = l_shaderfiles; tmp != 0; tmp = tmp->next )
+       {
+               if ( string_equal_nocase( dirstring, (char*)tmp->data ) ) {
+                       found = true;
+                       globalOutputStream() << "duplicate entry \"" << (char*)tmp->data << "\" in shaderlist.txt\n";
+                       break;
+               }
+       }
+
+       if ( !found ) {
+               l_shaderfiles = g_slist_append( l_shaderfiles, strdup( dirstring ) );
+       }
 }
 
 /*
@@ -1589,264 +1586,244 @@ void ShaderList_addShaderFile(const char *dirstring)
    build a CStringList of shader names
    ==================
  */
-void BuildShaderList(TextInputStream &shaderlist)
-{
-    Tokeniser &tokeniser = GlobalScriptLibrary().m_pfnNewSimpleTokeniser(shaderlist);
-    tokeniser.nextLine();
-    const char *token = tokeniser.getToken();
-    StringOutputStream shaderFile(64);
-    while (token != 0) {
-        // each token should be a shader filename
-        shaderFile << token << "." << g_shadersExtension;
-
-        ShaderList_addShaderFile(shaderFile.c_str());
+void BuildShaderList( TextInputStream& shaderlist ){
+       Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewSimpleTokeniser( shaderlist );
+       tokeniser.nextLine();
+       const char* token = tokeniser.getToken();
+       StringOutputStream shaderFile( 64 );
+       while ( token != 0 )
+       {
+               // each token should be a shader filename
+               shaderFile << token << "." << g_shadersExtension;
+
+               ShaderList_addShaderFile( shaderFile.c_str() );
+
+               tokeniser.nextLine();
+               token = tokeniser.getToken();
+
+               shaderFile.clear();
+       }
+       tokeniser.release();
+}
 
-        tokeniser.nextLine();
-        token = tokeniser.getToken();
+void FreeShaderList(){
+       while ( l_shaderfiles != 0 )
+       {
+               free( l_shaderfiles->data );
+               l_shaderfiles = g_slist_remove( l_shaderfiles, l_shaderfiles->data );
+       }
+}
 
-        shaderFile.clear();
-    }
-    tokeniser.release();
+void ShaderList_addFromArchive( const char *archivename ){
+       const char *shaderpath = GlobalRadiant().getGameDescriptionKeyValue( "shaderpath" );
+       if ( string_empty( shaderpath ) ) {
+               return;
+       }
+
+       StringOutputStream shaderlist( 256 );
+       shaderlist << DirectoryCleaned( shaderpath ) << "shaderlist.txt";
+
+       Archive *archive = GlobalFileSystem().getArchive( archivename, false );
+       if ( archive ) {
+               ArchiveTextFile *file = archive->openTextFile( shaderlist.c_str() );
+               if ( file ) {
+                       globalOutputStream() << "Found shaderlist.txt in " << archivename << "\n";
+                       BuildShaderList( file->getInputStream() );
+                       file->release();
+               }
+       }
 }
 
-void FreeShaderList()
-{
-    while (l_shaderfiles != 0) {
-        free(l_shaderfiles->data);
-        l_shaderfiles = g_slist_remove(l_shaderfiles, l_shaderfiles->data);
-    }
+#include "stream/filestream.h"
+
+bool shaderlist_findOrInstall( const char* enginePath, const char* toolsPath, const char* shaderPath, const char* gamename ){
+       StringOutputStream absShaderList( 256 );
+       absShaderList << enginePath << gamename << '/' << shaderPath << "shaderlist.txt";
+       if ( file_exists( absShaderList.c_str() ) ) {
+               return true;
+       }
+       {
+               StringOutputStream directory( 256 );
+               directory << enginePath << gamename << '/' << shaderPath;
+               if ( !file_exists( directory.c_str() ) && !Q_mkdir( directory.c_str() ) ) {
+                       return false;
+               }
+       }
+       {
+               StringOutputStream defaultShaderList( 256 );
+               defaultShaderList << toolsPath << gamename << '/' << "default_shaderlist.txt";
+               if ( file_exists( defaultShaderList.c_str() ) ) {
+                       return file_copy( defaultShaderList.c_str(), absShaderList.c_str() );
+               }
+       }
+       return false;
 }
 
-void ShaderList_addFromArchive(const char *archivename)
-{
-    const char *shaderpath = GlobalRadiant().getGameDescriptionKeyValue("shaderpath");
-    if (string_empty(shaderpath)) {
-        return;
-    }
+void Shaders_Load(){
+       if ( g_shaderLanguage == SHADERLANGUAGE_QUAKE4 ) {
+               GlobalFileSystem().forEachFile("guides/", "guide", makeCallbackF(loadGuideFile), 0);
+       }
 
-    StringOutputStream shaderlist(256);
-    shaderlist << DirectoryCleaned(shaderpath) << "shaderlist.txt";
+       const char* shaderPath = GlobalRadiant().getGameDescriptionKeyValue( "shaderpath" );
+       if ( !string_empty( shaderPath ) ) {
+               StringOutputStream path( 256 );
+               path << DirectoryCleaned( shaderPath );
 
-    Archive *archive = GlobalFileSystem().getArchive(archivename, false);
-    if (archive) {
-        ArchiveTextFile *file = archive->openTextFile(shaderlist.c_str());
-        if (file) {
-            globalOutputStream() << "Found shaderlist.txt in " << archivename << "\n";
-            BuildShaderList(file->getInputStream());
-            file->release();
-        }
-    }
-}
+               if ( g_useShaderList ) {
+                       // preload shader files that have been listed in shaderlist.txt
+                       const char* basegame = GlobalRadiant().getRequiredGameDescriptionKeyValue( "basegame" );
+                       const char* gamename = GlobalRadiant().getGameName();
+                       const char* enginePath = GlobalRadiant().getEnginePath();
+                       const char* toolsPath = GlobalRadiant().getGameToolsPath();
 
-#include "stream/filestream.h"
+                       bool isMod = !string_equal( basegame, gamename );
 
-bool
-shaderlist_findOrInstall(const char *enginePath, const char *toolsPath, const char *shaderPath, const char *gamename)
-{
-    StringOutputStream absShaderList(256);
-    absShaderList << enginePath << gamename << '/' << shaderPath << "shaderlist.txt";
-    if (file_exists(absShaderList.c_str())) {
-        return true;
-    }
-    {
-        StringOutputStream directory(256);
-        directory << enginePath << gamename << '/' << shaderPath;
-        if (!file_exists(directory.c_str()) && !Q_mkdir(directory.c_str())) {
-            return false;
-        }
-    }
-    {
-        StringOutputStream defaultShaderList(256);
-        defaultShaderList << toolsPath << gamename << '/' << "default_shaderlist.txt";
-        if (file_exists(defaultShaderList.c_str())) {
-            return file_copy(defaultShaderList.c_str(), absShaderList.c_str());
-        }
-    }
-    return false;
-}
-
-void Shaders_Load()
-{
-    if (g_shaderLanguage == SHADERLANGUAGE_QUAKE4) {
-        GlobalFileSystem().forEachFile("guides/", "guide", makeCallbackF(loadGuideFile), 0);
-    }
-
-    const char *shaderPath = GlobalRadiant().getGameDescriptionKeyValue("shaderpath");
-    if (!string_empty(shaderPath)) {
-        StringOutputStream path(256);
-        path << DirectoryCleaned(shaderPath);
-
-        if (g_useShaderList) {
-            // preload shader files that have been listed in shaderlist.txt
-            const char *basegame = GlobalRadiant().getRequiredGameDescriptionKeyValue("basegame");
-            const char *gamename = GlobalRadiant().getGameName();
-            const char *enginePath = GlobalRadiant().getEnginePath();
-            const char *toolsPath = GlobalRadiant().getGameToolsPath();
-
-            bool isMod = !string_equal(basegame, gamename);
-
-            if (!isMod || !shaderlist_findOrInstall(enginePath, toolsPath, path.c_str(), gamename)) {
-                gamename = basegame;
-                shaderlist_findOrInstall(enginePath, toolsPath, path.c_str(), gamename);
-            }
-
-            GlobalFileSystem().forEachArchive(makeCallbackF(ShaderList_addFromArchive), false, true);
-            DumpUnreferencedShaders();
-        } else {
-            GlobalFileSystem().forEachFile(path.c_str(), g_shadersExtension, makeCallbackF(ShaderList_addShaderFile),
-                                           0);
-        }
-
-        GSList *lst = l_shaderfiles;
-        StringOutputStream shadername(256);
-        while (lst) {
-            shadername << path.c_str() << reinterpret_cast<const char *>( lst->data );
-            LoadShaderFile(shadername.c_str());
-            shadername.clear();
-            lst = lst->next;
-        }
-    }
-
-    //StringPool_analyse(ShaderPool::instance());
-}
-
-void Shaders_Free()
-{
-    FreeShaders();
-    FreeShaderList();
-    g_shaderFilenames.clear();
+                       if ( !isMod || !shaderlist_findOrInstall( enginePath, toolsPath, path.c_str(), gamename ) ) {
+                               gamename = basegame;
+                               shaderlist_findOrInstall( enginePath, toolsPath, path.c_str(), gamename );
+                       }
+
+                       GlobalFileSystem().forEachArchive(makeCallbackF(ShaderList_addFromArchive), false, true);
+                       DumpUnreferencedShaders();
+               }
+               else
+               {
+                       GlobalFileSystem().forEachFile(path.c_str(), g_shadersExtension, makeCallbackF(ShaderList_addShaderFile), 0);
+               }
+
+               GSList *lst = l_shaderfiles;
+               StringOutputStream shadername( 256 );
+               while ( lst )
+               {
+                       shadername << path.c_str() << reinterpret_cast<const char*>( lst->data );
+                       LoadShaderFile( shadername.c_str() );
+                       shadername.clear();
+                       lst = lst->next;
+               }
+       }
+
+       //StringPool_analyse( ShaderPool::instance() );
+}
+
+void Shaders_Free(){
+       FreeShaders();
+       FreeShaderList();
+       g_shaderFilenames.clear();
 }
 
 ModuleObservers g_observers;
 
 std::size_t g_shaders_unrealised = 1; // wait until filesystem and is realised before loading anything
-bool Shaders_realised()
-{
-    return g_shaders_unrealised == 0;
+bool Shaders_realised(){
+       return g_shaders_unrealised == 0;
 }
 
-void Shaders_Realise()
-{
-    if (--g_shaders_unrealised == 0) {
-        Shaders_Load();
-        g_observers.realise();
-    }
+void Shaders_Realise(){
+       if ( --g_shaders_unrealised == 0 ) {
+               Shaders_Load();
+               g_observers.realise();
+       }
 }
 
-void Shaders_Unrealise()
-{
-    if (++g_shaders_unrealised == 1) {
-        g_observers.unrealise();
-        Shaders_Free();
-    }
+void Shaders_Unrealise(){
+       if ( ++g_shaders_unrealised == 1 ) {
+               g_observers.unrealise();
+               Shaders_Free();
+       }
 }
 
-void Shaders_Refresh()
-{
-    Shaders_Unrealise();
-    Shaders_Realise();
+void Shaders_Refresh(){
+       Shaders_Unrealise();
+       Shaders_Realise();
 }
 
-class Quake3ShaderSystem : public ShaderSystem, public ModuleObserver {
+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 beginActiveShadersIterator()
-    {
-        ActiveShaders_IteratorBegin();
-    }
-
-    bool endActiveShadersIterator()
-    {
-        return ActiveShaders_IteratorAtEnd();
-    }
-
-    IShader *dereferenceActiveShadersIterator()
-    {
-        return ActiveShaders_IteratorCurrent();
-    }
-
-    void incrementActiveShadersIterator()
-    {
-        ActiveShaders_IteratorIncrement();
-    }
-
-    void setActiveShadersChangedNotify(const Callback<void()> &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;
-    }
+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 beginActiveShadersIterator(){
+       ActiveShaders_IteratorBegin();
+}
+
+bool endActiveShadersIterator(){
+       return ActiveShaders_IteratorAtEnd();
+}
+
+IShader* dereferenceActiveShadersIterator(){
+       return ActiveShaders_IteratorCurrent();
+}
+
+void incrementActiveShadersIterator(){
+       ActiveShaders_IteratorIncrement();
+}
+
+void setActiveShadersChangedNotify( const Callback<void()>& 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;
 
-ShaderSystem &GetShaderSystem()
-{
-    return g_Quake3ShaderSystem;
+ShaderSystem& GetShaderSystem(){
+       return g_Quake3ShaderSystem;
 }
 
-void Shaders_Construct()
-{
-    GlobalFileSystem().attach(g_Quake3ShaderSystem);
+void Shaders_Construct(){
+       GlobalFileSystem().attach( g_Quake3ShaderSystem );
 }
 
-void Shaders_Destroy()
-{
-    GlobalFileSystem().detach(g_Quake3ShaderSystem);
+void Shaders_Destroy(){
+       GlobalFileSystem().detach( g_Quake3ShaderSystem );
 
-    if (Shaders_realised()) {
-        Shaders_Free();
-    }
+       if ( Shaders_realised() ) {
+               Shaders_Free();
+       }
 }
index 96401a0..21e7d9c 100644 (file)
 #include "brush_primit.h"
 
 const unsigned int BRUSH_DETAIL_FLAG = 27;
-const unsigned int BRUSH_DETAIL_MASK = (1 << BRUSH_DETAIL_FLAG);
-
-enum EBrushType {
-    eBrushTypeQuake,
-    eBrushTypeQuake2,
-    eBrushTypeQuake3,
-    eBrushTypeQuake3BP,
-    eBrushTypeDoom3,
-    eBrushTypeQuake4,
-    eBrushTypeHalfLife,
+const unsigned int BRUSH_DETAIL_MASK = ( 1 << BRUSH_DETAIL_FLAG );
+
+enum EBrushType
+{
+       eBrushTypeQuake,
+       eBrushTypeQuake2,
+       eBrushTypeQuake3,
+       eBrushTypeQuake3BP,
+       eBrushTypeDoom3,
+       eBrushTypeQuake4,
+       eBrushTypeHalfLife,
 };
 
 
@@ -83,79 +84,76 @@ enum EBrushType {
 #define BRUSH_DEGENERATE_DEBUG 0
 
 template<typename TextOuputStreamType>
-inline TextOuputStreamType &ostream_write(TextOuputStreamType &ostream, const Matrix4 &m)
-{
-    return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", "
-                   << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", "
-                   << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", "
-                   << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")";
+inline TextOuputStreamType& ostream_write( TextOuputStreamType& ostream, const Matrix4& m ){
+       return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", "
+                                  << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", "
+                                  << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", "
+                                  << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")";
 }
 
-inline void print_vector3(const Vector3 &v)
-{
-    globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
+inline void print_vector3( const Vector3& v ){
+       globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
 }
 
-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";
+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";
 }
 
 
-inline bool texdef_sane(const texdef_t &texdef)
-{
-    return fabs(texdef.shift[0]) < (1 << 16)
-           && fabs(texdef.shift[1]) < (1 << 16);
+inline bool texdef_sane( const texdef_t& texdef ){
+       return fabs( texdef.shift[0] ) < ( 1 << 16 )
+                  && fabs( texdef.shift[1] ) < ( 1 << 16 );
 }
 
-inline void Winding_DrawWireframe(const Winding &winding)
-{
-    glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
-    glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints));
+inline void Winding_DrawWireframe( const Winding& winding ){
+       glVertexPointer( 3, GL_FLOAT, sizeof( WindingVertex ), &winding.points.data()->vertex );
+       glDrawArrays( GL_LINE_LOOP, 0, GLsizei( winding.numpoints ) );
 }
 
-inline void Winding_Draw(const Winding &winding, const Vector3 &normal, RenderStateFlags state)
-{
-    glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
-
-    if ((state & RENDER_BUMP) != 0) {
-        Vector3 normals[c_brush_maxFaces];
-        typedef Vector3 *Vector3Iter;
-        for (Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i) {
-            *i = normal;
-        }
-        if (GlobalShaderCache().useShaderLanguage()) {
-            glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
-            glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(WindingVertex),
-                                     &winding.points.data()->texcoord);
-            glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(WindingVertex),
-                                     &winding.points.data()->tangent);
-            glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(WindingVertex),
-                                     &winding.points.data()->bitangent);
-        } else {
-            glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(Vector3), normals);
-            glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord);
-            glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent);
-            glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent);
-        }
-    } else {
-        if (state & RENDER_LIGHTING) {
-            Vector3 normals[c_brush_maxFaces];
-            typedef Vector3 *Vector3Iter;
-            for (Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i) {
-                *i = normal;
-            }
-            glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
-        }
-
-        if (state & RENDER_TEXTURE) {
-            glTexCoordPointer(2, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->texcoord);
-        }
-    }
+inline void Winding_Draw( const Winding& winding, const Vector3& normal, RenderStateFlags state ){
+       glVertexPointer( 3, GL_FLOAT, sizeof( WindingVertex ), &winding.points.data()->vertex );
+
+       if ( ( state & RENDER_BUMP ) != 0 ) {
+               Vector3 normals[c_brush_maxFaces];
+               typedef Vector3* Vector3Iter;
+               for ( Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i )
+               {
+                       *i = normal;
+               }
+               if ( GlobalShaderCache().useShaderLanguage() ) {
+                       glNormalPointer( GL_FLOAT, sizeof( Vector3 ), normals );
+                       glVertexAttribPointerARB( c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->texcoord );
+                       glVertexAttribPointerARB( c_attr_Tangent, 3, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->tangent );
+                       glVertexAttribPointerARB( c_attr_Binormal, 3, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->bitangent );
+               }
+               else
+               {
+                       glVertexAttribPointerARB( 11, 3, GL_FLOAT, 0, sizeof( Vector3 ), normals );
+                       glVertexAttribPointerARB( 8, 2, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->texcoord );
+                       glVertexAttribPointerARB( 9, 3, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->tangent );
+                       glVertexAttribPointerARB( 10, 3, GL_FLOAT, 0, sizeof( WindingVertex ), &winding.points.data()->bitangent );
+               }
+       }
+       else
+       {
+               if ( state & RENDER_LIGHTING ) {
+                       Vector3 normals[c_brush_maxFaces];
+                       typedef Vector3* Vector3Iter;
+                       for ( Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i )
+                       {
+                               *i = normal;
+                       }
+                       glNormalPointer( GL_FLOAT, sizeof( Vector3 ), normals );
+               }
+
+               if ( state & RENDER_TEXTURE ) {
+                       glTexCoordPointer( 2, GL_FLOAT, sizeof( WindingVertex ), &winding.points.data()->texcoord );
+               }
+       }
 #if 0
-                                                                                                                            if ( state & RENDER_FILL ) {
+       if ( state & RENDER_FILL ) {
                glDrawArrays( GL_TRIANGLE_FAN, 0, GLsizei( winding.numpoints ) );
        }
        else
@@ -163,11 +161,11 @@ inline void Winding_Draw(const Winding &winding, const Vector3 &normal, RenderSt
                glDrawArrays( GL_LINE_LOOP, 0, GLsizei( winding.numpoints ) );
        }
 #else
-    glDrawArrays(GL_POLYGON, 0, GLsizei(winding.numpoints));
+       glDrawArrays( GL_POLYGON, 0, GLsizei( winding.numpoints ) );
 #endif
 
 #if 0
-                                                                                                                            const Winding& winding = winding;
+       const Winding& winding = winding;
 
        if ( state & RENDER_FILL ) {
                glBegin( GL_POLYGON );
@@ -197,1285 +195,1180 @@ inline void Winding_Draw(const Winding &winding, const Vector3 &normal, RenderSt
 
 typedef DoubleVector3 PlanePoints[3];
 
-inline bool planepts_equal(const PlanePoints planepts, const PlanePoints other)
-{
-    return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2];
+inline bool planepts_equal( const PlanePoints planepts, const PlanePoints other ){
+       return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2];
 }
 
-inline void planepts_assign(PlanePoints planepts, const PlanePoints other)
-{
-    planepts[0] = other[0];
-    planepts[1] = other[1];
-    planepts[2] = other[2];
+inline void planepts_assign( PlanePoints planepts, const PlanePoints other ){
+       planepts[0] = other[0];
+       planepts[1] = other[1];
+       planepts[2] = other[2];
 }
 
-inline void planepts_quantise(PlanePoints planepts, double snap)
-{
-    vector3_snap(planepts[0], snap);
-    vector3_snap(planepts[1], snap);
-    vector3_snap(planepts[2], snap);
+inline void planepts_quantise( PlanePoints planepts, double snap ){
+       vector3_snap( planepts[0], snap );
+       vector3_snap( planepts[1], snap );
+       vector3_snap( planepts[2], snap );
 }
 
-inline float vector3_max_component(const Vector3 &vec3)
-{
-    return std::max(fabsf(vec3[0]), std::max(fabsf(vec3[1]), fabsf(vec3[2])));
+inline float vector3_max_component( const Vector3& vec3 ){
+       return std::max( fabsf( vec3[0] ), std::max( fabsf( vec3[1] ), fabsf( vec3[2] ) ) );
 }
 
-inline void edge_snap(Vector3 &edge, double snap)
-{
-    float scale = static_cast<float>( ceil(fabs(snap / vector3_max_component(edge))));
-    if (scale > 0.0f) {
-        vector3_scale(edge, scale);
-    }
-    vector3_snap(edge, snap);
+inline void edge_snap( Vector3& edge, double snap ){
+       float scale = static_cast<float>( ceil( fabs( snap / vector3_max_component( edge ) ) ) );
+       if ( scale > 0.0f ) {
+               vector3_scale( edge, scale );
+       }
+       vector3_snap( edge, snap );
 }
 
-inline void planepts_snap(PlanePoints planepts, double snap)
-{
-    Vector3 edge01(vector3_subtracted(planepts[1], planepts[0]));
-    Vector3 edge12(vector3_subtracted(planepts[2], planepts[1]));
-    Vector3 edge20(vector3_subtracted(planepts[0], planepts[2]));
-
-    double length_squared_01 = vector3_dot(edge01, edge01);
-    double length_squared_12 = vector3_dot(edge12, edge12);
-    double length_squared_20 = vector3_dot(edge20, edge20);
-
-    vector3_snap(planepts[0], snap);
-
-    if (length_squared_01 < length_squared_12) {
-        if (length_squared_12 < length_squared_20) {
-            edge_snap(edge01, snap);
-            edge_snap(edge12, snap);
-            planepts[1] = vector3_added(planepts[0], edge01);
-            planepts[2] = vector3_added(planepts[1], edge12);
-        } else {
-            edge_snap(edge20, snap);
-            edge_snap(edge01, snap);
-            planepts[1] = vector3_added(planepts[0], edge20);
-            planepts[2] = vector3_added(planepts[1], edge01);
-        }
-    } else {
-        if (length_squared_01 < length_squared_20) {
-            edge_snap(edge01, snap);
-            edge_snap(edge12, snap);
-            planepts[1] = vector3_added(planepts[0], edge01);
-            planepts[2] = vector3_added(planepts[1], edge12);
-        } else {
-            edge_snap(edge12, snap);
-            edge_snap(edge20, snap);
-            planepts[1] = vector3_added(planepts[0], edge12);
-            planepts[2] = vector3_added(planepts[1], edge20);
-        }
-    }
-}
-
-inline PointVertex pointvertex_for_planept(const DoubleVector3 &point, const Colour4b &colour)
-{
-    return PointVertex(
-            Vertex3f(
-                    static_cast<float>( point.x()),
-                    static_cast<float>( point.y()),
-                    static_cast<float>( point.z())
-            ),
-            colour
-    );
+inline void planepts_snap( PlanePoints planepts, double snap ){
+       Vector3 edge01( vector3_subtracted( planepts[1], planepts[0] ) );
+       Vector3 edge12( vector3_subtracted( planepts[2], planepts[1] ) );
+       Vector3 edge20( vector3_subtracted( planepts[0], planepts[2] ) );
+
+       double length_squared_01 = vector3_dot( edge01, edge01 );
+       double length_squared_12 = vector3_dot( edge12, edge12 );
+       double length_squared_20 = vector3_dot( edge20, edge20 );
+
+       vector3_snap( planepts[0], snap );
+
+       if ( length_squared_01 < length_squared_12 ) {
+               if ( length_squared_12 < length_squared_20 ) {
+                       edge_snap( edge01, snap );
+                       edge_snap( edge12, snap );
+                       planepts[1] = vector3_added( planepts[0], edge01 );
+                       planepts[2] = vector3_added( planepts[1], edge12 );
+               }
+               else
+               {
+                       edge_snap( edge20, snap );
+                       edge_snap( edge01, snap );
+                       planepts[1] = vector3_added( planepts[0], edge20 );
+                       planepts[2] = vector3_added( planepts[1], edge01 );
+               }
+       }
+       else
+       {
+               if ( length_squared_01 < length_squared_20 ) {
+                       edge_snap( edge01, snap );
+                       edge_snap( edge12, snap );
+                       planepts[1] = vector3_added( planepts[0], edge01 );
+                       planepts[2] = vector3_added( planepts[1], edge12 );
+               }
+               else
+               {
+                       edge_snap( edge12, snap );
+                       edge_snap( edge20, snap );
+                       planepts[1] = vector3_added( planepts[0], edge12 );
+                       planepts[2] = vector3_added( planepts[1], edge20 );
+               }
+       }
 }
 
-inline PointVertex pointvertex_for_windingpoint(const Vector3 &point, const Colour4b &colour)
-{
-    return PointVertex(
-            vertex3f_for_vector3(point),
-            colour
-    );
+inline PointVertex pointvertex_for_planept( const DoubleVector3& point, const Colour4b& colour ){
+       return PointVertex(
+                          Vertex3f(
+                                  static_cast<float>( point.x() ),
+                                  static_cast<float>( point.y() ),
+                                  static_cast<float>( point.z() )
+                                  ),
+                          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]);
-}
-
-inline void brush_check_shader(const char *name)
-{
-    if (!shader_valid(name)) {
-        globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n";
-    }
+inline PointVertex pointvertex_for_windingpoint( const Vector3& point, const Colour4b& colour ){
+       return PointVertex(
+                          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] );
+}
+
+inline void brush_check_shader( const char* name ){
+       if ( !shader_valid( name ) ) {
+               globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n";
+       }
 }
 
-class FaceShaderObserver {
+class FaceShaderObserver
+{
 public:
-    virtual void realiseShader() = 0;
+virtual void realiseShader() = 0;
 
-    virtual void unrealiseShader() = 0;
+virtual void unrealiseShader() = 0;
 };
 
 typedef ReferencePair<FaceShaderObserver> FaceShaderObserverPair;
 
 
-class ContentsFlagsValue {
+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)
-{
-    bool detail = bitfield_enabled(flags.m_contentFlags, BRUSH_DETAIL_MASK);
-    flags = other;
-    if (detail) {
-        flags.m_contentFlags = bitfield_enable(flags.m_contentFlags, BRUSH_DETAIL_MASK);
-    } else {
-        flags.m_contentFlags = bitfield_disable(flags.m_contentFlags, BRUSH_DETAIL_MASK);
-    }
+inline void ContentsFlagsValue_assignMasked( ContentsFlagsValue& flags, const ContentsFlagsValue& other ){
+       bool detail = bitfield_enabled( flags.m_contentFlags, BRUSH_DETAIL_MASK );
+       flags = other;
+       if ( detail ) {
+               flags.m_contentFlags = bitfield_enable( flags.m_contentFlags, BRUSH_DETAIL_MASK );
+       }
+       else
+       {
+               flags.m_contentFlags = bitfield_disable( flags.m_contentFlags, BRUSH_DETAIL_MASK );
+       }
 }
 
 
-class FaceShader : public ModuleObserver {
+class FaceShader : public ModuleObserver
+{
+public:
+class SavedState
+{
 public:
-    class SavedState {
-    public:
-        CopiedString m_shader;
-        ContentsFlagsValue 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.m_flags = m_flags;
-        }
-    };
-
-    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();
-    }
+CopiedString m_shader;
+ContentsFlagsValue 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 );
+}
+};
+
+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();
+}
 
 // copy-construction not supported
-    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([](FaceShaderObserver &observer) {
-            observer.realiseShader();
-        });
-    }
-
-    void unrealise()
-    {
-        ASSERT_MESSAGE(m_realised, "FaceTexdef::unrealise: already unrealised");
-        m_observers.forEach([](FaceShaderObserver &observer) {
-            observer.unrealiseShader();
-        });
-        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) {
-            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;
-    }
+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([](FaceShaderObserver &observer) {
+               observer.realiseShader();
+       });
+}
+
+void unrealise(){
+       ASSERT_MESSAGE( m_realised, "FaceTexdef::unrealise: already unrealised" );
+       m_observers.forEach([](FaceShaderObserver &observer) {
+               observer.unrealiseShader();
+       });
+       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 ) {
+               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;
+}
 };
 
 
-class FaceTexdef : public FaceShaderObserver {
+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;
-
-        SavedState(const FaceTexdef &faceTexdef)
-        {
-            m_projection = faceTexdef.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;
-
-    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);
-    }
-
-    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) {
-            addScale();
-        }
-    }
-
-    void unrealiseShader()
-    {
-        if (m_projectionInitialised && m_scaleApplied) {
-            removeScale();
-        }
-    }
-
-    void setTexdef(const TextureProjection &projection)
-    {
-        removeScale();
-        Texdef_Assign(m_projection, projection);
-        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);
-        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 fit(const Vector3 &normal, const Winding &winding, float s_repeat, float t_repeat)
-    {
-        Texdef_FitTexture(m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat);
-    }
-
-    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();
-    }
-
-    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);
-    }
-
-    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());
-    }
+class SavedState
+{
+public:
+TextureProjection m_projection;
+
+SavedState( const FaceTexdef& faceTexdef ){
+       m_projection = faceTexdef.m_projection;
+}
+
+void exportState( FaceTexdef& faceTexdef ) const {
+       Texdef_Assign( faceTexdef.m_projection, m_projection );
+}
 };
 
-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] << " )";
+FaceShader& m_shader;
+TextureProjection m_projection;
+bool m_projectionInitialised;
+bool m_scaleApplied;
+
+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 );
+}
 
-inline Plane3 Plane3_applyTranslation(const Plane3 &plane, const Vector3 &translation)
-{
-    Plane3 tmp(plane3_translated(Plane3(plane.normal(), -plane.dist()), translation));
-    return Plane3(tmp.normal(), -tmp.dist());
+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 ) {
+               addScale();
+       }
+}
+
+void unrealiseShader(){
+       if ( m_projectionInitialised && m_scaleApplied ) {
+               removeScale();
+       }
+}
+
+void setTexdef( const TextureProjection& projection ){
+       removeScale();
+       Texdef_Assign( m_projection, projection );
+       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 );
+       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 fit( const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat ){
+       Texdef_FitTexture( m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat );
+}
+
+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();
 }
 
-inline Plane3 Plane3_applyTransform(const Plane3 &plane, const Matrix4 &matrix)
+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 );
+}
+
+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() );
+}
+};
+
+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] << " )";
+}
+
+
+inline Plane3 Plane3_applyTranslation( const Plane3& plane, const Vector3& translation ){
+       Plane3 tmp( plane3_translated( Plane3( plane.normal(), -plane.dist() ), translation ) );
+       return Plane3( tmp.normal(), -tmp.dist() );
+}
+
+inline Plane3 Plane3_applyTransform( const Plane3& plane, const Matrix4& matrix ){
+       Plane3 tmp( plane3_transformed( Plane3( plane.normal(), -plane.dist() ), matrix ) );
+       return Plane3( tmp.normal(), -tmp.dist() );
+}
+
+class FacePlane
 {
-    Plane3 tmp(plane3_transformed(Plane3(plane.normal(), -plane.dist()), matrix));
-    return Plane3(tmp.normal(), -tmp.dist());
+PlanePoints m_planepts;
+Plane3 m_planeCached;
+Plane3 m_plane;
+public:
+Vector3 m_funcStaticOrigin;
+
+static EBrushType m_type;
+
+static bool isDoom3Plane(){
+       return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4;
 }
 
-class FacePlane {
-    PlanePoints m_planepts;
-    Plane3 m_planeCached;
-    Plane3 m_plane;
+class SavedState
+{
 public:
-    Vector3 m_funcStaticOrigin;
-
-    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;
-            } 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();
-        }
-    }
-
-    void MakePlane()
-    {
-        if (!isDoom3Plane()) {
+PlanePoints m_planepts;
+Plane3 m_plane;
+
+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();
+       }
+}
+
+void MakePlane(){
+       if ( !isDoom3Plane() ) {
 #if 0
-                                                                                                                                    if ( check_plane_is_integer( m_planepts ) ) {
+               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()) {
+               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() );
+               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]);
+               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 ( mirror ) {
+                       reverse();
+               }
 
 #if 0
-                                                                                                                                    if ( check_plane_is_integer( planePoints() ) ) {
+               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 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();
-        } 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(p2, p1, p0);
-            updateSource();
-        }
-    }
+               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 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();
+       }
+       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( p2, p1, p0 );
+               updateSource();
+       }
+}
 };
 
-inline void Winding_testSelect(Winding &winding, SelectionTest &test, SelectionIntersection &best)
-{
-    test.TestPolygon(VertexPointer(reinterpret_cast<VertexPointer::pointer>( &winding.points.data()->vertex ),
-                                   sizeof(WindingVertex)), winding.numpoints, best);
+inline void Winding_testSelect( Winding& winding, SelectionTest& test, SelectionIntersection& best ){
+       test.TestPolygon( VertexPointer( reinterpret_cast<VertexPointer::pointer>( &winding.points.data()->vertex ), sizeof( WindingVertex ) ), winding.numpoints, best );
 }
 
 const double GRID_MIN = 0.125;
 
-inline double quantiseInteger(double f)
-{
-    return float_to_integer(f);
+inline double quantiseInteger( double f ){
+       return float_to_integer( f );
 }
 
-inline double quantiseFloating(double f)
-{
-    return float_snapped(f, 1.f / (1 << 16));
+inline double quantiseFloating( double f ){
+       return float_snapped( f, 1.f / ( 1 << 16 ) );
 }
 
-typedef double ( *QuantiseFunc )(double f);
+typedef double ( *QuantiseFunc )( double f );
 
 class Face;
 
-class FaceFilter {
+class FaceFilter
+{
 public:
-    virtual bool filter(const Face &face) const = 0;
+virtual bool filter( const Face& face ) const = 0;
 };
 
-bool face_filtered(Face &face);
+bool face_filtered( Face& face );
 
-void add_face_filter(FaceFilter &filter, int mask, bool invert = false);
+void add_face_filter( FaceFilter& filter, int mask, bool invert = false );
 
-void Brush_addTextureChangedCallback(const SignalHandler &callback);
+void Brush_addTextureChangedCallback( const SignalHandler& callback );
 
 void Brush_textureChanged();
 
 
 extern bool g_brush_texturelock_enabled;
 
-class FaceObserver {
+class FaceObserver
+{
 public:
-    virtual void planeChanged() = 0;
+virtual void planeChanged() = 0;
 
-    virtual void connectivityChanged() = 0;
+virtual void connectivityChanged() = 0;
 
-    virtual void shaderChanged() = 0;
+virtual void shaderChanged() = 0;
 
-    virtual void evaluateTransform() = 0;
+virtual void evaluateTransform() = 0;
 };
 
 class Face :
-        public OpenGLRenderable,
-        public Filterable,
-        public Undoable,
-        public FaceShaderObserver {
-    std::size_t m_refcount;
-
-    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())
-        {
-        }
-
-        void exportState(Face &face) const
-        {
-            m_planeState.exportState(face.getPlane());
-            m_shaderState.exportState(face.getShader());
-            m_texdefState.exportState(face.getTexdef());
-        }
-
-        void release()
-        {
-            delete this;
-        }
-    };
+       public OpenGLRenderable,
+       public Filterable,
+       public Undoable,
+       public FaceShaderObserver
+{
+std::size_t m_refcount;
+
+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() ){
+}
+
+void exportState( Face& face ) const {
+       m_planeState.exportState( face.getPlane() );
+       m_shaderState.exportState( face.getShader() );
+       m_texdefState.exportState( face.getTexdef() );
+}
+
+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;
-    bool m_filtered;
+Winding m_winding;
+Vector3 m_centroid;
+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
-    ) :
-            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());
-        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);
-        }
-    }
+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();
+}
 
-// undoable
-    UndoMemento *exportState() const
-    {
-        return new SavedState(*this);
-    }
-
-    void importState(const UndoMemento *data)
-    {
-        undoSave();
-
-        static_cast<const SavedState *>( data )->exportState(*this);
-
-        planeChanged();
-        m_observer->connectivityChanged();
-        texdefChanged();
-        m_observer->shaderChanged();
-        updateFiltered();
-    }
-
-    void IncRef()
-    {
-        ++m_refcount;
-    }
-
-    void DecRef()
-    {
-        if (--m_refcount == 0) {
-            delete this;
-        }
-    }
-
-    void flipWinding()
-    {
-        m_plane.reverse();
-        planeChanged();
-    }
-
-    bool intersectVolume(const VolumeTest &volume, const Matrix4 &localToWorld) const
-    {
-        return volume.TestPlane(Plane3(plane3().normal(), -plane3().dist()), localToWorld);
-    }
-
-    void render(Renderer &renderer, const Matrix4 &localToWorld) const
-    {
-        renderer.SetState(m_shader.state(), Renderer::eFullMaterials);
-        renderer.addRenderable(*this, localToWorld);
-    }
-
-    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);
-        }
-
-        m_planeTransformed.transform(matrix, mirror);
+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();
+}
 
-#if 0
-        ASSERT_MESSAGE( projectionaxis_for_normal( normal ) == projectionaxis_for_normal( plane3().normal() ), "bleh" );
-#endif
-        m_observer->planeChanged();
+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() );
+       planeChanged();
+       updateFiltered();
+}
 
-        if (g_brush_texturelock_enabled) {
-            Brush_textureChanged();
-        }
-    }
+~Face(){
+       m_shader.detach( *this );
+}
 
-    void assign_planepts(const PlanePoints planepts)
-    {
-        m_planeTransformed.copy(planepts[0], planepts[1], planepts[2]);
-        m_observer->planeChanged();
-    }
+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<const SavedState*>( data )->exportState( *this );
+
+       planeChanged();
+       m_observer->connectivityChanged();
+       texdefChanged();
+       m_observer->shaderChanged();
+       updateFiltered();
+}
+
+void IncRef(){
+       ++m_refcount;
+}
+
+void DecRef(){
+       if ( --m_refcount == 0 ) {
+               delete this;
+       }
+}
+
+void flipWinding(){
+       m_plane.reverse();
+       planeChanged();
+}
+
+bool intersectVolume( const VolumeTest& volume, const Matrix4& localToWorld ) const {
+       return volume.TestPlane( Plane3( plane3().normal(), -plane3().dist() ), localToWorld );
+}
+
+void render( Renderer& renderer, const Matrix4& localToWorld ) const {
+       renderer.SetState( m_shader.state(), Renderer::eFullMaterials );
+       renderer.addRenderable( *this, localToWorld );
+}
+
+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 );
+       }
+
+       m_planeTransformed.transform( matrix, mirror );
+
+#if 0
+       ASSERT_MESSAGE( projectionaxis_for_normal( normal ) == projectionaxis_for_normal( plane3().normal() ), "bleh" );
+#endif
+       m_observer->planeChanged();
+
+       if ( g_brush_texturelock_enabled ) {
+               Brush_textureChanged();
+       }
+}
+
+void assign_planepts( const PlanePoints planepts ){
+       m_planeTransformed.copy( planepts[0], planepts[1], planepts[2] );
+       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)
-    {
-        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()) {
+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 ){
+       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" );
+               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())) {
-                globalErrorStream() << "WARNING: invalid plane after snap to grid\n";
-            }
-        }
-    }
-
-    void testSelect(SelectionTest &test, SelectionIntersection &best)
-    {
-        Winding_testSelect(m_winding, test, best);
-    }
-
-    void testSelect_centroid(SelectionTest &test, SelectionIntersection &best)
-    {
-        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)
-    {
-        undoSave();
-        m_texdef.setTexdef(projection);
-        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 FitTexture(float s_repeat, float t_repeat)
-    {
-        undoSave();
-        m_texdef.fit(m_plane.plane3().normal(), m_winding, s_repeat, t_repeat);
-        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;
-    }
-
-    const Plane3 &plane3() const
-    {
-        m_observer->evaluateTransform();
-        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;
-    }
+               SceneChangeNotify();
+               if ( !plane3_valid( m_plane.plane3() ) ) {
+                       globalErrorStream() << "WARNING: invalid plane after snap to grid\n";
+               }
+       }
+}
+
+void testSelect( SelectionTest& test, SelectionIntersection& best ){
+       Winding_testSelect( m_winding, test, best );
+}
+
+void testSelect_centroid( SelectionTest& test, SelectionIntersection& best ){
+       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 ){
+       undoSave();
+       m_texdef.setTexdef( projection );
+       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 FitTexture( float s_repeat, float t_repeat ){
+       undoSave();
+       m_texdef.fit( m_plane.plane3().normal(), m_winding, s_repeat, t_repeat );
+       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;
+}
+
+const Plane3& plane3() const {
+       m_observer->evaluateTransform();
+       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;
+}
 };
 
 
-class FaceVertexId {
-    std::size_t m_face;
-    std::size_t m_vertex;
+class FaceVertexId
+{
+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)
-    {
-    }
-
-    std::size_t getFace() const
-    {
-        return m_face;
-    }
-
-    std::size_t getVertex() const
-    {
-        return m_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;
+}
 };
 
 typedef std::size_t faceIndex_t;
 
-struct EdgeRenderIndices {
-    RenderIndex first;
-    RenderIndex second;
+struct EdgeRenderIndices
+{
+       RenderIndex first;
+       RenderIndex second;
 
-    EdgeRenderIndices()
-            : first(0), second(0)
-    {
-    }
+       EdgeRenderIndices()
+               : first( 0 ), second( 0 ){
+       }
 
-    EdgeRenderIndices(const RenderIndex _first, const RenderIndex _second)
-            : first(_first), second(_second)
-    {
-    }
+       EdgeRenderIndices( const RenderIndex _first, const RenderIndex _second )
+               : first( _first ), second( _second ){
+       }
 };
 
-struct EdgeFaces {
-    faceIndex_t first;
-    faceIndex_t second;
+struct EdgeFaces
+{
+       faceIndex_t first;
+       faceIndex_t second;
 
-    EdgeFaces()
-            : first(c_brush_maxFaces), second(c_brush_maxFaces)
-    {
-    }
+       EdgeFaces()
+               : first( c_brush_maxFaces ), second( c_brush_maxFaces ){
+       }
 
-    EdgeFaces(const faceIndex_t _first, const faceIndex_t _second)
-            : first(_first), second(_second)
-    {
-    }
+       EdgeFaces( const faceIndex_t _first, const faceIndex_t _second )
+               : first( _first ), second( _second ){
+       }
 };
 
-class RenderableWireframe : public OpenGLRenderable {
+class RenderableWireframe : public OpenGLRenderable
+{
 public:
-    void render(RenderStateFlags state) const
-    {
+void render( RenderStateFlags state ) const {
 #if 1
-        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices->colour);
-        glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices->vertex);
-        glDrawElements(GL_LINES, GLsizei(m_size << 1), RenderIndexTypeID, m_faceVertex.data());
+       glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices->colour );
+       glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices->vertex );
+       glDrawElements( GL_LINES, GLsizei( m_size << 1 ), RenderIndexTypeID, m_faceVertex.data() );
 #else
-                                                                                                                                glBegin( GL_LINES );
+       glBegin( GL_LINES );
        for ( std::size_t i = 0; i < m_size; ++i )
        {
                glVertex3fv( &m_vertices[m_faceVertex[i].first].vertex.x );
@@ -1483,2581 +1376,2457 @@ public:
        }
        glEnd();
 #endif
-    }
+}
 
-    Array<EdgeRenderIndices> m_faceVertex;
-    std::size_t m_size;
-    const PointVertex *m_vertices;
+Array<EdgeRenderIndices> m_faceVertex;
+std::size_t m_size;
+const PointVertex* m_vertices;
 };
 
 class Brush;
 
-typedef std::vector<Brush *> brush_vector_t;
+typedef std::vector<Brush*> brush_vector_t;
 
-class BrushFilter {
+class BrushFilter
+{
 public:
-    virtual bool filter(const Brush &brush) const = 0;
+virtual bool filter( const Brush& brush ) const = 0;
 };
 
-bool brush_filtered(Brush &brush);
+bool brush_filtered( Brush& brush );
 
-void add_brush_filter(BrushFilter &filter, int mask, bool invert = false);
+void add_brush_filter( BrushFilter& filter, int mask, bool invert = false );
 
 
 /// \brief Returns true if 'self' takes priority when building brush b-rep.
-inline bool plane3_inside(const Plane3 &self, const Plane3 &other, bool selfIsLater)
-{
-    if (vector3_equal_epsilon(self.normal(), other.normal(), 0.001)) {
-        // same plane? prefer the one with smaller index
-        if (self.dist() == other.dist()) {
-            return selfIsLater;
-        }
-        return self.dist() < other.dist();
-    }
-    return true;
+inline bool plane3_inside( const Plane3& self, const Plane3& other, bool selfIsLater ){
+       if ( vector3_equal_epsilon( self.normal(), other.normal(), 0.001 ) ) {
+               // same plane? prefer the one with smaller index
+               if ( self.dist() == other.dist() ) {
+                       return selfIsLater;
+               }
+               return self.dist() < other.dist();
+       }
+       return true;
 }
 
 typedef SmartPointer<Face> FaceSmartPointer;
 typedef std::vector<FaceSmartPointer> Faces;
 
 /// \brief Returns the unique-id of the edge adjacent to \p faceVertex in the edge-pair for the set of \p faces.
-inline FaceVertexId next_edge(const Faces &faces, FaceVertexId faceVertex)
-{
-    std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent;
-    std::size_t adjacent_vertex = Winding_FindAdjacent(faces[adjacent_face]->getWinding(), faceVertex.getFace());
+inline FaceVertexId next_edge( const Faces& faces, FaceVertexId faceVertex ){
+       std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent;
+       std::size_t adjacent_vertex = Winding_FindAdjacent( faces[adjacent_face]->getWinding(), faceVertex.getFace() );
 
-    ASSERT_MESSAGE(adjacent_vertex != c_brush_maxFaces, "connectivity data invalid");
-    if (adjacent_vertex == c_brush_maxFaces) {
-        return faceVertex;
-    }
+       ASSERT_MESSAGE( adjacent_vertex != c_brush_maxFaces, "connectivity data invalid" );
+       if ( adjacent_vertex == c_brush_maxFaces ) {
+               return faceVertex;
+       }
 
-    return FaceVertexId(adjacent_face, adjacent_vertex);
+       return FaceVertexId( adjacent_face, adjacent_vertex );
 }
 
 /// \brief Returns the unique-id of the vertex adjacent to \p faceVertex in the vertex-ring for the set of \p faces.
-inline FaceVertexId next_vertex(const Faces &faces, FaceVertexId faceVertex)
-{
-    FaceVertexId nextEdge = next_edge(faces, faceVertex);
-    return FaceVertexId(nextEdge.getFace(),
-                        Winding_next(faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex()));
+inline FaceVertexId next_vertex( const Faces& faces, FaceVertexId faceVertex ){
+       FaceVertexId nextEdge = next_edge( faces, faceVertex );
+       return FaceVertexId( nextEdge.getFace(), Winding_next( faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex() ) );
 }
 
-class SelectableEdge {
-    Vector3 getEdge() const
-    {
-        const Winding &winding = getFace().getWinding();
-        return vector3_mid(winding[m_faceVertex.getVertex()].vertex,
-                           winding[Winding_next(winding, m_faceVertex.getVertex())].vertex);
-    }
+class SelectableEdge
+{
+Vector3 getEdge() const {
+       const Winding& winding = getFace().getWinding();
+       return vector3_mid( winding[m_faceVertex.getVertex()].vertex, winding[Winding_next( winding, m_faceVertex.getVertex() )].vertex );
+}
 
 public:
-    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;
-    }
-
-    Face &getFace() const
-    {
-        return *m_faces[m_faceVertex.getFace()];
-    }
-
-    void testSelect(SelectionTest &test, SelectionIntersection &best)
-    {
-        test.TestPoint(getEdge(), best);
-    }
+Faces& m_faces;
+FaceVertexId m_faceVertex;
+
+SelectableEdge( Faces& faces, FaceVertexId faceVertex )
+       : m_faces( faces ), m_faceVertex( faceVertex ){
+}