Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/configure
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/configure (revision 9551)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/configure (revision 9551)
@@ -0,0 +1,1 @@
+cmake . -DCMAKE_BUILD_TYPE=Release $@
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Export
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Export (revision 9494)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Export (revision 9494)
@@ -0,0 +1,47 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_EXPORT_
+#define OSGVOLUME_EXPORT_ 1
+
+#if defined(_MSC_VER)
+    #pragma warning( disable : 4244 )
+    #pragma warning( disable : 4251 )
+    #pragma warning( disable : 4267 )
+    #pragma warning( disable : 4275 )
+    #pragma warning( disable : 4290 )
+    #pragma warning( disable : 4786 )
+    #pragma warning( disable : 4305 )
+    #pragma warning( disable : 4996 )
+#endif
+
+#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__)
+    #  if defined( OSG_LIBRARY_STATIC )
+    #    define OSGVOLUME_EXPORT
+    #  elif defined( OSGVOLUME_LIBRARY )
+    #    define OSGVOLUME_EXPORT   __declspec(dllexport)
+    #  else
+    #    define OSGVOLUME_EXPORT   __declspec(dllimport)
+    #  endif
+#else
+    #  define OSGVOLUME_EXPORT
+#endif  
+
+/**
+
+\namespace osgVolume
+
+The osgVolume library is a NodeKit that extends the core scene graph to support volume rendering.
+*/
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Locator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Locator (revision 9494)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Locator (revision 9494)
@@ -0,0 +1,73 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_LOCATOR
+#define OSGVOLUME_LOCATOR 1
+
+#include <osgVolume/Export>
+
+#include <osg/Object>
+#include <osg/Matrixd>
+
+namespace osgVolume {
+
+class OSGVOLUME_EXPORT Locator : public osg::Object
+{
+    public:
+        
+        Locator() {}
+
+        Locator(const osg::Matrixd& transform) { setTransform(transform); }
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Locator(const Locator& locator,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY):
+            osg::Object(locator, copyop),
+            _transform(locator._transform) {}
+        
+        META_Object(osgVolume, Locator);
+
+        /** Set the transformation from local coordinates to model coordinates.*/
+        void setTransform(const osg::Matrixd& transform) { _transform = transform; _inverse.invert(_transform); }
+
+        /** Set the transformation from local coordinates to model coordinates.*/
+        const osg::Matrixd& getTransform() const { return _transform; }
+
+        /** Set the extents of the local coords.*/
+        void setTransformAsExtents(double minX, double minY, double maxX, double maxY, double minZ, double maxZ);
+
+
+        virtual bool convertLocalToModel(const osg::Vec3d& /*local*/, osg::Vec3d& /*world*/) const;
+
+        virtual bool convertModelToLocal(const osg::Vec3d& /*world*/, osg::Vec3d& /*local*/) const;
+
+        static bool convertLocalCoordBetween(const Locator& source, const osg::Vec3d& sourceNDC, 
+                                             const Locator& destination, osg::Vec3d& destinationNDC)
+        {
+            osg::Vec3d model;
+            if (!source.convertLocalToModel(sourceNDC, model)) return false;
+            if (!destination.convertModelToLocal(model, destinationNDC)) return false;
+            return true;
+        }
+        
+        bool computeLocalBounds(osg::Vec3d& bottomLeft, osg::Vec3d& topRight) const;
+        bool computeLocalBounds(Locator& source, osg::Vec3d& bottomLeft, osg::Vec3d& topRight) const;
+
+    protected:
+    
+        osg::Matrixd _transform;
+        osg::Matrixd _inverse;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Property
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Property (revision 9650)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Property (revision 9650)
@@ -0,0 +1,393 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_PROPERTY
+#define OSGVOLUME_PROPERTY 1
+
+#include <osg/TransferFunction>
+#include <osg/Uniform>
+#include <osg/AlphaFunc>
+
+#include <osgGA/GUIEventHandler>
+
+#include <osgVolume/Export>
+
+namespace osgVolume {
+
+// forward decarle
+class Property;
+class CompositeProperty;
+class SwitchProperty;
+class TransferFunctionProperty;
+class ScalarProperty;
+class IsoSurfaceProperty;
+class MaximumIntensityProjectionProperty;
+class LightingProperty;
+class AlphaFuncProperty;
+class SampleDensityProperty;
+class TransparencyProperty;
+
+class OSGVOLUME_EXPORT PropertyVisitor
+{
+    public:
+
+        PropertyVisitor(bool traverseOnlyActiveChildren=true);
+
+        virtual ~PropertyVisitor() {}
+
+        virtual void apply(Property&) {}
+        virtual void apply(CompositeProperty&);
+        virtual void apply(SwitchProperty&);
+        virtual void apply(TransferFunctionProperty&) {}
+        virtual void apply(ScalarProperty&) {}
+        virtual void apply(IsoSurfaceProperty&) {}
+        virtual void apply(AlphaFuncProperty&) {}
+        virtual void apply(MaximumIntensityProjectionProperty&) {}
+        virtual void apply(LightingProperty&) {}
+        virtual void apply(SampleDensityProperty&) {}
+        virtual void apply(TransparencyProperty&) {}
+
+        bool _traverseOnlyActiveChildren;
+
+};
+
+
+class OSGVOLUME_EXPORT Property : public osg::Object
+{
+    public:
+
+        Property();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Property(const Property&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, Property);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~Property();
+};
+
+class OSGVOLUME_EXPORT CompositeProperty : public Property
+{
+    public:
+
+        CompositeProperty();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        CompositeProperty(const CompositeProperty& compositeProperty,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, CompositeProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+        void clear();
+
+        typedef std::vector< osg::ref_ptr<Property> > Properties;
+
+        void setProperty(unsigned int i, Property* property) { if (i>=_properties.size()) _properties.resize(i+1); _properties[i] = property; }
+
+        Property* getProperty(unsigned int i) { return i<_properties.size() ? _properties[i].get() : 0; }
+
+        const Property* getProperty(unsigned int i) const { return i<_properties.size() ? _properties[i].get() : 0; }
+
+        void addProperty(Property* property) { _properties.push_back(property); }
+
+        void removeProperty(unsigned int i) { _properties.erase(_properties.begin()+i); }
+
+        unsigned int getNumProperties() const { return _properties.size(); }
+
+    protected:
+
+        virtual ~CompositeProperty() {}
+
+
+        Properties _properties;
+};
+
+
+class OSGVOLUME_EXPORT SwitchProperty : public CompositeProperty
+{
+    public:
+
+        SwitchProperty();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        SwitchProperty(const SwitchProperty& switchProperty,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, SwitchProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+        /** Set which child property is active.
+          * -1 disables all children.*/
+        void setActiveProperty(int i) { _activeProperty = i; }
+
+        /** Get the active property.*/
+        int getActiveProperty() const { return _activeProperty; }
+
+    protected:
+
+        virtual ~SwitchProperty() {}
+
+        int _activeProperty;
+};
+
+class OSGVOLUME_EXPORT TransferFunctionProperty : public Property
+{
+    public:
+
+        TransferFunctionProperty(osg::TransferFunction* tf = 0);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        TransferFunctionProperty(const TransferFunctionProperty& tfp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, TransferFunctionProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+        /** Set the transfer function.*/
+        void setTransferFunction(osg::TransferFunction* tf) { _tf = tf; }
+
+        /** Get the transfer function.*/
+        osg::TransferFunction* getTransferFunction() { return _tf.get(); }
+
+        /** Get the const transfer function.*/
+        const osg::TransferFunction* getTransferFunction() const { return _tf.get(); }
+
+    protected:
+
+        virtual ~TransferFunctionProperty() {}
+
+        osg::ref_ptr<osg::TransferFunction> _tf;
+};
+
+
+
+class OSGVOLUME_EXPORT ScalarProperty : public Property
+{
+    public:
+
+        ScalarProperty(const std::string& scaleName, float value);
+
+        ScalarProperty(const ScalarProperty& scalarProperty,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, ScalarProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+        /** Set the value.*/
+        virtual void setValue(float v) { _uniform->set(v); }
+
+        /** Get the value.*/
+        float getValue() const { float v; _uniform->get(v); return v; }
+
+        /** Get the underlying uniform.*/
+        osg::Uniform* getUniform() { return _uniform.get(); }
+
+        /** Get the underlying uniform.*/
+        const osg::Uniform* getUniform() const { return _uniform.get(); }
+
+    protected:
+
+        virtual ~ScalarProperty() {}
+
+        ScalarProperty();
+
+        osg::ref_ptr<osg::Uniform>  _uniform;
+};
+
+
+class OSGVOLUME_EXPORT IsoSurfaceProperty : public ScalarProperty
+{
+    public:
+
+        IsoSurfaceProperty(float value=1.0);
+
+        IsoSurfaceProperty(const IsoSurfaceProperty& isp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, IsoSurfaceProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~IsoSurfaceProperty() {}
+};
+
+class OSGVOLUME_EXPORT AlphaFuncProperty : public ScalarProperty
+{
+    public:
+
+        AlphaFuncProperty(float value=1.0);
+
+        AlphaFuncProperty(const AlphaFuncProperty& isp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, AlphaFuncProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+        virtual void setValue(float v);
+
+        osg::AlphaFunc* getAlphaFunc() { return _alphaFunc.get(); }
+
+        const osg::AlphaFunc* getAlphaFunc() const { return _alphaFunc.get(); }
+
+
+    protected:
+
+        virtual ~AlphaFuncProperty() {}
+
+        osg::ref_ptr<osg::AlphaFunc> _alphaFunc;
+};
+
+class OSGVOLUME_EXPORT MaximumIntensityProjectionProperty : public Property
+{
+    public:
+
+        MaximumIntensityProjectionProperty();
+
+        MaximumIntensityProjectionProperty(const MaximumIntensityProjectionProperty& mipp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, MaximumIntensityProjectionProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~MaximumIntensityProjectionProperty() {}
+};
+
+
+class OSGVOLUME_EXPORT LightingProperty : public Property
+{
+    public:
+
+        LightingProperty();
+
+        LightingProperty(const LightingProperty& mipp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, LightingProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~LightingProperty() {}
+};
+
+
+class OSGVOLUME_EXPORT SampleDensityProperty : public ScalarProperty
+{
+    public:
+
+        SampleDensityProperty(float value=1.0);
+
+        SampleDensityProperty(const SampleDensityProperty& isp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, SampleDensityProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~SampleDensityProperty() {}
+};
+
+class OSGVOLUME_EXPORT TransparencyProperty : public ScalarProperty
+{
+    public:
+
+        TransparencyProperty(float value=1.0);
+
+        TransparencyProperty(const TransparencyProperty& isp,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osgVolume, TransparencyProperty);
+
+        virtual void accept(PropertyVisitor& pv) { pv.apply(*this); }
+
+    protected:
+
+        virtual ~TransparencyProperty() {}
+};
+
+
+class OSGVOLUME_EXPORT CollectPropertiesVisitor : public osgVolume::PropertyVisitor
+{
+    public:
+
+        CollectPropertiesVisitor(bool traverseOnlyActiveChildren=true);
+
+        virtual void apply(Property&);
+        virtual void apply(TransferFunctionProperty&);
+        virtual void apply(ScalarProperty&);
+        virtual void apply(IsoSurfaceProperty& iso);
+        virtual void apply(AlphaFuncProperty& af);
+        virtual void apply(MaximumIntensityProjectionProperty& mip);
+        virtual void apply(LightingProperty& lp);
+        virtual void apply(SampleDensityProperty& sdp);
+        virtual void apply(TransparencyProperty& tp);
+
+        osg::ref_ptr<TransferFunctionProperty>              _tfProperty;
+        osg::ref_ptr<IsoSurfaceProperty>                    _isoProperty;
+        osg::ref_ptr<AlphaFuncProperty>                     _afProperty;
+        osg::ref_ptr<MaximumIntensityProjectionProperty>    _mipProperty;
+        osg::ref_ptr<LightingProperty>                      _lightingProperty;
+        osg::ref_ptr<SampleDensityProperty>                 _sampleDensityProperty;
+        osg::ref_ptr<TransparencyProperty>                  _transparencyProperty;
+
+};
+
+class OSGVOLUME_EXPORT PropertyAdjustmentCallback : public osgGA::GUIEventHandler, public osg::StateSet::Callback
+{
+    public:
+
+        PropertyAdjustmentCallback();
+
+        PropertyAdjustmentCallback(const PropertyAdjustmentCallback&,const osg::CopyOp&) {}
+
+        META_Object(osgVolume,PropertyAdjustmentCallback);
+
+        void setKeyEventCycleForward(int key) { _cyleForwardKey = key; }
+        int getKeyEventCyclesForward() const { return _cyleForwardKey; }
+
+        void setKeyEventCycleBackward(int key) { _cyleBackwardKey = key; }
+        int getKeyEventCyclesBackward() const { return _cyleBackwardKey; }
+
+        void setKeyEventActivatesTransparencyAdjustment(int key) { _transparencyKey = key; }
+        int getKeyEventActivatesTransparencyAdjustment() const { return _transparencyKey; }
+
+        void setKeyEventActivatesSampleDensityAdjustment(int key) { _sampleDensityKey = key; }
+        int getKeyEventActivatesSampleAdjustment() const { return _sampleDensityKey; }
+
+        void setKeyEventActivatesAlphaFuncAdjustment(int key) { _alphaFuncKey = key; }
+        int getKeyEventActivatesAlphaFuncAdjustment() const { return _alphaFuncKey; }
+
+        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&, osg::Object* object, osg::NodeVisitor*);
+
+        int     _cyleForwardKey;
+        int     _cyleBackwardKey;
+        int     _transparencyKey;
+        int     _alphaFuncKey;
+        int     _sampleDensityKey;
+
+        bool    _updateTransparency;
+        bool    _updateAlphaCutOff;
+        bool    _updateSampleDensity;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/RayTracedTechnique
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/RayTracedTechnique (revision 9524)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/RayTracedTechnique (revision 9524)
@@ -0,0 +1,52 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_RAYTRACEDTECHNIQUE
+#define OSGVOLUME_RAYTRACEDTECHNIQUE 1
+
+#include <osgVolume/VolumeTechnique>
+
+namespace osgVolume {
+
+class OSGVOLUME_EXPORT RayTracedTechnique : public VolumeTechnique
+{
+    public:
+
+        RayTracedTechnique();
+
+        RayTracedTechnique(const RayTracedTechnique&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, RayTracedTechnique);
+
+        virtual void init();
+
+        virtual void update(osgUtil::UpdateVisitor* nv);
+
+        virtual void cull(osgUtil::CullVisitor* nv);
+
+        /** Clean scene graph from any terrain technique specific nodes.*/
+        virtual void cleanSceneGraph();
+
+        /** Traverse the terrain subgraph.*/
+        virtual void traverse(osg::NodeVisitor& nv);
+
+    protected:
+    
+        virtual ~RayTracedTechnique();
+        
+        osg::ref_ptr<osg::Geode> _geode;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Version
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Version (revision 9494)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Version (revision 9494)
@@ -0,0 +1,46 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_VERSION
+#define OSGVOLUME_VERSION 1
+
+#include <osgVolume/Export>
+
+extern "C" {
+
+/**
+ * osgVolumeGetVersion() returns the library version number.
+ * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgVolumeGetVersion.
+ *
+ * This C function can be also used to check for the existence of the OpenSceneGraph
+ * library using autoconf and its m4 macro AC_CHECK_LIB.
+ *
+ * Here is the code to add to your configure.in:
+ \verbatim
+ #
+ # Check for the OpenSceneGraph (OSG) Volume library
+ #
+ AC_CHECK_LIB(osg, osgVolumeGetVersion, ,
+    [AC_MSG_ERROR(OpenSceneGraph Volume library not found. See http://www.openscenegraph.org)],)
+ \endverbatim
+*/
+extern OSGVOLUME_EXPORT const char* osgVolumeGetVersion();
+
+/**
+ * osgVolumeGetLibraryName() returns the library name in human friendly form.
+*/
+extern OSGVOLUME_EXPORT const char* osgVolumeGetLibraryName();
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTile
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTile (revision 9747)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTile (revision 9747)
@@ -0,0 +1,157 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_tile
+#define OSGVOLUME_tile 1
+
+#include <osg/Group>
+#include <osg/Image>
+
+#include <osgDB/ReaderWriter>
+
+#include <osgVolume/Layer>
+#include <osgVolume/VolumeTechnique>
+
+namespace osgVolume {
+
+class Volume;
+
+class OSGVOLUME_EXPORT TileID
+{
+    public:
+    
+        TileID();
+
+        TileID(int in_level, int in_x, int in_y, int in_z);
+            
+        bool operator == (const TileID& rhs) const        
+        {
+            return (level==rhs.level) && (x==rhs.x) && (y==rhs.y) && (z==rhs.z);
+        }
+
+        bool operator != (const TileID& rhs) const        
+        {
+            return (level!=rhs.level) || (x!=rhs.x) || (y!=rhs.y) || (z!=rhs.z);
+        }
+
+        bool operator < (const TileID& rhs) const
+        {
+            if (level<rhs.level) return true;
+            if (level>rhs.level) return false;
+            if (x<rhs.x) return true;
+            if (x>rhs.x) return false;
+            if (y<rhs.y) return true;
+            if (y>rhs.y) return false;
+            return z<rhs.z;
+        }
+        
+        bool valid() const { return level>=0; }
+
+        int level;
+        int x;
+        int y;
+        int z;
+};
+
+
+/** VolumeTile provides a framework for loosely coupling 3d image data with rendering algorithms.
+  * This allows TerrainTechnique's to be plugged in at runtime.*/
+class OSGVOLUME_EXPORT VolumeTile : public osg::Group
+{
+    public:
+
+        VolumeTile();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        VolumeTile(const VolumeTile&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Node(osgVolume, VolumeTile);
+
+        virtual void traverse(osg::NodeVisitor& nv);
+
+        /** Call init on any attached TerrainTechnique.*/
+        void init();
+
+
+        /** Set the Volume that this Volume tile is a member of.*/
+        void setVolume(Volume* ts);
+
+        /** Get the Volume that this Volume tile is a member of.*/
+        Volume* getVolume() { return _volume; }
+
+        /** Get the const Volume that this Volume tile is a member of.*/
+        const Volume* getVolume() const { return _volume; }
+
+        
+        /** Set the TileID (layer, x,y,z) of the VolumeTile.
+          * The TileID is used so it can be located by its neighbours 
+          * via the enclosing Volume node that manages a map of TileID to VolumeTiles.*/
+        void setTileID(const TileID& tileID);
+        
+        /** Get the TileID (layer, x,y,z) of the VolumeTile.*/
+        const TileID& getTileID() const { return _tileID; }
+        
+        
+        void setLocator(Locator* locator) { _locator = locator; }
+        Locator* getLocator() { return _locator.get(); }
+        const Locator* getLocator() const { return _locator.get(); }
+
+
+        void setLayer(Layer* layer);
+        Layer* getLayer() { return _layer.get(); }
+        const Layer* getLayer() const { return _layer.get(); }
+
+
+
+        /** Set the VolumeTechnique that will be used to render this tile. */
+        void setVolumeTechnique(VolumeTechnique* VolumeTechnique);
+
+        /** Get the VolumeTechnique that will be used to render this tile. */
+        VolumeTechnique* getVolumeTechnique() { return _volumeTechnique.get(); }
+        
+        /** Get the const VolumeTechnique that will be used to render this tile. */
+        const VolumeTechnique* getVolumeTechnique() const { return _volumeTechnique.get(); }
+
+
+        /** Set the dirty flag on/off.*/
+        void setDirty(bool dirty);
+
+        /** return true if the tile is dirty and needs to be updated,*/
+        bool getDirty() const { return _dirty; }
+
+
+        virtual osg::BoundingSphere computeBound() const;
+
+    protected:
+
+        virtual ~VolumeTile();
+
+        friend class Volume;
+
+        Volume*                             _volume;
+        
+        bool                                _dirty;
+        bool                                _hasBeenTraversal;
+        
+        TileID                              _tileID;
+
+        osg::ref_ptr<VolumeTechnique>       _volumeTechnique;
+
+        osg::ref_ptr<Locator>               _locator;        
+
+        osg::ref_ptr<Layer>                 _layer;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Volume
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Volume (revision 9497)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Volume (revision 9497)
@@ -0,0 +1,79 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME
+#define OSGVOLUME 1
+
+#include <osg/Group>
+#include <osg/CoordinateSystemNode>
+
+#include <osgVolume/VolumeTile>
+
+namespace osgVolume {
+
+/** Volume provides a framework for loosely coupling 3d image VolumeTile's with volume algorithms.
+  * This allows VolumeTechnique's to be plugged in at runtime.*/
+class OSGVOLUME_EXPORT Volume : public osg::Group
+{
+    public:
+
+        Volume();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Volume(const Volume&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Node(osgVolume, Volume);
+
+        virtual void traverse(osg::NodeVisitor& nv);
+        
+        /** Get the VolumeTile for a given VolumeTileID.*/
+        VolumeTile* getVolumeTile(const TileID& tileID);
+
+        /** Get the const VolumeTile for a given VolumeTileID.*/
+        const VolumeTile* getVolumeTile(const TileID& tileID) const;
+        
+
+        /** Set the VolumeTechnique prototype that nested VolumeTile should clone if they haven't already been assigned a volume rendering technique. */
+        void setVolumeTechniquePrototype(VolumeTechnique* volumeTechnique) { _volumeTechnique = volumeTechnique; }
+
+        /** Get the VolumeTechnique prototype. */
+        VolumeTechnique* getVolumeTechniquePrototype() { return _volumeTechnique.get(); }
+        
+        /** Get the const VolumeTechnique prototype. */
+        const VolumeTechnique* getVolumeTechniquePrototype() const { return _volumeTechnique.get(); }
+
+
+    protected:
+
+        virtual ~Volume();
+        
+        friend class VolumeTile;
+        
+        void dirtyRegisteredVolumeTiles();
+
+        void registerVolumeTile(VolumeTile* tile);
+        void unregisterVolumeTile(VolumeTile* tile);
+
+        typedef std::map< TileID, VolumeTile* > VolumeTileMap;
+        typedef std::set< VolumeTile* >         VolumeTileSet;
+
+        mutable OpenThreads::Mutex              _mutex;
+        VolumeTileSet                           _volumeTileSet;
+        VolumeTileMap                           _volumeTileMap;
+       
+        osg::ref_ptr<VolumeTechnique>           _volumeTechnique;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/FixedFunctionTechnique
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/FixedFunctionTechnique (revision 9504)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/FixedFunctionTechnique (revision 9504)
@@ -0,0 +1,60 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_FIXEDFUNCTIONTECHNIQUE
+#define OSGVOLUME_FIXEDFUNCTIONTECHNIQUE 1
+
+#include <osgVolume/VolumeTechnique>
+
+namespace osgVolume {
+
+class OSGVOLUME_EXPORT FixedFunctionTechnique : public VolumeTechnique
+{
+    public:
+
+        FixedFunctionTechnique();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        FixedFunctionTechnique(const FixedFunctionTechnique&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, FixedFunctionTechnique);
+
+        virtual void init();
+
+        virtual void update(osgUtil::UpdateVisitor* nv);
+
+        virtual void cull(osgUtil::CullVisitor* nv);
+        
+        void setNumSlices(unsigned int numSlices);
+
+        unsigned int getNumSlices() const { return _numSlices; }
+        
+
+        /** Clean scene graph from any terrain technique specific nodes.*/
+        virtual void cleanSceneGraph();
+
+        /** Traverse the terrain subgraph.*/
+        virtual void traverse(osg::NodeVisitor& nv);
+
+    protected:
+    
+        virtual ~FixedFunctionTechnique();
+        
+        osg::ref_ptr<osg::Node> _node;
+        
+        unsigned int _numSlices;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Layer
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Layer (revision 9747)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/Layer (revision 9747)
@@ -0,0 +1,234 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_LAYER
+#define OSGVOLUME_LAYER 1
+
+#include <osg/Image>
+#include <osg/TransferFunction>
+
+#include <osgVolume/Locator>
+#include <osgVolume/Property>
+
+namespace osgVolume {
+
+class OSGVOLUME_EXPORT Layer : public osg::Object
+{
+    public:
+
+        Layer();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, Layer);
+        
+        /** Set the file name of the data associated with this layer. */
+        virtual void setFileName(const std::string& filename) { _filename = filename; }
+
+        /** Get the file name of the layer. */
+        virtual const std::string& getFileName() const { return _filename; }
+
+        void setLocator(Locator* locator) { _locator = locator; }
+        Locator* getLocator() { return _locator.get(); }
+        const Locator* getLocator() const { return _locator.get(); }
+        
+        void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; }
+        const osg::Vec4& getDefaultValue() const { return _defaultValue; }
+
+        /** Set the minification texture filter to use when do texture associated with this layer.*/
+        void setMinFilter(osg::Texture::FilterMode filter) { _minFilter = filter; }
+
+        /** Get the minification texture filter to use when do texture associated with this layer.*/
+        osg::Texture::FilterMode getMinFilter() const { return _minFilter; }
+
+        /** Set the magniification texture filter to use when do texture associated with this layer.*/
+        void setMagFilter(osg::Texture::FilterMode filter) { _magFilter = filter; }
+
+        /** Get the magnification texture filter to use when do texture associated with this layer.*/
+        osg::Texture::FilterMode getMagFilter() const { return _magFilter; }
+
+        /** Return image associated with layer if supported. */        
+        virtual osg::Image* getImage() { return 0; }
+
+        /** Return const image associated with layer if supported. */        
+        virtual const osg::Image* getImage() const { return 0; }
+
+
+        /** Set the Property (or Properties via the CompositeProperty) that informs the VolumeTechnique how this layer should be rendered.*/
+        void setProperty(Property* property) { _property = property; }
+
+        /** Get the Property that informs the VolumeTechnique how this layer should be rendered.*/
+        Property* getProperty() { return _property.get(); }
+
+        /** Get the const Property that informs the VolumeTechnique how this layer should be rendered.*/
+        const Property* getProperty() const { return _property.get(); }
+
+        /** Add a property, automatically creating a CompositePorperty if one isn't already assigned.*/
+        void addProperty(Property* property);
+
+
+        /** Specify whether ImageLayer requires update traversal. */
+        virtual bool requiresUpdateTraversal() const { return false; }
+
+        /** Call update on the Layer.*/
+        virtual void update(osg::NodeVisitor& /*nv*/) {}        
+
+        /** increment the modified count."*/
+        virtual void dirty() {};
+
+        /** Set the modified count value.  */
+        virtual void setModifiedCount(unsigned int /*value*/) {};
+
+        /** Get modified count value. */
+        virtual unsigned int getModifiedCount() const { return 0; }
+
+        virtual osg::BoundingSphere computeBound() const;
+
+    protected:
+
+        virtual ~Layer();
+
+        std::string                         _filename;
+        osg::ref_ptr<Locator>               _locator;
+        osg::Vec4                           _defaultValue;
+        osg::Texture::FilterMode            _minFilter;
+        osg::Texture::FilterMode            _magFilter;
+        
+        osg::ref_ptr<Property>              _property;
+
+};
+
+class OSGVOLUME_EXPORT ImageLayer : public Layer
+{
+    public:
+
+        ImageLayer(osg::Image* image=0);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, ImageLayer);
+
+        void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); }
+        virtual const std::string& getFileName() const { return _image.get() ? _image->getFileName() : _filename; }
+
+        void setImage(osg::Image* image);
+
+        /** Return image associated with layer. */  
+        virtual osg::Image* getImage() { return _image.get(); }
+
+        /** Return const image associated with layer. */
+        virtual const osg::Image* getImage() const { return _image.get(); }
+                
+        /** Compute the min and max pixel colors.*/
+        bool computeMinMax(osg::Vec4& min, osg::Vec4& max);
+                
+        /** Apply color transformation to pixels using c' = offset + c * scale .*/
+        void offsetAndScaleImage(const osg::Vec4& offset, const osg::Vec4& scale);
+        
+        /** Compute the min max range of the image, and then remap this to a 0 to 1 range.*/
+        void rescaleToZeroToOneRange();
+               
+        /** Compute the min color component of the image and then translate and pixels by this offset to make the new min component 0.*/
+        void translateMinToZero();
+
+        virtual bool requiresUpdateTraversal() const;
+
+        virtual void update(osg::NodeVisitor& /*nv*/);
+
+        virtual void dirty();
+        virtual void setModifiedCount(unsigned int value);
+        virtual unsigned int getModifiedCount() const;
+
+    protected:
+
+        virtual ~ImageLayer() {}
+
+        osg::ref_ptr<osg::Image>    _image;
+
+};
+
+class OSGVOLUME_EXPORT CompositeLayer : public Layer
+{
+    public:
+
+        CompositeLayer();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, CompositeLayer);
+
+        void clear();
+
+        void setFileName(unsigned int i, const std::string& filename) { _layers[i].filename = filename; if (_layers[i].layer.valid()) _layers[i].layer->setFileName(filename); }
+        const std::string& getFileName(unsigned int i) const { return _layers[i].layer.valid() ? _layers[i].layer->getFileName() : _layers[i].filename; }
+
+        void setLayer(unsigned int i, Layer* layer) { if (i>=_layers.size()) _layers.resize(i+1); _layers[i].layer = layer; }
+        Layer* getLayer(unsigned int i) { return i<_layers.size() ? _layers[i].layer.get() : 0; }
+        const Layer* getLayer(unsigned int i) const { return i<_layers.size() ? _layers[i].layer.get() : 0; }
+
+        void addLayer(Layer* layer) { _layers.push_back(NameLayer(layer->getFileName(),layer)); }
+
+        void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); }
+        
+        unsigned int getNumLayers() const { return _layers.size(); }
+
+        bool requiresUpdateTraversal() const;
+   
+        virtual void update(osg::NodeVisitor& /*nv*/);
+
+    protected:
+
+        virtual ~CompositeLayer() {}
+
+        struct NameLayer
+        {
+            NameLayer() {}
+        
+            NameLayer(const NameLayer& cnl):
+                filename(cnl.filename),
+                layer(cnl.layer) {}
+
+            NameLayer(const std::string& fn, Layer* l):
+                filename(fn),
+                layer(l) {}
+
+            NameLayer& operator = (const NameLayer& cnl)
+            {
+                if (&cnl==this) return *this;
+                
+                filename = cnl.filename;
+                layer = cnl.layer;
+                return *this;
+            }
+
+            std::string         filename;
+            osg::ref_ptr<Layer> layer;
+        };
+        
+        typedef std::vector< NameLayer > Layers;
+        
+        Layers _layers;
+};
+
+/** Compute a 3d image that represent the normal map of the specified 3d image.*/
+extern OSGVOLUME_EXPORT osg::Image* createNormalMapTexture(osg::Image* image_3d);
+
+/** Create an image that has a transfer function applied specified Image.*/
+extern OSGVOLUME_EXPORT osg::Image* applyTransferFunction(osg::Image* image, osg::TransferFunction1D* transferFunction);
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTechnique
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTechnique (revision 9494)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgVolume/VolumeTechnique (revision 9494)
@@ -0,0 +1,68 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGVOLUME_VOLUMETECHNIQUE
+#define OSGVOLUME_VOLUMETECHNIQUE 1
+
+#include <osg/Object>
+
+#include <osgUtil/UpdateVisitor>
+#include <osgUtil/CullVisitor>
+
+#include <osgVolume/Export>
+
+namespace osgVolume {
+
+class VolumeTile;
+
+class OSGVOLUME_EXPORT VolumeTechnique : public osg::Object
+{
+    public:
+
+        VolumeTechnique();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        VolumeTechnique(const VolumeTechnique&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Object(osgVolume, VolumeTechnique);
+
+        VolumeTile* getVolumeTile() { return _volumeTile; }
+        const VolumeTile* getVolumeTile() const { return _volumeTile; }
+
+        virtual void init();
+
+        virtual void update(osgUtil::UpdateVisitor* nv);
+
+        virtual void cull(osgUtil::CullVisitor* nv);
+
+        /** Clean scene graph from any terrain technique specific nodes.*/
+        virtual void cleanSceneGraph();
+
+        /** Traverse the terrain subgraph.*/
+        virtual void traverse(osg::NodeVisitor& nv);
+
+    protected:
+    
+        void setDirty(bool dirty);
+
+        virtual ~VolumeTechnique();
+        
+        friend class osgVolume::VolumeTile;
+
+        VolumeTile*    _volumeTile;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/BumpMapping
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/BumpMapping (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/BumpMapping (revision 5328)
@@ -0,0 +1,198 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_BUMPMAPPING_
+#define OSGFX_BUMPMAPPING_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+#include <osg/ref_ptr>
+#include <osg/Texture2D>
+
+namespace osgFX
+{
+
+    /**
+     This effect makes surfaces appear bumpy. Children nodes must use two textures, 
+     one for diffuse color and one for the normal map (which can be created 
+     from a height map with tools like nVIDIA's normal map generator). Furthermore, 
+     tangent-space basis vectors must be created and assigned to each Geometry; this 
+     can be done quickly by calling BumpMapping::prepareChildren(). Note that both 
+     diffuse and normal map textures must have corresponding UV maps defined in 
+     Geometry objects.
+     This effect defines a preferred technique which uses ARB vertex & fragment 
+     programs, and a fallback technique which doesn't use fragment programs. The 
+     latter is more limited though since it can't handle ambient and specular 
+     components.
+     */
+    class OSGFX_EXPORT BumpMapping: public Effect {
+    public:
+        BumpMapping();
+        BumpMapping(const BumpMapping& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        META_Effect(osgFX, BumpMapping, 
+        
+            "Bump Mapping", 
+            
+            "This effect makes surfaces appear bumpy. Children nodes must use two textures, "
+            "one for diffuse color and one for the normal map (which can be created "
+            "from a height map with tools like nVIDIA's normal map generator). Furthermore, "
+            "tangent-space basis vectors must be created and assigned to each Geometry; this "
+            "can be done quickly by calling BumpMapping::prepareChildren(). Note that both "
+            "diffuse and normal map textures must have corresponding UV maps defined in "
+            "Geometry objects.\n"
+            "This effect defines a preferred technique which uses ARB vertex & fragment "
+            "programs, and a fallback technique which doesn't use fragment programs. The "
+            "latter is more limited though since it can't handle ambient and specular "
+            "components.",
+            
+            "Marco Jez");
+            
+        
+        /** get the OpenGL light number */
+        inline int getLightNumber() const;
+        
+        /** set the OpenGL light number that will be used in lighting computations */
+        inline void setLightNumber(int n);
+        
+        /** get the texture unit that contains diffuse color texture. Default is 1 */
+        inline int getDiffuseTextureUnit() const;
+        
+        /** set the texture unit that contains diffuse color texture. Default is 1 */
+        inline void setDiffuseTextureUnit(int n);
+
+        /** get the texture unit that contains normal map texture. Default is 0 */
+        inline int getNormalMapTextureUnit() const;
+        
+        /** set the texture unit that contains normal map texture. Default is 0 */
+        inline void setNormalMapTextureUnit(int n);
+        
+        /** get the diffuse color texture that overrides children's texture */
+        inline osg::Texture2D* getOverrideDiffuseTexture();
+        
+        /** get the const diffuse color texture that overrides children's texture */
+        inline const osg::Texture2D* getOverrideDiffuseTexture() const;
+        
+        /** set the diffuse color texture that overrides children's texture */
+        inline void setOverrideDiffuseTexture(osg::Texture2D* texture);
+        
+        /** get the normal map texture that overrides children's texture */
+        inline osg::Texture2D* getOverrideNormalMapTexture();
+        
+        /** get the const normal map texture that overrides children's texture */
+        inline const osg::Texture2D* getOverrideNormalMapTexture() const;
+
+        /** set the normal map texture that overrides children's texture */
+        inline void setOverrideNormalMapTexture(osg::Texture2D* texture);
+        
+        /**
+         prepare a Geometry for bump lighting. Tangent-space basis vectors are
+         generated and attached to the geometry as vertex attribute arrays.
+         */
+        void prepareGeometry(osg::Geometry* geo);
+        
+        /** prepare a Node for bump lighting, calling prepareGeometry() for each Geometry */
+        void prepareNode(osg::Node* node);
+        
+        /** prepare children for bump lighting. Actually calls prepareNode() for each child */
+        void prepareChildren();
+        
+        /** set up a demo environment with predefined diffuse and normal maps, as well as texture coordinates */
+        void setUpDemo();
+
+    protected:
+        virtual ~BumpMapping() {}
+        BumpMapping &operator=(const BumpMapping &) { return *this; }
+
+        bool define_techniques();
+
+    private:
+        int _lightnum;
+        int _diffuse_unit;
+        int _normal_unit;
+        osg::ref_ptr<osg::Texture2D> _diffuse_tex;
+        osg::ref_ptr<osg::Texture2D> _normal_tex;
+    };
+
+    // INLINE METHODS    
+   
+    inline int BumpMapping::getLightNumber() const
+    {
+        return _lightnum;
+    }
+    
+    inline void BumpMapping::setLightNumber(int n)
+    {
+        _lightnum = n;
+        dirtyTechniques();
+    }
+    
+    inline int BumpMapping::getDiffuseTextureUnit() const
+    {
+        return _diffuse_unit;
+    }
+    
+    inline void BumpMapping::setDiffuseTextureUnit(int n)
+    {
+        _diffuse_unit = n;
+        dirtyTechniques();
+    }
+    
+    inline int BumpMapping::getNormalMapTextureUnit() const
+    {
+        return _normal_unit;
+    }
+    
+    inline void BumpMapping::setNormalMapTextureUnit(int n)
+    {
+        _normal_unit = n;
+        dirtyTechniques();
+    }
+    
+    inline osg::Texture2D* BumpMapping::getOverrideDiffuseTexture()
+    {
+        return _diffuse_tex.get();
+    }
+
+    inline const osg::Texture2D* BumpMapping::getOverrideDiffuseTexture() const
+    {
+        return _diffuse_tex.get();
+    }
+    
+    inline void BumpMapping::setOverrideDiffuseTexture(osg::Texture2D* texture)
+    {
+        _diffuse_tex = texture;
+        dirtyTechniques();
+    }
+
+    inline osg::Texture2D* BumpMapping::getOverrideNormalMapTexture()
+    {
+        return _normal_tex.get();
+    }
+
+    inline const osg::Texture2D* BumpMapping::getOverrideNormalMapTexture() const
+    {
+        return _normal_tex.get();
+    }
+    
+    inline void BumpMapping::setOverrideNormalMapTexture(osg::Texture2D* texture)
+    {
+        _normal_tex = texture;
+        dirtyTechniques();
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/AnisotropicLighting
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/AnisotropicLighting (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/AnisotropicLighting (revision 5328)
@@ -0,0 +1,122 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_ANISOTROPICLIGHTING_
+#define OSGFX_ANISOTROPICLIGHTING_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+#include <osg/ref_ptr>
+#include <osg/Texture2D>
+
+namespace osgFX
+{
+
+    /**
+     This single-pass effect implements a sort of anisotropic 
+     lighting that replaces the standard OpenGL lighting model.
+     The final color of vertices is not computed directly, it is 
+     the result of a texture lookup on a user-supplied lighting 
+     image map. A vertex program is used to compute the s and t 
+     texture coordinates as follows: s = (N dot H) ; t = (N dot L) 
+     where N is the vertex normal, L is the light-to-vertex vector, 
+     H is the half-way vector. This is a good example of how you 
+     can use the State::getInitialViewMatrix() method to retrieve 
+     the view matrix and perform view-dependant effects without 
+     fakes of any kind.
+     This effect requires the ARB_vertex_program extension.
+     */
+    class OSGFX_EXPORT AnisotropicLighting: public Effect {
+    public:
+        AnisotropicLighting();
+        AnisotropicLighting(const AnisotropicLighting& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        META_Effect(osgFX, AnisotropicLighting, 
+        
+            "Anisotropic Lighting", 
+            
+            "This single-pass effect implements a sort of anisotropic "
+            "lighting that replaces the standard OpenGL lighting model.\n"
+            "The final color of vertices is not computed directly, it is "
+            "the result of a texture lookup on a user-supplied lighting "
+            "image map. A vertex program is used to compute the s and t "
+            "texture coordinates as follows: s = (N dot H) ; t = (N dot L) "
+            "where N is the vertex normal, L is the light-to-vertex vector, "
+            "H is the half-way vector. This is a good example of how you "
+            "can use the State::getInitialViewMatrix() method to retrieve "
+            "the view matrix and perform view-dependant effects without "
+            "fakes of any kind.\n"
+            "This effect requires the ARB_vertex_program extension.", 
+            
+            "Marco Jez");
+            
+        
+        /** get the lighting map */
+        inline osg::Image* getLightingMap();
+        
+        /** get the const lighting map */
+        inline const osg::Image* getLightingMap() const;
+        
+        /** set the lighting map */
+        inline void setLightingMap(osg::Image* image);
+
+        /** get the OpenGL light number */
+        inline int getLightNumber() const;
+        
+        /** set the OpenGL light number that will be used in lighting computations */
+        inline void setLightNumber(int n);
+
+    protected:
+        virtual ~AnisotropicLighting() {}
+        AnisotropicLighting& operator=(const AnisotropicLighting&) { return *this; }
+
+        bool define_techniques();
+
+    private:
+        int _lightnum;
+        osg::ref_ptr<osg::Texture2D> _texture;
+    };
+
+    // INLINE METHODS
+    
+    inline osg::Image* AnisotropicLighting::getLightingMap()
+    {
+        return _texture->getImage();
+    }
+    
+    inline const osg::Image* AnisotropicLighting::getLightingMap() const
+    {
+        return _texture->getImage();
+    }
+    
+    inline void AnisotropicLighting::setLightingMap(osg::Image* image)
+    {
+        _texture->setImage(image);
+    }
+    
+    inline int AnisotropicLighting::getLightNumber() const
+    {
+        return _lightnum;
+    }
+    
+    inline void AnisotropicLighting::setLightNumber(int n)
+    {
+        _lightnum = n;
+        dirtyTechniques();
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Export
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Export (revision 8744)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Export (revision 8744)
@@ -0,0 +1,40 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_EXPORT_
+#define OSGFX_EXPORT_
+
+#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__)  || defined( __MWERKS__)
+    #  if defined( OSG_LIBRARY_STATIC )
+    #    define OSGFX_EXPORT
+    #  elif defined( OSGFX_LIBRARY )
+    #    define OSGFX_EXPORT   __declspec(dllexport)
+    #  else
+    #    define OSGFX_EXPORT   __declspec(dllimport)
+    #  endif
+#else
+    #  define OSGFX_EXPORT
+#endif
+
+/**
+
+\namespace osgFX
+
+The osgFX library is a NodeKit that extends the core scene graph to provide a special effects framework. 
+osgFX's framework allows multiple rendering techniques to be provide for each effect, thereby provide the use
+appropriate rendering techniques for each different class of graphics hardware, i.e. support for both modern
+programmable graphics hardware and still have standard OpenGL 1.1 support as a fallback. 
+*/
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Cartoon
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Cartoon (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Cartoon (revision 5328)
@@ -0,0 +1,122 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_CARTOON_
+#define OSGFX_CARTOON_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+#include <osg/Material>
+#include <osg/LineWidth>
+
+namespace osgFX
+{
+
+     /**
+     This effect implements a technique called 'Cel-Shading' to produce a 
+     cartoon-style (non photorealistic) rendering. Two passes are required: 
+     the first one draws solid surfaces, the second one draws the outlines. 
+     A vertex program is used to setup texture coordinates for a sharp lighting 
+     texture on unit 0 which is generated on-the-fly.
+     This effect requires the ARB_vertex_program extension.
+     */
+    class OSGFX_EXPORT Cartoon: public Effect {
+    public:
+        Cartoon();
+        Cartoon(const Cartoon& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        // effect class informations
+        META_Effect(
+            osgFX, 
+            Cartoon, 
+            
+            "Cartoon", 
+            
+            "This effect implements a technique called 'Cel-Shading' to produce a "
+            "cartoon-style (non photorealistic) rendering. Two passes are required: "
+            "the first one draws solid surfaces, the second one draws the outlines. "
+            "A vertex program is used to setup texture coordinates for a sharp lighting "
+            "texture on unit 0 which is generated on-the-fly.\n"
+            "This effect requires the ARB_vertex_program extension "
+            "or OpenGL Shading Language.",
+            
+            "Marco Jez; OGLSL port by Mike Weiblen");
+
+        /** get the outline color */
+        inline const osg::Vec4& getOutlineColor() const;
+        
+        /** set the outline color */
+        inline void setOutlineColor(const osg::Vec4& color);
+        
+        /** get the outline line width */
+        inline float getOutlineLineWidth() const;
+        
+        /** set the outline line width */
+        inline void setOutlineLineWidth(float w);
+        
+        /** get the OpenGL light number */
+        inline int getLightNumber() const;
+        
+        /** set the OpenGL light number that will be used in lighting computations */
+        inline void setLightNumber(int n);
+
+    protected:
+        virtual ~Cartoon() {}
+        Cartoon& operator=(const Cartoon&) { return *this; }
+
+        bool define_techniques();
+
+    private:
+        osg::ref_ptr<osg::Material> _wf_mat;
+        osg::ref_ptr<osg::LineWidth> _wf_lw;
+        int _lightnum;
+    };
+
+    // INLINE METHODS
+
+    inline const osg::Vec4& Cartoon::getOutlineColor() const
+    {
+        return _wf_mat->getEmission(osg::Material::FRONT_AND_BACK);
+    }
+
+    inline void Cartoon::setOutlineColor(const osg::Vec4& color)
+    {
+        _wf_mat->setEmission(osg::Material::FRONT_AND_BACK, color);
+    }
+    
+    inline float Cartoon::getOutlineLineWidth() const
+    {
+        return _wf_lw->getWidth();
+    }
+    
+    inline void Cartoon::setOutlineLineWidth(float w)
+    {
+        _wf_lw->setWidth(w);
+    }
+    
+    inline int Cartoon::getLightNumber() const
+    {
+        return _lightnum;
+    }
+    
+    inline void Cartoon::setLightNumber(int n)
+    {
+        _lightnum = n;
+        dirtyTechniques();
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Technique
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Technique (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Technique (revision 5328)
@@ -0,0 +1,158 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_TECHNIQUE_
+#define OSGFX_TECHNIQUE_
+
+#include <osgFX/Export>
+
+#include <osg/Referenced>
+#include <osg/State>
+#include <osg/Group>
+#include <osg/NodeVisitor>
+
+#include <vector>
+#include <string>
+
+/**
+ An helper macro that defines the methods techniqueName() and 
+ techniqueDescription() making them return the strings passed as parameters.
+ */
+#define META_Technique(name, description) \
+    inline virtual const char *techniqueName() { return name; } \
+    inline virtual const char *techniqueDescription() { return description; }
+
+
+namespace osgFX
+{
+
+    class Effect;
+
+    /**
+     This is the base class for effect techniques. A technique represents one
+     of the possible ways to implement a special effect. This base class is
+     abstract, you will have to subclass your own techniques for your custom
+     effects.
+     Derived classes will have to implement the define_passes() method to
+     configure the rendering pass(es) that make up the technique. Usually
+     you will create one StateSet object for each rendering pass and then
+     you'll call addPass(stateset).
+     The validate() method should return true if the technique is valid within
+     the current rendering context, false otherwise. The default implementation
+     of validate() calls getRequiredExtensions() and tests whether all required
+     extensions are supported or not, returning false if at least one extension
+     is not supported.
+     */
+    class OSGFX_EXPORT Technique: public osg::Referenced {
+    public:
+        Technique();
+
+        /** get the name of this Technique */
+        virtual const char *techniqueName()        { return "Default"; }
+
+        /** get a brief description of this Technique */
+        virtual const char *techniqueDescription() { return "This is the default technique"; }
+
+        /**
+         collect the GL extension strings which are required for this technique
+         to work properly. This method is called from the default implementation
+         of validate().
+         */
+        virtual void getRequiredExtensions(std::vector<std::string>&  /*extensions*/) const {};
+
+        /**
+         tests whether this technique is valid for the current rendering context.
+         The default behavior is to call getRequiredExtensions() and check for
+         extension availability.
+         */
+        virtual bool validate(osg::State& ) const;
+
+        /** get the number of rendering passes defined in this Technique */
+        inline int getNumPasses() const;
+
+        /** get the StateSet object associated to the i-th pass */
+        inline osg::StateSet* getPassStateSet(int i);
+
+        /** get the const StateSet object associated to the i-th pass */
+        inline const osg::StateSet* getPassStateSet(int i) const;
+
+        /** 
+         traverse children with multipass if necessary. By default this method
+         simply calls the protected method traverse_implementation(); you can
+         override it to change the default behavior.
+         Don't call this method directly as it is called by osgFX::Effect
+         */
+        inline virtual void traverse(osg::NodeVisitor& nv, Effect* fx);
+        
+    protected:
+        Technique(const Technique &): osg::Referenced() {}    // copying is nonsense ;)
+        virtual ~Technique() {}
+        Technique &operator=(const Technique &)  { return *this; }
+
+        /** force rebuilding of pass nodes on next traversal */
+        inline void dirtyPasses();
+
+        /** create a new pass node, add it to the technique and associate a StateSet */
+        void addPass(osg::StateSet* ss = 0);
+        
+        /** optional: return a node that overrides the child node on a specified pass */
+        inline virtual osg::Node* getOverrideChild(int)  { return 0; }
+
+        /**
+         define the rendering passes that make up this technique. You must
+         implement this method in derived classes to add the required passes.
+         */
+        virtual void define_passes() = 0;
+        
+        /**
+         traverse children with multipass if necessary. Don't call this method
+         directly unless you are in a customized version of traverse().
+         */
+        void traverse_implementation(osg::NodeVisitor& nv, Effect* fx);
+
+    private:
+        typedef std::vector<osg::ref_ptr<osg::StateSet> > Pass_list;
+        Pass_list _passes;
+    };
+
+    // INLINE METHODS
+
+    inline int Technique::getNumPasses() const
+    {
+        return static_cast<int>(_passes.size());
+    }
+
+    inline osg::StateSet* Technique::getPassStateSet(int i)
+    {
+        return _passes[i].get();
+    }
+
+    inline const osg::StateSet* Technique::getPassStateSet(int i) const
+    {
+        return _passes[i].get();
+    }
+      
+    inline void Technique::dirtyPasses()
+    {
+        _passes.clear();
+    }
+    
+    inline void Technique::traverse(osg::NodeVisitor& nv, Effect* fx)
+    {
+        traverse_implementation(nv, fx);
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Validator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Validator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Validator (revision 5328)
@@ -0,0 +1,75 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_VALIDATOR_
+#define OSGFX_VALIDATOR_
+
+#include <osgFX/Effect>
+
+#include <osg/ref_ptr>
+#include <osg/StateAttribute>
+
+#include <vector>
+
+namespace osgFX
+{
+
+    /**
+     This class is used internally by osgFX::Effect to choose between different
+     techniques dynamically. The apply() method will call each technique's
+     validate() method and store the results in a buffered array. The Effect
+     class will then choose the first technique that could be validated in all
+     active rendering contexts.
+     */
+    class OSGFX_EXPORT Validator: public osg::StateAttribute {
+    public:
+        
+        Validator();
+        Validator(Effect* effect);
+        Validator(const Validator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osgFX, Validator, VALIDATOR);
+
+        void apply(osg::State& state) const;
+        void compileGLObjects(osg::State& state) const;
+
+        inline int compare(const osg::StateAttribute& sa) const;
+        
+        inline void disable() { _effect = 0; }
+
+    protected:
+        virtual ~Validator() {}
+        Validator& operator=(const Validator&) { return *this; }
+
+    private:
+        mutable Effect* _effect;
+    };
+
+    // INLINE METHODS
+
+    inline int Validator::compare(const osg::StateAttribute& sa) const
+    {
+        // check the types are equal and then create the rhs variable
+        //used by the COMPARE_StateAttribute_Paramter macro's below.
+        COMPARE_StateAttribute_Types(Validator,sa)
+        
+        // compare parameters
+        COMPARE_StateAttribute_Parameter(_effect)
+
+        return 0;
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Version
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Version (revision 7365)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Version (revision 7365)
@@ -0,0 +1,46 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGFX_VERSION
+#define OSGFX_VERSION 1
+
+#include <osgFX/Export>
+
+extern "C" {
+
+/**
+ * osgFXGetVersion() returns the library version number.
+ * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgFXGetVersion.
+ *
+ * This C function can be also used to check for the existence of the OpenSceneGraph
+ * library using autoconf and its m4 macro AC_CHECK_LIB.
+ *
+ * Here is the code to add to your configure.in:
+ \verbatim
+ #
+ # Check for the OpenSceneGraph (OSG) FX library
+ #
+ AC_CHECK_LIB(osg, osgFXGetVersion, ,
+    [AC_MSG_ERROR(OpenSceneGraph FX library not found. See http://www.openscenegraph.org)],)
+ \endverbatim
+*/
+extern OSGFX_EXPORT const char* osgFXGetVersion();
+
+/**
+ * getLibraryName() returns the library name in human friendly form.
+*/
+extern OSGFX_EXPORT const char* osgFXGetLibraryName();
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Scribe
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Scribe (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Scribe (revision 5328)
@@ -0,0 +1,101 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_SCRIBE_
+#define OSGFX_SCRIBE_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+#include <osg/Material>
+#include <osg/LineWidth>
+
+namespace osgFX
+{
+
+    /**
+     This is a two-passes effect; the first pass renders the subgraph as usual 
+     while the second pass switches to wireframe mode, sets up lighting and 
+     material to obtain a fixed (user-defined) color and then renders the subgraph.
+     This effect uses the PolygonOffset attribute to avoid Z-fighting, so it 
+     requires at least OpenGL version 1.1.
+    */
+    class OSGFX_EXPORT Scribe: public Effect {
+    public:
+        Scribe();
+        Scribe(const Scribe& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        // effect class informations
+        META_Effect(
+            osgFX, 
+            Scribe, 
+            
+            "Scribe", 
+            
+            "This is a two-passes effect; the first pass renders the subgraph as usual "
+            "while the second pass switches to wireframe mode, sets up lighting and "
+            "material to obtain a fixed (user-defined) color and then renders the subgraph.\n"
+            "This effect uses the PolygonOffset attribute to avoid Z-fighting, so it "
+            "requires at least OpenGL version 1.1.",
+            
+            "Marco Jez");
+
+        /** get the wireframe color */
+        inline const osg::Vec4& getWireframeColor() const;
+        
+        /** set the wireframe color */
+        inline void setWireframeColor(const osg::Vec4& color);
+        
+        /** get the wireframe line width */
+        inline float getWireframeLineWidth() const;
+        
+        /** set the wireframe line width */
+        inline void setWireframeLineWidth(float w);
+
+    protected:
+        virtual ~Scribe() {}
+        Scribe& operator=(const Scribe&) { return *this; }
+
+        bool define_techniques();
+
+    private:
+        osg::ref_ptr<osg::Material> _wf_mat;
+        osg::ref_ptr<osg::LineWidth> _wf_lw;
+    };
+
+    // INLINE METHODS
+
+    inline const osg::Vec4& Scribe::getWireframeColor() const
+    {
+        return _wf_mat->getEmission(osg::Material::FRONT_AND_BACK);
+    }
+
+    inline void Scribe::setWireframeColor(const osg::Vec4& color)
+    {
+        _wf_mat->setEmission(osg::Material::FRONT_AND_BACK, color);
+    }
+    
+    inline float Scribe::getWireframeLineWidth() const
+    {
+        return _wf_lw->getWidth();
+    }
+    
+    inline void Scribe::setWireframeLineWidth(float w)
+    {
+        _wf_lw->setWidth(w);
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Registry
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Registry (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Registry (revision 5328)
@@ -0,0 +1,74 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_REGISTRY_
+#define OSGFX_REGISTRY_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+#include <osg/ref_ptr>
+
+#include <map>
+#include <string>
+
+namespace osgFX
+{
+
+    class OSGFX_EXPORT Registry : public osg::Referenced
+    {
+    public:
+
+        struct Proxy {
+            Proxy(const Effect* effect)
+            {
+                Registry::instance()->registerEffect(effect);
+            }
+        };
+
+        typedef std::map<std::string, osg::ref_ptr<const Effect> > EffectMap;
+
+        static Registry* instance();
+
+        inline void registerEffect(const Effect* effect);
+
+        inline const EffectMap& getEffectMap() const;
+
+    protected:
+
+        // Registry is a singleton; constructor and destructor must be protected
+        Registry();
+        ~Registry() {}
+
+    private:
+        EffectMap _effects;
+    };
+
+    // INLINE METHODS
+
+    
+
+    inline const Registry::EffectMap& Registry::getEffectMap() const
+    {
+        return _effects;
+    }
+
+    inline void Registry::registerEffect(const Effect* effect)
+    {
+        _effects[effect->effectName()] = effect;
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/SpecularHighlights
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/SpecularHighlights (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/SpecularHighlights (revision 5328)
@@ -0,0 +1,138 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX_SPECULARHIGHLIGHTS_
+#define OSGFX_SPECULARHIGHLIGHTS_
+
+#include <osgFX/Export>
+#include <osgFX/Effect>
+
+namespace osgFX
+{
+
+    /**
+      This effect applies additive specular highlights at fragment level (instead 
+     of OpenGL's vertex-level lighting) by using a cube map and reflective texgen. 
+     A texture matrix is computed to rotate the cube map automatically; this makes 
+     the specular effect consistent with respect to view direction and light position. 
+     The user can choose which light should be used to compute the texture matrix.
+     This effect requires the GL_ARB_texture_env_add extension and one of the cube map 
+     extensions (GL_EXT_texture_cube_map, GL_ARB_texture_cube_map or OpenGL v1.3).
+     */
+    class OSGFX_EXPORT SpecularHighlights: public Effect {
+    public:
+        SpecularHighlights();
+        SpecularHighlights(const SpecularHighlights& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        META_Effect(osgFX, SpecularHighlights, 
+        
+            "Specular Highlights", 
+            
+            "This effect applies additive specular highlights at fragment level (instead "
+            "of OpenGL's vertex-level lighting) by using a cube map and reflective texgen. "
+            "A texture matrix is computed to rotate the cube map automatically; this makes "
+            "the specular effect consistent with respect to view direction and light position. "
+            "The user can choose which light should be used to compute the texture matrix.\n"
+            "This effect requires the GL_ARB_texture_env_add extension and one of the cube map "
+            "extensions (GL_EXT_texture_cube_map, GL_ARB_texture_cube_map or OpenGL v1.3).", 
+            
+            "Marco Jez");
+            
+        
+        /** get the OpenGL light number */
+        inline int getLightNumber() const;
+        
+        /** set the OpenGL light number that will be used in lighting computations */
+        inline void setLightNumber(int n);
+        
+        /** get the texture unit number */
+        inline int getTextureUnit() const;
+        
+        /** set the texture unit that will be used to apply the cube map */
+        inline void setTextureUnit(int n);
+        
+        /** get the specular color */
+        inline const osg::Vec4& getSpecularColor() const;
+        
+        /** set the specular color */
+        inline void setSpecularColor(const osg::Vec4& color);
+        
+        /** get the specular exponent */
+        inline float getSpecularExponent() const;
+        
+        /** set the specular exponent */
+        inline void setSpecularExponent(float e);
+
+    protected:
+        virtual ~SpecularHighlights() {}
+        SpecularHighlights& operator=(const SpecularHighlights&) { return *this; }
+
+        bool define_techniques();
+
+    private:
+        int _lightnum;
+        int _unit;
+        osg::Vec4 _color;
+        float _sexp;
+    };
+
+    // INLINE METHODS
+    
+    inline int SpecularHighlights::getLightNumber() const
+    {
+        return _lightnum;
+    }
+    
+    inline void SpecularHighlights::setLightNumber(int n)
+    {
+        _lightnum = n;
+        dirtyTechniques();
+    }
+    
+    inline int SpecularHighlights::getTextureUnit() const
+    {
+        return _unit;
+    }
+    
+    inline void SpecularHighlights::setTextureUnit(int n)
+    {
+        _unit = n;
+        dirtyTechniques();
+    }
+
+    inline const osg::Vec4& SpecularHighlights::getSpecularColor() const
+    {
+        return _color;
+    }
+    
+    inline void SpecularHighlights::setSpecularColor(const osg::Vec4& color)
+    {
+        _color = color;
+        dirtyTechniques();
+    }
+
+    inline float SpecularHighlights::getSpecularExponent() const
+    {
+        return _sexp;
+    }
+    
+    inline void SpecularHighlights::setSpecularExponent(float e)
+    {
+        _sexp = e;
+        dirtyTechniques();
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Effect
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Effect (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/Effect (revision 5328)
@@ -0,0 +1,217 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//osgFX - Copyright (C) 2003 Marco Jez
+
+#ifndef OSGFX__effect
+#define OSGFX__effect
+
+#include <osgFX/Export>
+#include <osgFX/Technique>
+
+#include <osg/buffered_value>
+#include <osg/ref_ptr>
+#include <osg/Node>
+#include <osg/Group>
+#include <osg/Geode>
+#include <osg/OccluderNode>
+
+#include <vector>
+
+/**
+ An helper macro that defines the methods like effectName() and effectDescription()
+ making them return the strings passed as parameters, after the usual library name
+ and class name.
+ */
+#define META_Effect(library, classname, effectname, effectdescription, effectauthor) \
+    META_Node(library, classname) \
+    virtual const char *effectName() const        { return effectname; } \
+    virtual const char *effectDescription() const { return effectdescription; } \
+    virtual const char *effectAuthor() const      { return effectauthor; }
+
+
+namespace osgFX
+{
+
+    /**
+     The base class for special effects. An effect is basically a collection of
+     state attributes and an interface for configuring them in a predefined
+     fashion. The Effect class does more however, as it handles multipass
+     rendering transparently and it allows more than one "technique" to be
+     defined. Each technique tries to implement the effect in a different way,
+     often using different OpenGL extensions. The active technique can be
+     selected either manually, with selectTechnique(), or automatically, in which
+     case the first technique that is supported by all active rendering contexts 
+     is chosen.
+     If you are an Effect user, then simply use it as a node group. Create an 
+     instance of your desired effect, add it to your scene graph and call its 
+     addChild() method to add a child node as you would do with a Group.
+     If you are an Effect developer, you will have to implement the method
+     define_techniques() to define the different techniques that can be used
+     for obtaining the desired effect. In define_techniques() you will usually
+     create one or more instances of custom classes derived from Technique and
+     you will add them to the effect with addTechnique(). The order is important:
+     techniques added first will have higher priority and will be used first as
+     soon as all rendering contexts support it.
+     */
+    class OSGFX_EXPORT Effect: public osg::Group {
+    public:
+        Effect();
+        Effect(const Effect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        virtual inline bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const Effect*>(obj) != NULL; }
+        virtual inline const char* libraryName() const { return "osgFX"; }
+        virtual inline const char* className() const { return "Effect"; }
+
+        /** get the name of this Effect */
+        virtual const char *effectName() const        = 0;
+        
+        /** get a brief description of this Effect*/
+        virtual const char *effectDescription() const = 0;
+
+        /** get the effect author's name */
+        virtual const char *effectAuthor() const      = 0;
+
+        /** get whether the effect is enabled or not */
+        inline bool getEnabled() const;
+
+        /** set whether the effect is enabled or not */
+        inline void setEnabled(bool v);
+        
+        /**
+         optional: set effect parameters to produce a visually significant
+         result to be used in demo applications like osgfxbrowser. Default
+         is to do nothing.
+        */
+        inline virtual void setUpDemo()   {}
+
+        /** get the number of techniques defined for this Effect */
+        inline int getNumTechniques() const;
+        
+        /** get the i-th Technique */
+        inline Technique* getTechnique(int i);
+
+        /** get the i-th const Technique */
+        inline const Technique* getTechnique(int i) const;
+
+        /** get the index of the currently selected Technique */
+        inline int getSelectedTechnique() const;
+
+        enum TechniqueSelection {
+            AUTO_DETECT = -1
+        };
+
+        /** select a technique or enable automatic detection */
+        inline void selectTechnique(int i = AUTO_DETECT);
+
+        /** custom traversal */
+        virtual void traverse(osg::NodeVisitor& nv);        
+
+        /** default traversal */
+        inline void inherited_traverse(osg::NodeVisitor& nv);
+
+    protected:
+        virtual ~Effect();
+        Effect &operator=(const Effect &) { return *this; }
+       
+        /** force rebuilding of techniques on next traversal */
+        inline void dirtyTechniques();
+
+        /** add a technique to the Effect */
+        inline void addTechnique(Technique* tech);
+
+        /**
+         abstract method to be implemented in derived classes; its purpose
+         if to create the techniques that can be used for obtaining the
+         desired effect. You will usually call addTechnique() inside
+         this method.
+         */
+        virtual bool define_techniques() = 0;
+        
+    private:
+        friend class Validator;
+
+        bool _enabled;
+
+        typedef std::vector<osg::ref_ptr<Technique> > Technique_list;
+        Technique_list _techs;
+
+        mutable osg::buffered_value<int> _sel_tech;
+
+        // use int instead of bool to avoid errors
+        mutable osg::buffered_value<int> _tech_selected;
+        
+        int _global_sel_tech;
+
+        bool _techs_defined;
+
+        osg::ref_ptr<osg::Geode> _dummy_for_validation;
+        
+        void build_dummy_node();
+    };
+
+    // INLINE METHODS
+
+    inline bool Effect::getEnabled() const
+    {
+        return _enabled;
+    }
+
+    inline void Effect::setEnabled(bool v)
+    {
+        _enabled = v;
+    }
+    
+    inline int Effect::getNumTechniques() const
+    {
+        return static_cast<int>(_techs.size());
+    }
+
+    inline Technique* Effect::getTechnique(int i)
+    {
+        return _techs[i].get();
+    }
+
+    inline const Technique* Effect::getTechnique(int i) const
+    {
+        return _techs[i].get();
+    }
+
+    inline int Effect::getSelectedTechnique() const
+    {
+        return _global_sel_tech;
+    }
+
+    inline void Effect::selectTechnique(int i)
+    {
+        _global_sel_tech = i;
+    }
+
+    inline void Effect::addTechnique(Technique* tech)
+    {
+        _techs.push_back(tech);
+    }
+    
+    inline void Effect::dirtyTechniques()
+    {
+        _techs_defined = false;
+    }
+    
+    inline void Effect::inherited_traverse(osg::NodeVisitor& nv)
+    {
+        typedef osg::Group inherited;
+        inherited::traverse(nv);
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/MultiTextureControl
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/MultiTextureControl (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgFX/MultiTextureControl (revision 5328)
@@ -0,0 +1,53 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGFX_MULTITEXTURECONTROL
+#define OSGFX_MULTITEXTURECONTROL
+
+#include <osg/Group>
+
+#include <osgFX/Export>
+
+namespace osgFX
+{
+    /**
+      This node provides control over the which texture units are active and the
+      blending weighting between them.
+     */
+    class OSGFX_EXPORT MultiTextureControl: public osg::Group {
+    public:
+
+        MultiTextureControl();
+        MultiTextureControl(const MultiTextureControl& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
+
+        META_Node(osgFX, MultiTextureControl);
+        
+        void setTextureWeight(unsigned int unit, float weight);
+
+        float getTextureWeight(unsigned int unit) const { return (unit<_textureWeightList.size()) ?  _textureWeightList[unit] : 0.0f; }
+        
+        unsigned int getNumTextureWeights() const { return _textureWeightList.size(); }
+        
+    protected:
+        virtual ~MultiTextureControl() {}
+        MultiTextureControl& operator = (const MultiTextureControl&) { return *this; }
+        
+        void updateStateSet();
+        
+        typedef std::vector<float> TextureWeightList;
+        TextureWeightList _textureWeightList;
+    };
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CullVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CullVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CullVisitor (revision 9377)
@@ -0,0 +1,442 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_CULLVISITOR
+#define OSGUTIL_CULLVISITOR 1
+
+#include <map>
+#include <vector>
+
+#include <osg/NodeVisitor>
+#include <osg/BoundingSphere>
+#include <osg/BoundingBox>
+#include <osg/Matrix>
+#include <osg/Drawable>
+#include <osg/StateSet>
+#include <osg/State>
+#include <osg/ClearNode>
+#include <osg/Camera>
+#include <osg/Notify>
+
+#include <osg/CullStack>
+
+#include <osgUtil/StateGraph>
+#include <osgUtil/RenderStage>
+
+#include <osg/Vec3>
+
+namespace osgUtil {
+
+/**
+ * Basic NodeVisitor implementation for rendering a scene.
+ * This visitor traverses the scene graph, collecting transparent and
+ * opaque osg::Drawables into a depth sorted transparent bin and a state
+ * sorted opaque bin.  The opaque bin is rendered first, and then the
+ * transparent bin is rendered in order from the furthest osg::Drawable
+ * from the eye to the one nearest the eye. 
+ */
+class OSGUTIL_EXPORT CullVisitor : public osg::NodeVisitor, public osg::CullStack
+{
+    public:
+    
+        typedef osg::Matrix::value_type value_type;
+    
+
+        CullVisitor();
+        
+        /// Copy constructor that does a shallow copy.
+        CullVisitor(const CullVisitor&);
+
+        META_NodeVisitor("osgUtil","CullVisitor")
+
+        /** Create a shallow copy of the CullVisitor, used by CullVisitor::create() to clone the prototype. */
+        virtual CullVisitor* clone() const { return new CullVisitor(*this); }
+
+        /** get the prototype singleton used by CullVisitor::create().*/
+        static osg::ref_ptr<CullVisitor>& prototype();
+        
+        /** create a CullVisitor by cloning CullVisitor::prototype().*/
+        static CullVisitor* create();
+
+        virtual void reset();
+
+        virtual osg::Vec3 getEyePoint() const { return getEyeLocal(); }
+        virtual osg::Vec3 getViewPoint() const { return getViewPointLocal(); }
+        
+        virtual float getDistanceToEyePoint(const osg::Vec3& pos, bool withLODScale) const;
+        virtual float getDistanceFromEyePoint(const osg::Vec3& pos, bool withLODScale) const;
+
+        virtual float getDistanceToViewPoint(const osg::Vec3& pos, bool withLODScale) const;
+
+        virtual void apply(osg::Node&);
+        virtual void apply(osg::Geode& node);
+        virtual void apply(osg::Billboard& node);
+        virtual void apply(osg::LightSource& node);
+        virtual void apply(osg::ClipNode& node);
+        virtual void apply(osg::TexGenNode& node);
+
+        virtual void apply(osg::Group& node);
+        virtual void apply(osg::Transform& node);
+        virtual void apply(osg::Projection& node);
+        virtual void apply(osg::Switch& node);
+        virtual void apply(osg::LOD& node);
+        virtual void apply(osg::ClearNode& node);
+        virtual void apply(osg::Camera& node);
+        virtual void apply(osg::OccluderNode& node);
+        virtual void apply(osg::OcclusionQueryNode& node);
+
+        /** Push state set on the current state group.
+          * If the state exists in a child state group of the current
+          * state group then move the current state group to that child.
+          * Otherwise, create a new state group for the state set, add
+          * it to the current state group then move the current state
+          * group pointer to the new state group.
+          */
+        inline void pushStateSet(const osg::StateSet* ss)
+        {
+            _currentStateGraph = _currentStateGraph->find_or_insert(ss);
+
+            if (_numberOfEncloseOverrideRenderBinDetails==0 && ss->useRenderBinDetails() && !ss->getBinName().empty())
+            {
+                _renderBinStack.push_back(_currentRenderBin);
+
+                _currentRenderBin = ss->getNestRenderBins() ?
+                    _currentRenderBin->find_or_insert(ss->getBinNumber(),ss->getBinName()) :
+                    _currentRenderBin->getStage()->find_or_insert(ss->getBinNumber(),ss->getBinName());
+            }
+
+            if (ss->getRenderBinMode()==osg::StateSet::OVERRIDE_RENDERBIN_DETAILS)
+            {
+                ++_numberOfEncloseOverrideRenderBinDetails;
+            }
+        }
+        
+        /** Pop the top state set and hence associated state group.
+          * Move the current state group to the parent of the popped
+          * state group.
+          */
+        inline void popStateSet()
+        {
+            const osg::StateSet* ss = _currentStateGraph->getStateSet();
+            if (ss->getRenderBinMode()==osg::StateSet::OVERRIDE_RENDERBIN_DETAILS)
+            {
+                --_numberOfEncloseOverrideRenderBinDetails;
+            }
+            if (_numberOfEncloseOverrideRenderBinDetails==0 && ss->useRenderBinDetails() && !ss->getBinName().empty())
+            {
+                if (_renderBinStack.empty())
+                {
+                    _currentRenderBin = _currentRenderBin->getStage();
+                }
+                else
+                {
+                    _currentRenderBin = _renderBinStack.back();
+                    _renderBinStack.pop_back();
+                }
+            }
+            _currentStateGraph = _currentStateGraph->_parent;
+        }
+        
+        inline void setStateGraph(StateGraph* rg)
+        {
+            _rootStateGraph = rg;
+            _currentStateGraph = rg;
+        }
+
+        inline StateGraph* getRootStateGraph()
+        {
+            return _rootStateGraph.get();
+        }
+
+        inline StateGraph* getCurrentStateGraph()
+        {
+            return _currentStateGraph;
+        }
+
+        inline void setRenderStage(RenderStage* rg)
+        {
+            _rootRenderStage = rg;
+            _currentRenderBin = rg;
+        }
+
+        inline RenderStage* getRenderStage()
+        {
+            return _rootRenderStage.get();
+        }
+
+        inline RenderStage* getCurrentRenderStage()
+        {
+            return _currentRenderBin->getStage();
+        }
+
+        inline osg::Camera* getCurrentCamera()
+        {
+            return getCurrentRenderStage()->getCamera();
+        }
+
+        inline RenderBin* getCurrentRenderBin()
+        {
+            return _currentRenderBin;
+        }
+
+        inline void setCurrentRenderBin(RenderBin* rb)
+        {
+            _currentRenderBin = rb;
+        }
+
+        inline value_type getCalculatedNearPlane() const { return _computed_znear; }
+        
+        inline value_type getCalculatedFarPlane() const { return _computed_zfar; }
+
+        value_type computeNearestPointInFrustum(const osg::Matrix& matrix, const osg::Polytope::PlaneList& planes,const osg::Drawable& drawable);
+
+        bool updateCalculatedNearFar(const osg::Matrix& matrix,const osg::BoundingBox& bb);
+
+        bool updateCalculatedNearFar(const osg::Matrix& matrix,const osg::Drawable& drawable, bool isBillboard=false);
+        
+        void updateCalculatedNearFar(const osg::Vec3& pos);
+        
+        /** Add a drawable to current render graph.*/
+        inline void addDrawable(osg::Drawable* drawable,osg::RefMatrix* matrix);
+
+        /** Add a drawable and depth to current render graph.*/
+        inline void addDrawableAndDepth(osg::Drawable* drawable,osg::RefMatrix* matrix,float depth);
+
+        /** Add an attribute which is positioned relative to the modelview matrix.*/
+        inline void addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr);
+
+        /** Add an attribute which is positioned relative to the modelview matrix.*/
+        inline void addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr);
+
+
+        /** compute near plane based on the polgon intersection of primtives in near plane candidate list of drawables.
+          * Note, you have to set ComputeNearFarMode to COMPUTE_NEAR_FAR_USING_PRIMITIVES to be able to near plane candidate drawables to be recorded by the cull traversal. */ 
+        void computeNearPlane();
+
+        /** Re-implement CullStack's popProjectionMatrix() adding clamping of the projection matrix to
+          * the computed near and far.*/
+        virtual void popProjectionMatrix();
+        
+
+        /** CullVisitor's default clamping of the projection float matrix to computed near and far values.
+          * Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback.*/
+        virtual bool clampProjectionMatrixImplementation(osg::Matrixf& projection, double& znear, double& zfar) const;
+
+        /** CullVisitor's default clamping of the projection double matrix to computed near and far values.
+          * Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback.*/
+        virtual bool clampProjectionMatrixImplementation(osg::Matrixd& projection, double& znear, double& zfar) const;
+
+        /** Clamp the projection float matrix to computed near and far values, use callback if it exists,
+          * otherwise use default CullVisitor implementation.*/
+        inline bool clampProjectionMatrix(osg::Matrixf& projection, value_type& znear, value_type& zfar) const
+        {
+            double zn = znear;
+            double zf = zfar;
+            bool result = false;
+            if (_clampProjectionMatrixCallback.valid()) result = _clampProjectionMatrixCallback->clampProjectionMatrixImplementation(projection, zn, zf);
+            else result = clampProjectionMatrixImplementation(projection, zn, zf);
+
+            if (result)
+            {
+                znear = zn;
+                zfar = zf;
+                return true;
+            }
+            else 
+                return false;
+        }
+
+        /** Clamp the projection double matrix to computed near and far values, use callback if it exists,
+          * otherwise use default CullVisitor implementation.*/
+        inline bool clampProjectionMatrix(osg::Matrixd& projection, value_type& znear, value_type& zfar) const
+        {
+            double zn = znear;
+            double zf = zfar;
+            bool result = false;
+
+            if (_clampProjectionMatrixCallback.valid()) result = _clampProjectionMatrixCallback->clampProjectionMatrixImplementation(projection, zn, zf);
+            else result = clampProjectionMatrixImplementation(projection, zn, zf);
+
+            if (result)
+            {
+                znear = zn;
+                zfar = zf;
+                return true;
+            }
+            else 
+                return false;
+        }
+        
+
+        void setState(osg::State* state) { _renderInfo.setState(state); }
+        osg::State* getState() { return _renderInfo.getState(); }
+        const osg::State* getState() const { return _renderInfo.getState(); }
+
+        void setRenderInfo(osg::RenderInfo& renderInfo) { _renderInfo = renderInfo; }
+        osg::RenderInfo& getRenderInfo() { return _renderInfo; }
+        const osg::RenderInfo& getRenderInfo() const { return _renderInfo; }
+
+    protected:
+
+        virtual ~CullVisitor();
+
+        /** Prevent unwanted copy operator.*/
+        CullVisitor& operator = (const CullVisitor&) { return *this; }
+        
+        inline void handle_cull_callbacks_and_traverse(osg::Node& node)
+        {
+            osg::NodeCallback* callback = node.getCullCallback();
+            if (callback) (*callback)(&node,this);
+            else traverse(node);
+        }
+
+        inline void handle_cull_callbacks_and_accept(osg::Node& node,osg::Node* acceptNode)
+        {
+            osg::NodeCallback* callback = node.getCullCallback();
+            if (callback) (*callback)(&node,this);
+            else acceptNode->accept(*this);
+        }
+
+        osg::ref_ptr<StateGraph>                                   _rootStateGraph;
+        StateGraph*                                                _currentStateGraph;
+
+        osg::ref_ptr<RenderStage>                                   _rootRenderStage;        
+        RenderBin*                                                  _currentRenderBin;
+        std::vector<RenderBin*>                                     _renderBinStack;
+
+
+        value_type               _computed_znear;
+        value_type               _computed_zfar;
+        
+        
+        typedef std::vector< osg::ref_ptr<RenderLeaf> > RenderLeafList;
+        RenderLeafList _reuseRenderLeafList;
+        unsigned int _currentReuseRenderLeafIndex;
+    
+        inline RenderLeaf* createOrReuseRenderLeaf(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* matrix, float depth=0.0f);
+        
+        unsigned int _numberOfEncloseOverrideRenderBinDetails;
+
+        osg::RenderInfo         _renderInfo;
+
+
+        struct MatrixPlanesDrawables
+        {
+            MatrixPlanesDrawables(const osg::Matrix& matrix, const osg::Drawable* drawable, const osg::Polytope& frustum):
+                _matrix(matrix),
+                _drawable(drawable)
+            {
+                // create a new list of planes from the active walls of the frustum.
+                osg::Polytope::ClippingMask result_mask = frustum.getResultMask();
+                osg::Polytope::ClippingMask selector_mask = 0x1;
+                for(osg::Polytope::PlaneList::const_iterator itr=frustum.getPlaneList().begin();
+                    itr!=frustum.getPlaneList().end();
+                    ++itr)
+                {
+                    if (result_mask&selector_mask) _planes.push_back(*itr);
+                    selector_mask <<= 1; 
+                }
+            }
+            
+            MatrixPlanesDrawables(const MatrixPlanesDrawables& mpd):
+                _matrix(mpd._matrix),
+                _drawable(mpd._drawable),
+                _planes(mpd._planes) {}
+                
+            MatrixPlanesDrawables& operator = (const MatrixPlanesDrawables& mpd)
+            {
+                _matrix = mpd._matrix;
+                _drawable = mpd._drawable;
+                _planes = mpd._planes;
+                return *this;
+            }
+            
+            osg::Matrix                 _matrix;
+            const osg::Drawable*        _drawable;
+            osg::Polytope::PlaneList    _planes;
+        };
+        
+        typedef std::multimap<value_type, MatrixPlanesDrawables>   DistanceMatrixDrawableMap;
+        DistanceMatrixDrawableMap                                  _nearPlaneCandidateMap;
+    
+};
+
+inline void CullVisitor::addDrawable(osg::Drawable* drawable,osg::RefMatrix* matrix)
+{
+    if (_currentStateGraph->leaves_empty())
+    {
+        // this is first leaf to be added to StateGraph
+        // and therefore should not already know to current render bin,
+        // so need to add it.
+        _currentRenderBin->addStateGraph(_currentStateGraph);
+    }
+    //_currentStateGraph->addLeaf(new RenderLeaf(drawable,matrix));
+    _currentStateGraph->addLeaf(createOrReuseRenderLeaf(drawable,_projectionStack.back().get(),matrix));
+}
+
+/** Add a drawable and depth to current render graph.*/
+inline void CullVisitor::addDrawableAndDepth(osg::Drawable* drawable,osg::RefMatrix* matrix,float depth)
+{
+    if (_currentStateGraph->leaves_empty())
+    {
+        // this is first leaf to be added to StateGraph
+        // and therefore should not already know to current render bin,
+        // so need to add it.
+        _currentRenderBin->addStateGraph(_currentStateGraph);
+    }
+    //_currentStateGraph->addLeaf(new RenderLeaf(drawable,matrix,depth));
+    _currentStateGraph->addLeaf(createOrReuseRenderLeaf(drawable,_projectionStack.back().get(),matrix,depth));
+}
+
+/** Add an attribute which is positioned relative to the modelview matrix.*/
+inline void CullVisitor::addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+{
+    _currentRenderBin->getStage()->addPositionedAttribute(matrix,attr);
+}
+
+/** Add an attribute which is positioned relative to the modelview matrix.*/
+inline void CullVisitor::addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+{
+    _currentRenderBin->getStage()->addPositionedTextureAttribute(textureUnit,matrix,attr);
+}
+
+inline RenderLeaf* CullVisitor::createOrReuseRenderLeaf(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* matrix, float depth)
+{
+    // Skips any already reused renderleaf.
+    while (_currentReuseRenderLeafIndex<_reuseRenderLeafList.size() && 
+           _reuseRenderLeafList[_currentReuseRenderLeafIndex]->referenceCount()>1)
+    {
+        osg::notify(osg::NOTICE)<<"Warning:createOrReuseRenderLeaf() skipping multiply refrenced entry."<< std::endl;
+        ++_currentReuseRenderLeafIndex;
+    }
+
+    // If still within list, element must be singularly referenced then return it to be reused.
+    if (_currentReuseRenderLeafIndex<_reuseRenderLeafList.size())
+    {
+        RenderLeaf* renderleaf = _reuseRenderLeafList[_currentReuseRenderLeafIndex++].get();
+        renderleaf->set(drawable,projection,matrix,depth);
+        return renderleaf;
+    }
+
+    // Otherwise need to create new renderleaf.
+    RenderLeaf* renderleaf = new RenderLeaf(drawable,projection,matrix,depth);
+    _reuseRenderLeafList.push_back(renderleaf);
+    ++_currentReuseRenderLeafIndex;
+    return renderleaf;
+}
+
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectVisitor (revision 10101)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectVisitor (revision 10101)
@@ -0,0 +1,228 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_INTERSECTVISITOR
+#define OSGUTIL_INTERSECTVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/LineSegment>
+#include <osg/Geode>
+#include <osg/Matrix>
+#include <osg/Transform>
+
+#include <osgUtil/Export>
+
+#include <map>
+#include <set>
+#include <vector>
+
+namespace osgUtil {
+
+
+class OSGUTIL_EXPORT Hit
+{ 
+    /** Deprecated */
+    public:
+
+        Hit();
+        Hit(const Hit& hit);
+        ~Hit();
+        
+        Hit& operator = (const Hit& hit);
+        
+        typedef std::vector<int> VecIndexList;
+
+        bool operator < (const Hit& hit) const
+        {
+            if (_originalLineSegment<hit._originalLineSegment) return true;
+            if (hit._originalLineSegment<_originalLineSegment) return false;
+            return _ratio<hit._ratio;
+        }
+        
+        
+        const osg::Vec3& getLocalIntersectPoint() const { return _intersectPoint; }
+        const osg::Vec3& getLocalIntersectNormal() const { return _intersectNormal; }
+        
+        const osg::Vec3 getWorldIntersectPoint() const { if (_matrix.valid()) return _intersectPoint*(*_matrix); else return _intersectPoint; }
+        const osg::Vec3 getWorldIntersectNormal() const ;
+
+        float getRatio() const { return _ratio; }
+        const osg::LineSegment* getOriginalLineSegment() const { return _originalLineSegment.get(); }
+        const osg::LineSegment* getLocalLineSegment() const { return _localLineSegment.get(); }
+        osg::NodePath& getNodePath() { return _nodePath; }
+        const osg::NodePath& getNodePath() const { return _nodePath; }
+        osg::Geode* getGeode() { return _geode.get(); }
+        const osg::Geode* getGeode() const { return _geode.get(); }
+        osg::Drawable* getDrawable() { return _drawable.get(); }
+        const osg::Drawable* getDrawable() const { return _drawable.get(); }
+        const osg::RefMatrix* getMatrix() const { return _matrix.get(); }
+        const osg::RefMatrix* getInverseMatrix() const { return _inverse.get(); }
+        const VecIndexList& getVecIndexList() const { return _vecIndexList; }
+        int getPrimitiveIndex() const { return _primitiveIndex; }
+        
+        
+        float                           _ratio;
+        osg::ref_ptr<osg::LineSegment>  _originalLineSegment;
+        osg::ref_ptr<osg::LineSegment>  _localLineSegment;
+        osg::NodePath                   _nodePath;
+        osg::ref_ptr<osg::Geode>        _geode;
+        osg::ref_ptr<osg::Drawable>     _drawable;
+        osg::ref_ptr<osg::RefMatrix>    _matrix;
+        osg::ref_ptr<osg::RefMatrix>    _inverse;
+        
+        VecIndexList                    _vecIndexList;
+        int                             _primitiveIndex;
+        osg::Vec3                       _intersectPoint;
+        osg::Vec3                       _intersectNormal;
+
+
+};
+
+
+/** Deprecated - use IntersectionVisitor instead.*/
+class OSGUTIL_EXPORT IntersectVisitor : public osg::NodeVisitor
+{
+    public:
+
+        IntersectVisitor();
+        virtual ~IntersectVisitor();
+
+        META_NodeVisitor("osgUtil","IntersectVisitor")
+
+        void reset();
+        
+        /** Add a line segment to use for intersection testing during scene traversal.
+          * Note, a maximum of 32 line segments can be added to a IntersectVistor,
+          * adding more than this will result in warning being emitted to the console
+          * and the excess segments being ignored.*/
+        void addLineSegment(osg::LineSegment* seg);
+
+        typedef std::vector<Hit> HitList;
+        typedef std::map<const osg::LineSegment*,HitList > LineSegmentHitListMap;
+
+        HitList& getHitList(const osg::LineSegment* seg) { return _segHitList[seg]; }
+
+        int getNumHits(const osg::LineSegment* seg) { return _segHitList[seg].size(); }
+        
+        LineSegmentHitListMap& getSegHitList() { return _segHitList; }
+
+        bool hits();
+
+        enum LODSelectionMode
+        {
+            USE_HIGHEST_LEVEL_OF_DETAIL,
+            USE_SEGMENT_START_POINT_AS_EYE_POINT_FOR_LOD_LEVEL_SELECTION
+        };
+        
+        void setLODSelectionMode(LODSelectionMode mode) { _lodSelectionMode = mode; }
+        LODSelectionMode getLODSelectionMode() const { return _lodSelectionMode; }
+
+        /** Set the eye point in local coordinates.
+          * This is a pseudo-EyePoint for billboarding and LOD purposes.
+          * It is copied from the Start point of the most-recently-added segment
+          * of the intersection ray set (IntersectState::_segList). */
+        void setEyePoint(const osg::Vec3& eye) { _pseudoEyePoint = eye; }
+
+        virtual osg::Vec3 getEyePoint() const;
+
+
+        /** Get the distance from a point to the eye point, distance value in local coordinate system.
+          * This is calculated using the pseudo-EyePoint (above) when doing LOD calculcations. */
+        virtual float getDistanceToEyePoint(const osg::Vec3& pos, bool withLODScale) const;
+
+        virtual void apply(osg::Node&);
+        virtual void apply(osg::Geode& node);
+        virtual void apply(osg::Billboard& node);
+
+        virtual void apply(osg::Group& node);
+        virtual void apply(osg::Transform& node);
+        virtual void apply(osg::Switch& node);
+        virtual void apply(osg::LOD& node);
+
+    protected:
+
+        class IntersectState : public osg::Referenced
+        {
+            public:
+
+                IntersectState();
+
+                osg::ref_ptr<osg::RefMatrix> _view_matrix;
+                osg::ref_ptr<osg::RefMatrix> _view_inverse;
+                osg::ref_ptr<osg::RefMatrix> _model_matrix;
+                osg::ref_ptr<osg::RefMatrix> _model_inverse;
+
+                typedef std::pair<osg::ref_ptr<osg::LineSegment>,osg::ref_ptr<osg::LineSegment> >   LineSegmentPair;
+                typedef std::vector< LineSegmentPair >                                              LineSegmentList;
+                LineSegmentList _segList;
+
+                typedef unsigned int LineSegmentMask;
+                typedef std::vector<LineSegmentMask> LineSegmentMaskStack;
+                LineSegmentMaskStack _segmentMaskStack;
+
+                bool isCulled(const osg::BoundingSphere& bs,LineSegmentMask& segMaskOut);
+                bool isCulled(const osg::BoundingBox& bb,LineSegmentMask& segMaskOut);
+
+                void addLineSegment(osg::LineSegment* seg);
+
+            protected:
+
+                ~IntersectState();
+
+        };
+
+        bool intersect(osg::Drawable& gset);
+
+        void pushMatrix(osg::RefMatrix* matrix, osg::Transform::ReferenceFrame rf);
+        void popMatrix();
+
+        bool enterNode(osg::Node& node);
+        void leaveNode();
+
+        typedef std::vector<osg::ref_ptr<IntersectState> > IntersectStateStack;
+        
+        IntersectStateStack         _intersectStateStack;
+
+        LineSegmentHitListMap       _segHitList;
+        
+        LODSelectionMode            _lodSelectionMode;
+        osg::Vec3                   _pseudoEyePoint;
+};
+
+/** Picking intersection visitor specialises the IntersectVistor to allow more convinient handling of mouse picking.*/
+class OSGUTIL_EXPORT PickVisitor : public osgUtil::IntersectVisitor
+{
+    public:
+
+        PickVisitor(const osg::Viewport* viewport, const osg::Matrixd& proj, const osg::Matrixd& view, float mx, float my);
+
+        void runNestedPickVisitor(osg::Node& node, const osg::Viewport* viewport, const osg::Matrix& proj, const osg::Matrix& view, float mx, float my);
+
+        void apply(osg::Projection& projection);
+
+        void apply(osg::Camera& camera);
+
+    protected:
+        
+        float _mx;
+        float _my;
+
+        osg::ref_ptr<const osg::Viewport>   _lastViewport;
+        osg::Matrixd                        _lastProjectionMatrix;
+        osg::Matrixd                        _lastViewMatrix;
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PlaneIntersector
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PlaneIntersector (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PlaneIntersector (revision 7648)
@@ -0,0 +1,108 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_PLANEINTERSECTOR
+#define OSGUTIL_PLANEINTERSECTOR 1
+
+#include <osgUtil/IntersectionVisitor>
+
+#include <osg/CoordinateSystemNode>
+
+namespace osgUtil
+{
+
+/** Concrete class for implementing polytope intersections with the scene graph.
+  * To be used in conjunction with IntersectionVisitor. */
+class OSGUTIL_EXPORT PlaneIntersector : public Intersector
+{
+    public:
+    
+        /** Construct a PolytopeIntersector using speified polytope in MODEL coordinates.*/
+        PlaneIntersector(const osg::Plane& plane, const osg::Polytope& boundingPolytope=osg::Polytope());
+        
+        /** Construct a PolytopeIntersector using speified polytope in specified coordinate frame.*/
+        PlaneIntersector(CoordinateFrame cf, const osg::Plane& plane, const osg::Polytope& boundingPolytope=osg::Polytope());
+
+        struct Intersection
+        {
+            Intersection() {}
+        
+            bool operator < (const Intersection& rhs) const
+            {
+                if (polyline < rhs.polyline) return true;
+                if (rhs.polyline < polyline) return false;
+                
+                if (nodePath < rhs.nodePath) return true;
+                if (rhs.nodePath < nodePath ) return false;
+                
+                return (drawable < rhs.drawable);
+            }
+
+            typedef std::vector<osg::Vec3d> Polyline;
+            typedef std::vector<double> Attributes;
+
+            osg::NodePath                   nodePath;
+            osg::ref_ptr<osg::RefMatrix>    matrix;
+            osg::ref_ptr<osg::Drawable>     drawable;
+            Polyline                        polyline;
+            Attributes                      attributes;
+            
+        };
+        
+        typedef std::vector<Intersection> Intersections;
+        
+        inline void insertIntersection(const Intersection& intersection) { getIntersections().push_back(intersection); }
+
+        inline Intersections& getIntersections() { return _parent ? _parent->_intersections : _intersections; }
+
+        
+        void setRecordHeightsAsAttributes(bool flag) { _recordHeightsAsAttributes = flag; }
+        
+        bool getRecordHeightsAsAttributes() const { return _recordHeightsAsAttributes; }
+
+        void setEllipsoidModel(osg::EllipsoidModel* em) { _em = em; }
+        
+        const osg::EllipsoidModel* getEllipsoidModel() const { return _em.get(); }
+
+    public:
+
+        virtual Intersector* clone(osgUtil::IntersectionVisitor& iv);
+        
+        virtual bool enter(const osg::Node& node);
+        
+        virtual void leave();
+        
+        virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable);
+        
+        virtual void reset();
+
+        virtual bool containsIntersections() { return !_intersections.empty(); }
+
+    protected:
+
+        PlaneIntersector*                   _parent;
+        
+        bool                                _recordHeightsAsAttributes;
+        osg::ref_ptr<osg::EllipsoidModel>   _em;
+
+        osg::Plane                          _plane;
+        osg::Polytope                       _polytope;
+        
+        Intersections                       _intersections;
+    
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TangentSpaceGenerator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TangentSpaceGenerator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TangentSpaceGenerator (revision 5328)
@@ -0,0 +1,78 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_TANGENTSPACEGENERATOR_
+#define OSGUTIL_TANGENTSPACEGENERATOR_
+
+#include <osgUtil/Export>
+
+#include <osg/ref_ptr>
+#include <osg/Referenced>
+#include <osg/Array>
+#include <osg/Geometry>
+
+namespace osgUtil
+{
+
+/**
+ The TangentSpaceGenerator class generates three arrays containing tangent-space basis vectors.
+ It takes a texture-mapped Geometry object as input, traverses its primitive sets and computes
+ Tangent, Normal and Binormal vectors for each vertex, storing them into arrays.
+ The resulting arrays can be used as vertex program varying (per-vertex) parameters,
+ enabling advanced effects like bump-mapping.
+ To use this class, simply call the generate() method specifying the Geometry object
+ you want to process and the texture unit that contains UV mapping for the normal map;
+ then you can retrieve the TBN arrays by calling getTangentArray(), getNormalArray()
+ and getBinormalArray() methods.
+ */
+class OSGUTIL_EXPORT TangentSpaceGenerator: public osg::Referenced {
+public:
+    TangentSpaceGenerator();
+    TangentSpaceGenerator(const TangentSpaceGenerator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY);
+
+    void generate(osg::Geometry *geo, int normal_map_tex_unit = 0);
+
+    inline osg::Vec4Array *getTangentArray()               { return T_.get(); }
+    inline const osg::Vec4Array *getTangentArray() const   { return T_.get(); }
+    inline void setTangentArray(osg::Vec4Array *array)     { T_ = array; }
+
+    inline osg::Vec4Array *getNormalArray()                { return N_.get(); }
+    inline const osg::Vec4Array *getNormalArray() const    { return N_.get(); }
+    inline void setNormalArray(osg::Vec4Array *array)      { N_ = array; }
+
+    inline osg::Vec4Array *getBinormalArray()              { return B_.get(); }
+    inline const osg::Vec4Array *getBinormalArray() const  { return B_.get(); }
+    inline void setBinormalArray(osg::Vec4Array *array)    { B_ = array; }
+
+    inline osg::IndexArray *getIndices() { return indices_.get(); }
+
+protected:
+
+    virtual ~TangentSpaceGenerator() {}
+    TangentSpaceGenerator &operator=(const TangentSpaceGenerator &) { return *this; }
+
+    void compute(osg::PrimitiveSet *pset,
+                 const osg::Array *vx,
+                 const osg::Array *nx,
+                 const osg::Array *tx,
+                 int iA, int iB, int iC);
+
+    osg::ref_ptr<osg::Vec4Array> T_;
+    osg::ref_ptr<osg::Vec4Array> B_;
+    osg::ref_ptr<osg::Vec4Array> N_;
+    osg::ref_ptr<osg::UIntArray> indices_;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CubeMapGenerator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CubeMapGenerator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/CubeMapGenerator (revision 5328)
@@ -0,0 +1,121 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+#ifndef OSGUTIL_CUBEMAPGENERATOR_
+#define OSGUTIL_CUBEMAPGENERATOR_
+
+#include <osgUtil/Export>
+
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/CopyOp>
+#include <osg/Referenced>
+#include <osg/TextureCubeMap>
+#include <osg/Image>
+#include <osg/Notify>
+
+#include <vector>
+
+namespace osgUtil
+{
+
+    /** This is the base class for cube map generators. 
+        It exposes the necessary interface to access the six generated images;
+        descendants should only override the compute_color() method.
+    */
+    class OSGUTIL_EXPORT CubeMapGenerator: public osg::Referenced {
+    public:
+        explicit CubeMapGenerator(int texture_size = 64);
+        CubeMapGenerator(const CubeMapGenerator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY);
+
+        inline osg::Image *getImage(osg::TextureCubeMap::Face face);
+        inline const osg::Image *getImage(osg::TextureCubeMap::Face face) const;
+
+        /** Generate the six cube images. 
+            If use_osg_system is true, then the OSG's coordinate system is used instead 
+            of the default OpenGL one.
+        */
+        void generateMap(bool use_osg_system = true);
+
+    protected:
+        virtual ~CubeMapGenerator() {}
+        CubeMapGenerator &operator=(const CubeMapGenerator &) { return *this; }
+
+        inline void set_pixel(int index, int c, int r, const osg::Vec4 &color);
+        inline static osg::Vec4 vector_to_color(const osg::Vec3 &vec);        
+
+        /** Override this method to define how colors are computed. 
+            The parameter R is the reflection vector, pointing from the center of the cube.
+            The return value should be the RGBA color associated with that reflection ray.
+        */
+        virtual osg::Vec4 compute_color(const osg::Vec3 &R) const = 0;
+
+    private:
+        int texture_size_;
+
+        typedef std::vector<osg::ref_ptr<osg::Image> > Image_list;
+        Image_list images_;        
+    };
+
+    // INLINE METHODS
+
+    inline osg::Image *CubeMapGenerator::getImage(osg::TextureCubeMap::Face face)
+    {
+        switch (face) {
+            case osg::TextureCubeMap::POSITIVE_X: return images_[0].get();
+            case osg::TextureCubeMap::NEGATIVE_X: return images_[1].get();
+            case osg::TextureCubeMap::POSITIVE_Y: return images_[2].get();
+            case osg::TextureCubeMap::NEGATIVE_Y: return images_[3].get();
+            case osg::TextureCubeMap::POSITIVE_Z: return images_[4].get();
+            case osg::TextureCubeMap::NEGATIVE_Z: return images_[5].get();            
+            default: return 0;
+        }
+    }
+
+    inline const osg::Image *CubeMapGenerator::getImage(osg::TextureCubeMap::Face face) const
+    {
+        switch (face) {
+            case osg::TextureCubeMap::POSITIVE_X: return images_[0].get();
+            case osg::TextureCubeMap::NEGATIVE_X: return images_[1].get();
+            case osg::TextureCubeMap::POSITIVE_Y: return images_[2].get();
+            case osg::TextureCubeMap::NEGATIVE_Y: return images_[3].get();
+            case osg::TextureCubeMap::POSITIVE_Z: return images_[4].get();
+            case osg::TextureCubeMap::NEGATIVE_Z: return images_[5].get();            
+            default: return 0;
+        }
+    }
+
+    inline void CubeMapGenerator::set_pixel(int index, int c, int r, const osg::Vec4 &color)
+    {
+        osg::Image *i = images_[index].get();
+        if (i) {
+            *(i->data(c, r)+0) = static_cast<unsigned char>(osg::clampBetween(color.x(),0.0f,1.0f) * 255);
+            *(i->data(c, r)+1) = static_cast<unsigned char>(osg::clampBetween(color.y(),0.0f,1.0f) * 255);
+            *(i->data(c, r)+2) = static_cast<unsigned char>(osg::clampBetween(color.z(),0.0f,1.0f) * 255);
+            *(i->data(c, r)+3) = static_cast<unsigned char>(osg::clampBetween(color.w(),0.0f,1.0f) * 255);            
+        } else {
+            osg::notify(osg::WARN) << "Warning: CubeMapGenerator::set_pixel(): invalid image index\n";
+        }
+    }
+
+    inline osg::Vec4 CubeMapGenerator::vector_to_color(const osg::Vec3 &vec)
+    {
+        return osg::Vec4(
+            vec.x() / vec.length() / 2 + 0.5f,
+            vec.y() / vec.length() / 2 + 0.5f,
+            vec.z() / vec.length() / 2 + 0.5f,
+            1);
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Version
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Version (revision 7365)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Version (revision 7365)
@@ -0,0 +1,48 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_VERSION
+#define OSGUTIL_VERSION 1
+
+#include <osgUtil/Export>
+
+
+extern "C" {
+
+/**
+ * osgUtilGetVersion() returns the library version number.
+ * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgUtilGetVersion.
+ *
+ * This C function can be also used to check for the existence of the OpenSceneGraph
+ * library using autoconf and its m4 macro AC_CHECK_LIB.
+ *
+ * Here is the code to add to your configure.in:
+ \verbatim
+ #
+ # Check for the OpenSceneGraph (OSG) Util library
+ #
+ AC_CHECK_LIB(osg, osgUtilGetVersion, ,
+    [AC_MSG_ERROR(OpenSceneGraph Util library not found. See http://www.openscenegraph.org)],)
+ \endverbatim
+*/
+extern OSGUTIL_EXPORT const char* osgUtilGetVersion();
+
+/**
+ * osgUtilGetLibraryName() returns the library name in human friendly form.
+ */
+extern OSGUTIL_EXPORT const char* osgUtilGetLibraryName();
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneGraphBuilder
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneGraphBuilder (revision 7942)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneGraphBuilder (revision 7942)
@@ -0,0 +1,186 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_SCENEGRAPHBUILDER
+#define OSGUTIL_SCENEGRAPHBUILDER 1
+
+#include <osg/Geode>
+#include <osg/Geometry>
+#include <osg/MatrixTransform>
+#include <osg/GLU>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** A class for assisting the building ascene graphs that is equivilant to OpenGL 1.0 style calls.
+  */
+class OSGUTIL_EXPORT SceneGraphBuilder
+{
+    public:
+
+        SceneGraphBuilder();
+
+        // 
+        //  OpenGL 1.0 style building methods
+        //
+        void PushMatrix();
+        void PopMatrix();
+        void LoadIdentity();
+        void LoadMatrixd(const GLdouble* m);
+        void MultMatrixd(const GLdouble* m);
+        void Translated(GLdouble x, GLdouble y, GLdouble z);
+        void Scaled(GLdouble x, GLdouble y, GLdouble z);
+        void Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+        
+        void BlendFunc(GLenum srcFactor, GLenum dstFactor);
+        void CullFace(GLenum mode);
+        void DepthFunc(GLenum mode);
+        void FrontFace(GLenum mode);
+        void LineStipple(GLint factor, GLushort pattern);
+        void LineWidth(GLfloat lineWidth);
+        void PointSize(GLfloat pointSize);
+        void PolygonMode(GLenum face, GLenum mode);
+        void PolygonOffset(GLfloat factor, GLfloat units);
+        void PolygonStipple(const GLubyte* mask);
+        void ShadeModel(GLenum mode);
+        
+        void Enable(GLenum mode);
+        void Disable(GLenum mode);
+        
+        void Color4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+        void Color4fv(GLfloat* c) { Color4f(c[0], c[1], c[2], c[3]); }
+
+        void Vertex3f(GLfloat x, GLfloat y, GLfloat z);
+        void Vertex3fv(GLfloat* v) { Vertex3f(v[0], v[1], v[2]); }
+
+        void Normal3f(GLfloat x, GLfloat y, GLfloat z);
+        void Normal3fv(GLfloat* n) { Normal3f(n[0], n[1], n[2]); }
+
+        void TexCoord1f(GLfloat x);
+        void TexCoord1fv(GLfloat* tc) { TexCoord1f(tc[0]); }
+
+        void TexCoord2f(GLfloat x, GLfloat y);
+        void TexCoord2fv(GLfloat* tc) { TexCoord2f(tc[0],tc[1]); }
+
+        void TexCoord3f(GLfloat x, GLfloat y, GLfloat z);
+        void TexCoord3fv(GLfloat* tc) { TexCoord3f(tc[0], tc[1], tc[2]); }
+
+        void TexCoord4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+        void TexCoord4fv(GLfloat* tc) { TexCoord4f(tc[0], tc[1], tc[2], tc[3]); }
+
+        void Begin(GLenum mode);
+        void End();
+
+        //
+        // glu style building methods
+        //
+        void QuadricDrawStyle(GLenum aDrawStyle);
+        void QuadricNormals(GLenum aNormals);
+        void QuadricOrientation(GLenum aOrientation);
+        void QuadricTexture(GLboolean aTexture);
+
+        void Cylinder(GLfloat base,
+                      GLfloat top,
+                      GLfloat height,
+                      GLint slices,
+                      GLint stacks);
+
+       void Disk(GLfloat inner,
+                 GLfloat outer,
+                 GLint slices,
+                 GLint loops);
+
+       void PartialDisk(GLfloat inner,
+                        GLfloat outer,
+                        GLint slices,
+                        GLint loops,
+                        GLfloat start,
+                        GLfloat sweep);
+
+       void Sphere(GLfloat radius,
+                   GLint slices,
+                   GLint stacks);
+
+
+        //
+        // methods for obtaining the built scene graph
+        //
+        osg::Node* getScene();
+        osg::Node* takeScene();
+
+    protected:
+    
+        typedef std::vector<osg::Matrixd> Matrices;
+
+        void matrixChanged();
+        void addAttribute(osg::StateAttribute* attribute);
+        void addMode(GLenum mode, bool enabled);                
+        void addTextureAttribute(unsigned int unit, osg::StateAttribute* attribute);
+        void addTextureMode(unsigned int unit, GLenum mode, bool enabled);                
+        void addShape(osg::Shape* shape);
+        void addDrawable(osg::Drawable* drawable);
+        void newGeometry();
+        
+        void allocateGeometry();
+        void completeGeometry();
+        
+        void allocateStateSet();
+        
+        Matrices                            _matrixStack;
+        osg::ref_ptr<osg::StateSet>         _stateset;
+        bool                                _statesetAssigned;
+        
+        bool                                _normalSet;
+        osg::Vec3f                          _normal;
+
+        bool                                _colorSet;
+        osg::Vec4f                          _color;
+
+        unsigned int                        _maxNumTexCoordComponents;
+        osg::Vec4f                          _texCoord;
+
+        GLenum                              _primitiveMode;        
+        osg::ref_ptr<osg::Vec3Array>        _vertices;
+        osg::ref_ptr<osg::Vec3Array>        _normals;
+        osg::ref_ptr<osg::Vec4Array>        _colors;
+        osg::ref_ptr<osg::Vec4Array>        _texCoords;
+    
+        struct QuadricState
+        {
+            QuadricState():
+                _drawStyle(GLU_FILL),
+                _normals(GLU_SMOOTH),
+                _orientation(GLU_OUTSIDE),
+                _texture(GLU_FALSE) {}
+
+            GLenum      _drawStyle;
+            GLenum      _normals;
+            GLenum      _orientation;
+            GLboolean   _texture;
+        };
+
+        QuadricState _quadricState;
+
+
+        osg::ref_ptr<osg::Geometry>         _geometry;
+        osg::ref_ptr<osg::Geode>            _geode;
+        osg::ref_ptr<osg::MatrixTransform>  _transform;
+        osg::ref_ptr<osg::Group>            _group;
+    
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectionVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectionVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/IntersectionVisitor (revision 9377)
@@ -0,0 +1,274 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_INTERSECTIONVISITOR
+#define OSGUTIL_INTERSECTIONVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Drawable>
+#include <osgUtil/Export>
+
+#include <list>
+
+namespace osgUtil
+{
+
+// forward declare to allow Intersector to reference it.
+class IntersectionVisitor;
+
+/** Pure virtual base class for implementing custom intersection technique.
+  * To implement a specific intersection technique on must override all
+  * the pure virtue methods, concrete examples of how to do this can be seen in
+  * the LineSegmentIntersector. */
+class Intersector : public osg::Referenced
+{
+    public:
+    
+        enum CoordinateFrame
+        {
+            WINDOW,
+            PROJECTION,
+            VIEW,
+            MODEL
+        };
+        
+        Intersector(CoordinateFrame cf=MODEL):
+            _coordinateFrame(cf),
+            _disabledCount(0) {}
+    
+    
+        void setCoordinateFrame(CoordinateFrame cf) { _coordinateFrame = cf; }
+        
+        CoordinateFrame getCoordinateFrame() const { return _coordinateFrame; }
+        
+        
+        virtual Intersector* clone(osgUtil::IntersectionVisitor& iv) = 0;
+        
+        virtual bool enter(const osg::Node& node) = 0;
+        
+        virtual void leave() = 0;
+        
+        virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable) = 0;
+        
+        virtual void reset() { _disabledCount = 0; }
+        
+        virtual bool containsIntersections() = 0;
+        
+        inline bool disabled() const { return _disabledCount!=0; }
+        
+        inline void incrementDisabledCount() { ++_disabledCount; }
+        
+        inline void decrementDisabledCount() { if (_disabledCount>0) --_disabledCount; }
+
+   protected:
+    
+        CoordinateFrame _coordinateFrame;
+        unsigned int    _disabledCount;
+
+};
+
+
+/** Concrete class for passing multiple intersectors through the scene graph.
+  * To be used in conjunction with IntersectionVisitor. */
+class OSGUTIL_EXPORT IntersectorGroup : public Intersector
+{
+    public:
+    
+        IntersectorGroup();
+
+        /** Add an Intersector. */
+        void addIntersector(Intersector* intersector);
+        
+        typedef std::vector< osg::ref_ptr<Intersector> > Intersectors;
+
+        /** Get the list of intersector. */
+        Intersectors& getIntersectors() { return _intersectors; }
+
+        /** Clear the list of intersectors.*/    
+        void clear();
+
+    public:
+
+        virtual Intersector* clone(osgUtil::IntersectionVisitor& iv);
+        
+        virtual bool enter(const osg::Node& node);
+        
+        virtual void leave();
+        
+        virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable);
+        
+        virtual void reset();
+
+        virtual bool containsIntersections();
+
+    protected:
+        
+        Intersectors _intersectors;
+    
+};
+
+/** InteresectionVisitor is used to testing for intersections with the scene, traversing the scene using generic osgUtil::Intersector's to test against the scene.
+  * To implement different types of intersection techniques, one implements custom versions of the osgUtil::Intersector, and then
+  * pass the constructed intersector to the IntersectionVisitor.*/
+class OSGUTIL_EXPORT IntersectionVisitor : public osg::NodeVisitor
+{
+    public:
+
+        /** Callback used to implement the reading of external files, allowing support for paged databases to be
+          * integrated with IntersectionVisitor.  A concrete implementation can be found in osgDB.
+          * Note, this loose coupling approach is required as osgUtil is independent from osgDB where the file reading
+          * is implemented, and osgDB itself is dependent upon osgUtil so a circular dependency would result from
+          * tighter integration.*/
+        struct ReadCallback : public osg::Referenced
+        {
+            virtual osg::Node* readNodeFile(const std::string& filename) = 0;
+        };
+
+
+        IntersectionVisitor(Intersector* intersector=0, ReadCallback* readCallback=0);
+        
+        META_NodeVisitor("osgUtil","IntersectionVisitor")
+
+        virtual void reset();
+
+
+        /** Set the intersector that will be used to intersect with the scene, and to store any hits that occur.*/
+        void setIntersector(Intersector* intersector);
+        
+        /** Get the intersector that will be used to intersect with the scene, and to store any hits that occur.*/
+        Intersector* getIntersector() { return _intersectorStack.empty() ? 0 : _intersectorStack.front().get(); }
+
+        /** Get the const intersector that will be used to intersect with the scene, and to store any hits that occur.*/
+        const Intersector* getIntersector() const { return _intersectorStack.empty() ? 0 : _intersectorStack.front().get(); }
+
+
+        /** Set whether the intersectors should use KdTrees when they are found on the scene graph.*/
+        void setUseKdTreeWhenAvailable(bool useKdTrees) { _useKdTreesWhenAvailable = useKdTrees; }
+        
+        /** Set whether the intersectors should use KdTrees.*/
+        bool getUseKdTreeWhenAvailable() const { return _useKdTreesWhenAvailable; }
+        
+        void setDoDummyTraversal(bool dummy) { _dummyTraversal = dummy; }
+        bool getDoDummyTraversal() const { return _dummyTraversal; }
+
+
+        /** Set the read callback.*/
+        void setReadCallback(ReadCallback* rc) { _readCallback = rc; }
+
+        /** Get the read callback.*/
+        ReadCallback* getReadCallback() { return _readCallback.get(); }
+
+        /** Get the const read callback.*/
+        const ReadCallback* getReadCallback() const { return _readCallback.get(); }
+        
+        
+        void pushWindowMatrix(osg::RefMatrix* matrix) { _windowStack.push_back(matrix); _eyePointDirty = true; }
+        void pushWindowMatrix(osg::Viewport* viewport) { _windowStack.push_back(new osg::RefMatrix( viewport->computeWindowMatrix()) ); _eyePointDirty = true; }
+        void popWindowMatrix() { _windowStack.pop_back(); _eyePointDirty = true; }
+        osg::RefMatrix* getWindowMatrix() { return _windowStack.empty() ? 0 :  _windowStack.back().get(); }
+        const osg::RefMatrix* getWindowMatrix() const { return _windowStack.empty() ? 0 :  _windowStack.back().get(); }
+
+        void pushProjectionMatrix(osg::RefMatrix* matrix) { _projectionStack.push_back(matrix); _eyePointDirty = true; }
+        void popProjectionMatrix() { _projectionStack.pop_back(); _eyePointDirty = true; }
+        osg::RefMatrix* getProjectionMatrix() { return _projectionStack.empty() ? 0 :  _projectionStack.back().get(); }
+        const osg::RefMatrix* getProjectionMatrix() const { return _projectionStack.empty() ? 0 :  _projectionStack.back().get(); }
+
+        void pushViewMatrix(osg::RefMatrix* matrix) { _viewStack.push_back(matrix); _eyePointDirty = true; }
+        void popViewMatrix() { _viewStack.pop_back(); _eyePointDirty = true; }
+        osg::RefMatrix* getViewMatrix() { return _viewStack.empty() ? 0 :  _viewStack.back().get(); }
+        const osg::RefMatrix* getViewMatrix() const { return _viewStack.empty() ? 0 :  _viewStack.back().get(); }
+
+        void pushModelMatrix(osg::RefMatrix* matrix) { _modelStack.push_back(matrix); _eyePointDirty = true; }
+        void popModelMatrix() { _modelStack.pop_back(); _eyePointDirty = true; } 
+        osg::RefMatrix* getModelMatrix() { return _modelStack.empty() ? 0 :  _modelStack.back().get(); }
+        const osg::RefMatrix* getModelMatrix() const { return _modelStack.empty() ? 0 :  _modelStack.back().get(); }
+
+
+        /** Set the reference eye point that is used for nodes that require an eye point to position themselves, such as billboards.*/
+        void setReferenceEyePoint(const osg::Vec3& ep) { _referenceEyePoint = ep; _eyePointDirty = true; }
+
+        /** Get the reference eye point.*/
+        const osg::Vec3& getReferenceEyePoint() const { return _referenceEyePoint; }
+        
+        /** Set the coordinate frame of the reference eye point.*/
+        void setReferenceEyePointCoordinateFrame(Intersector::CoordinateFrame cf) { _referenceEyePointCoordinateFrame = cf; }
+
+        /** Get the coordinate frame of the reference eye point.*/
+        Intersector::CoordinateFrame getReferenceEyePointCoordinateFrame() const { return _referenceEyePointCoordinateFrame; }
+        
+
+        /** Get the eye point in the local coordinate frame a given traversal point.*/
+        virtual osg::Vec3 getEyePoint() const;
+
+        enum LODSelectionMode
+        {
+            USE_HIGHEST_LEVEL_OF_DETAIL,
+            USE_EYE_POINT_FOR_LOD_LEVEL_SELECTION
+        };
+        
+        /** Set the LOD selection scheme.*/
+        void setLODSelectionMode(LODSelectionMode mode) { _lodSelectionMode = mode; }
+
+        /** Get the LOD selection scheme.*/
+        LODSelectionMode getLODSelectionMode() const { return _lodSelectionMode; }
+
+         /** Get the distance from a point to the eye point, distance value in local coordinate system.
+          * This is calculated using the pseudo-EyePoint (above) when doing LOD calculcations. */
+        virtual float getDistanceToEyePoint(const osg::Vec3& pos, bool withLODScale) const;
+
+    public:
+
+        virtual void apply(osg::Node& node);
+        virtual void apply(osg::Geode& geode);
+        virtual void apply(osg::Billboard& geode);
+        virtual void apply(osg::Group& group);
+        virtual void apply(osg::LOD& lod);
+        virtual void apply(osg::PagedLOD& lod);
+        virtual void apply(osg::Transform& transform);
+        virtual void apply(osg::Projection& projection);
+        virtual void apply(osg::Camera& camera);
+    
+    protected:
+    
+        inline bool enter(const osg::Node& node) { return _intersectorStack.empty() ? false : _intersectorStack.back()->enter(node); }
+        inline void leave() { _intersectorStack.back()->leave(); }
+        inline void intersect(osg::Drawable* drawable) { _intersectorStack.back()->intersect(*this, drawable); }
+        inline void push_clone() { _intersectorStack.push_back ( _intersectorStack.front()->clone(*this) ); }
+        inline void pop_clone() { if (_intersectorStack.size()>=2) _intersectorStack.pop_back(); }
+
+        typedef std::list< osg::ref_ptr<Intersector> > IntersectorStack;
+        IntersectorStack _intersectorStack;
+
+        bool _useKdTreesWhenAvailable;
+        bool _dummyTraversal;
+        
+        osg::ref_ptr<ReadCallback> _readCallback;
+        
+        typedef std::list< osg::ref_ptr<osg::RefMatrix> > MatrixStack;
+        MatrixStack _windowStack;
+        MatrixStack _projectionStack;
+        MatrixStack _viewStack;
+        MatrixStack _modelStack;
+
+        osg::Vec3                       _referenceEyePoint;
+        Intersector::CoordinateFrame    _referenceEyePointCoordinateFrame;
+        LODSelectionMode                _lodSelectionMode;
+
+        mutable bool                    _eyePointDirty;
+        mutable osg::Vec3               _eyePoint;
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SmoothingVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SmoothingVisitor (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SmoothingVisitor (revision 5328)
@@ -0,0 +1,46 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_SMOOTHINGVISITOR
+#define OSGUTIL_SMOOTHINGVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/Geometry>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** A smoothing visitor for calculating smoothed normals for
+  * osg::GeoSet's which contains surface primitives.
+  */
+class OSGUTIL_EXPORT SmoothingVisitor : public osg::NodeVisitor
+{
+    public:
+
+        /// default to traversing all children.
+        SmoothingVisitor();
+        virtual ~SmoothingVisitor();
+        
+        /// smooth geoset by creating per vertex normals.
+        static void smooth(osg::Geometry& geoset);
+
+        /// apply smoothing method to all geode geosets.
+        virtual void apply(osg::Geode& geode);
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneView
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneView (revision 9562)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/SceneView (revision 9562)
@@ -0,0 +1,543 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_SCENEVIEW
+#define OSGUTIL_SCENEVIEW 1
+
+#include <osg/Node>
+#include <osg/StateSet>
+#include <osg/Light>
+#include <osg/FrameStamp>
+#include <osg/DisplaySettings>
+#include <osg/CollectOccludersVisitor>
+#include <osg/CullSettings>
+#include <osg/Camera>
+
+#include <osgUtil/CullVisitor>
+
+namespace osgUtil {
+
+/**
+ * SceneView is deprecated, and is now just kept for backwards compatibility.
+ * It is recommend that you use osgViewer::Viewer/Composite in combination
+ * with osgViewer::GraphicsWindowEmbedded for embedded rendering support as
+ * this provides a greater range of functionality and consistency of API.
+*/
+class OSGUTIL_EXPORT SceneView : public osg::Object, public osg::CullSettings
+{
+    public:
+
+        /** Construct a default scene view.*/
+        SceneView(osg::DisplaySettings* ds=NULL);
+
+        SceneView(const SceneView& sceneview, const osg::CopyOp& copyop = osg::CopyOp());
+
+        META_Object(osgUtil, SceneView);
+
+        enum Options
+        {
+            NO_SCENEVIEW_LIGHT = 0x0,
+            HEADLIGHT = 0x1,
+            SKY_LIGHT = 0x2,
+            COMPILE_GLOBJECTS_AT_INIT = 0x4,
+            STANDARD_SETTINGS = HEADLIGHT |
+                                COMPILE_GLOBJECTS_AT_INIT                                
+        };
+
+        /* Set defaults. */
+        virtual void setDefaults() { setDefaults(STANDARD_SETTINGS); }
+
+        /** Set scene view to use default global state, light, camera
+         *  and render visitor.
+         */
+        virtual void setDefaults(unsigned int options);
+
+        /** Set the camera used to represent the camera view of this SceneView.*/
+        void setCamera(osg::Camera* camera, bool assumeOwnershipOfCamera = true);
+
+        /** Get the camera used to represent the camera view of this SceneView.*/
+        osg::Camera* getCamera() { return _camera.get(); }
+
+        /** Get the const camera used to represent the camera view of this SceneView.*/
+        const osg::Camera* getCamera() const { return _camera.get(); }
+
+        /** Set the data to view. The data will typically be
+         *  an osg::Scene but can be any osg::Node type.
+         */
+        void setSceneData(osg::Node* node);
+        
+        /** Get the scene data to view. The data will typically be
+         *  an osg::Scene but can be any osg::Node type.
+         */
+        osg::Node* getSceneData(unsigned int childNo=0) { return (_camera->getNumChildren()>childNo) ? _camera->getChild(childNo) : 0; }
+
+        /** Get the const scene data which to view. The data will typically be
+         *  an osg::Scene but can be any osg::Node type.
+         */
+        const osg::Node* getSceneData(unsigned int childNo=0) const { return (_camera->getNumChildren()>childNo) ? _camera->getChild(childNo) : 0; }
+        
+        /** Get the number of scene data subgraphs added to the SceneView's camera.*/
+        unsigned int getNumSceneData() const { return _camera->getNumChildren(); }
+
+        /** Set the viewport of the scene view to use specified osg::Viewport. */
+        void setViewport(osg::Viewport* viewport) { _camera->setViewport(viewport); }
+
+        /** Set the viewport of the scene view to specified dimensions. */
+        void setViewport(int x,int y,int width,int height) { _camera->setViewport(x,y,width,height); }
+
+
+        /** Get the viewport. */
+        osg::Viewport* getViewport() { return (_camera->getViewport()!=0) ? _camera->getViewport() : 0; }
+
+        /** Get the const viewport. */
+        const osg::Viewport* getViewport() const { return (_camera->getViewport()!=0) ? _camera->getViewport() : 0; }
+        
+        /** Set the DisplaySettings. */
+        inline void setDisplaySettings(osg::DisplaySettings* vs) { _displaySettings = vs; }
+        
+        /** Get the const DisplaySettings */
+        inline const osg::DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); }
+
+        /** Get the DisplaySettings */
+        inline osg::DisplaySettings* getDisplaySettings() { return _displaySettings.get(); }
+
+
+        /** Set the color used in glClearColor().
+            Defaults to an off blue color.*/
+        void setClearColor(const osg::Vec4& color) { _camera->setClearColor(color); }
+
+        /** Get the color used in glClearColor.*/
+        const osg::Vec4& getClearColor() const { return _camera->getClearColor(); }
+        
+        
+        /** Manually set the redraw interlaced stereo stencil mask request flag to control whether to redraw the stencil buffer on the next frame.*/  
+        void setRedrawInterlacedStereoStencilMask(bool flag) { _redrawInterlacedStereoStencilMask = flag; }
+
+        /** Get the redraw interlaced stereo stencil mask request flag.*/  
+        bool getRedrawInterlacedStereoStencilMask() const { return _redrawInterlacedStereoStencilMask; }
+
+
+        void setGlobalStateSet(osg::StateSet* state) { _globalStateSet = state; }
+        osg::StateSet* getGlobalStateSet() { return _globalStateSet.get(); }
+        const osg::StateSet* getGlobalStateSet() const { return _globalStateSet.get(); }
+
+        void setLocalStateSet(osg::StateSet* state) { _localStateSet = state; }
+        osg::StateSet* getLocalStateSet() { return _localStateSet.get(); }
+        const osg::StateSet* getLocalStateSet() const { return _localStateSet.get(); }
+        
+        enum ActiveUniforms
+        {
+            FRAME_NUMBER_UNIFORM            = 1,
+            FRAME_TIME_UNIFORM              = 2,
+            DELTA_FRAME_TIME_UNIFORM        = 4,
+            SIMULATION_TIME_UNIFORM         = 8,
+            DELTA_SIMULATION_TIME_UNIFORM   = 16,
+            VIEW_MATRIX_UNIFORM             = 32,
+            VIEW_MATRIX_INVERSE_UNIFORM     = 64,
+            DEFAULT_UNIFORMS                = FRAME_NUMBER_UNIFORM |
+                                              FRAME_TIME_UNIFORM |
+                                              DELTA_FRAME_TIME_UNIFORM |
+                                              SIMULATION_TIME_UNIFORM |
+                                              DELTA_SIMULATION_TIME_UNIFORM |
+                                              VIEW_MATRIX_UNIFORM |
+                                              VIEW_MATRIX_INVERSE_UNIFORM,
+            ALL_UNIFORMS                    = 0x7FFFFFFF
+        };
+
+        /** Set the uniforms that SceneView should set set up on each frame.*/        
+        void setActiveUniforms(int activeUniforms) { _activeUniforms = activeUniforms; }
+
+        /** Get the uniforms that SceneView should set set up on each frame.*/
+        int getActiveUniforms() const { return _activeUniforms; }
+
+        void updateUniforms();
+        
+
+        typedef Options LightingMode;
+
+        void setLightingMode(LightingMode mode);
+        LightingMode getLightingMode() const { return _lightingMode; }
+
+        void setLight(osg::Light* light) { _light = light; }
+        osg::Light* getLight() { return _light.get(); }
+        const osg::Light* getLight() const { return _light.get(); }
+        
+        void setState(osg::State* state) { _renderInfo.setState(state); }
+        osg::State* getState() { return _renderInfo.getState(); }
+        const osg::State* getState() const { return _renderInfo.getState(); }
+        
+        void setView(osg::View* view) { _camera->setView(view); }
+        osg::View* getView() { return _camera->getView(); }
+        const osg::View* getView() const { return _camera->getView(); }
+
+        void setRenderInfo(osg::RenderInfo& renderInfo) { _renderInfo = renderInfo; }
+        osg::RenderInfo& getRenderInfo() { return _renderInfo; }
+        const osg::RenderInfo& getRenderInfo() const { return _renderInfo; }
+        
+
+
+        /** Set the projection matrix. Can be thought of as setting the lens of a camera. */
+        inline void setProjectionMatrix(const osg::Matrixf& matrix) { _camera->setProjectionMatrix(matrix); }
+
+        /** Set the projection matrix. Can be thought of as setting the lens of a camera. */
+        inline void setProjectionMatrix(const osg::Matrixd& matrix) { _camera->setProjectionMatrix(matrix); }
+
+        /** Set to an orthographic projection. See OpenGL glOrtho for documentation further details.*/
+        void setProjectionMatrixAsOrtho(double left, double right,
+                                        double bottom, double top,
+                                        double zNear, double zFar);
+
+        /** Set to a 2D orthographic projection. See OpenGL glOrtho2D documentation for further details.*/
+        void setProjectionMatrixAsOrtho2D(double left, double right,
+                                          double bottom, double top);
+
+        /** Set to a perspective projection. See OpenGL glFrustum documentation for further details.*/
+        void setProjectionMatrixAsFrustum(double left, double right,
+                                          double bottom, double top,
+                                          double zNear, double zFar);
+
+        /** Create a symmetrical perspective projection, See OpenGL gluPerspective documentation for further details.
+          * Aspect ratio is defined as width/height.*/
+        void setProjectionMatrixAsPerspective(double fovy,double aspectRatio,
+                                              double zNear, double zFar);
+
+        /** Get the projection matrix.*/
+        osg::Matrixd& getProjectionMatrix() { return _camera->getProjectionMatrix(); }
+
+        /** Get the const projection matrix.*/
+        const osg::Matrixd& getProjectionMatrix() const { return _camera->getProjectionMatrix(); }
+
+        /** Get the orthographic settings of the orthographic projection matrix. 
+          * Returns false if matrix is not an orthographic matrix, where parameter values are undefined.*/
+        bool getProjectionMatrixAsOrtho(double& left, double& right,
+                                        double& bottom, double& top,
+                                        double& zNear, double& zFar) const;
+
+        /** Get the frustum setting of a perspective projection matrix.
+          * Returns false if matrix is not a perspective matrix, where parameter values are undefined.*/
+        bool getProjectionMatrixAsFrustum(double& left, double& right,
+                                          double& bottom, double& top,
+                                          double& zNear, double& zFar) const;
+
+        /** Get the frustum setting of a symmetric perspective projection matrix.
+          * Returns false if matrix is not a perspective matrix, where parameter values are undefined. 
+          * Note, if matrix is not a symmetric perspective matrix then the shear will be lost.
+          * Asymmetric matrices occur when stereo, power walls, caves and reality center display are used.
+          * In these configurations one should use the 'getProjectionMatrixAsFrustum' method instead.*/
+        bool getProjectionMatrixAsPerspective(double& fovy,double& aspectRatio,
+                                              double& zNear, double& zFar) const;
+
+
+        /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */
+        inline void setViewMatrix(const osg::Matrixf& matrix) { _camera->setViewMatrix(matrix); }
+        
+        /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */
+        inline void setViewMatrix(const osg::Matrixd& matrix) { _camera->setViewMatrix(matrix); }
+
+        /** Set to the position and orientation of view matrix, using the same convention as gluLookAt. */
+        void setViewMatrixAsLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up);
+
+        /** Get the view matrix. */
+        osg::Matrixd& getViewMatrix() { return _camera->getViewMatrix(); }
+
+        /** Get the const view matrix. */
+        const osg::Matrixd& getViewMatrix() const { return _camera->getViewMatrix(); }
+
+        /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */
+        void getViewMatrixAsLookAt(osg::Vec3& eye,osg::Vec3& center,osg::Vec3& up,float lookDistance=1.0f) const;
+
+
+
+        
+        void setInitVisitor(osg::NodeVisitor* av) { _initVisitor = av; }
+        osg::NodeVisitor* getInitVisitor() { return _initVisitor.get(); }
+        const osg::NodeVisitor* getInitVisitor() const { return _initVisitor.get(); }
+
+
+        void setUpdateVisitor(osg::NodeVisitor* av) { _updateVisitor = av; }
+        osg::NodeVisitor* getUpdateVisitor() { return _updateVisitor.get(); }
+        const osg::NodeVisitor* getUpdateVisitor() const { return _updateVisitor.get(); }
+
+
+        void setCullVisitor(osgUtil::CullVisitor* cv) { _cullVisitor = cv; }
+        osgUtil::CullVisitor* getCullVisitor() { return _cullVisitor.get(); }
+        const osgUtil::CullVisitor* getCullVisitor() const { return _cullVisitor.get(); }
+
+        void setCullVisitorLeft(osgUtil::CullVisitor* cv) { _cullVisitorLeft = cv; }
+        osgUtil::CullVisitor* getCullVisitorLeft() { return _cullVisitorLeft.get(); }
+        const osgUtil::CullVisitor* getCullVisitorLeft() const { return _cullVisitorLeft.get(); }
+
+        void setCullVisitorRight(osgUtil::CullVisitor* cv) { _cullVisitorRight = cv; }
+        osgUtil::CullVisitor* getCullVisitorRight() { return _cullVisitorRight.get(); }
+        const osgUtil::CullVisitor* getCullVisitorRight() const { return _cullVisitorRight.get(); }
+        
+        void setCollectOccludersVisitor(osg::CollectOccludersVisitor* cov) { _collectOccludersVisitor = cov; }
+        osg::CollectOccludersVisitor* getCollectOccludersVisitor() { return _collectOccludersVisitor.get(); }
+        const osg::CollectOccludersVisitor* getCollectOccludersVisitor() const { return _collectOccludersVisitor.get(); }
+
+
+        void setStateGraph(osgUtil::StateGraph* rg) { _stateGraph = rg; }
+        osgUtil::StateGraph* getStateGraph() { return _stateGraph.get(); }
+        const osgUtil::StateGraph* getStateGraph() const { return _stateGraph.get(); }
+
+        void setStateGraphLeft(osgUtil::StateGraph* rg) { _stateGraphLeft = rg; }
+        osgUtil::StateGraph* getStateGraphLeft() { return _stateGraphLeft.get(); }
+        const osgUtil::StateGraph* getStateGraphLeft() const { return _stateGraphLeft.get(); }
+
+        void setStateGraphRight(osgUtil::StateGraph* rg) { _stateGraphRight = rg; }
+        osgUtil::StateGraph* getStateGraphRight() { return _stateGraphRight.get(); }
+        const osgUtil::StateGraph* getStateGraphRight() const { return _stateGraphRight.get(); }
+
+
+        void setRenderStage(osgUtil::RenderStage* rs) { _renderStage = rs; }
+        osgUtil::RenderStage* getRenderStage() { return _renderStage.get(); }
+        const osgUtil::RenderStage* getRenderStage() const { return _renderStage.get(); }
+
+        void setRenderStageLeft(osgUtil::RenderStage* rs) { _renderStageLeft = rs; }
+        osgUtil::RenderStage* getRenderStageLeft() { return _renderStageLeft.get(); }
+        const osgUtil::RenderStage* getRenderStageLeft() const { return _renderStageLeft.get(); }
+
+        void setRenderStageRight(osgUtil::RenderStage* rs) { _renderStageRight = rs; }
+        osgUtil::RenderStage* getRenderStageRight() { return _renderStageRight.get(); }
+        const osgUtil::RenderStage* getRenderStageRight() const { return _renderStageRight.get(); }
+
+
+        /** Set the draw buffer value used at the start of each frame draw.  Note, overridden in quad buffer stereo mode */
+        void setDrawBufferValue( GLenum drawBufferValue ) { _camera->setDrawBuffer(drawBufferValue); }
+
+        /** Get the draw buffer value used at the start of each frame draw. */
+        GLenum getDrawBufferValue() const { return _camera->getDrawBuffer(); }
+
+
+        /** FusionDistanceMode is used only when working in stereo.*/
+        enum FusionDistanceMode
+        {
+            /** Use fusion distance from the value set on the SceneView.*/
+            USE_FUSION_DISTANCE_VALUE,
+            /** Compute the fusion distance by multiplying the screen distance by the fusion distance value.*/
+            PROPORTIONAL_TO_SCREEN_DISTANCE
+        };
+
+        /** Set the FusionDistanceMode and Value. Note, is used only when working in stereo.*/
+        void setFusionDistance(FusionDistanceMode mode,float value=1.0f)
+        {
+            _fusionDistanceMode = mode;
+            _fusionDistanceValue = value;
+        }
+
+        /** Get the FusionDistanceMode.*/
+        FusionDistanceMode getFusionDistanceMode() const { return _fusionDistanceMode; }
+
+        /** Get the FusionDistanceValue. Note, only used for USE_FUSION_DISTANCE_VALUE & PROPORTIONAL_TO_SCREEN_DISTANCE modes.*/
+        float getFusionDistanceValue() const { return _fusionDistanceValue; }
+
+
+        /** Set whether the draw method should call renderer->prioritizeTexture.*/
+        void setPrioritizeTextures(bool pt) { _prioritizeTextures = pt; }
+        
+        /** Get whether the draw method should call renderer->prioritizeTexture.*/
+        bool getPrioritizeTextures() const { return _prioritizeTextures; }
+
+        /** Callback for overidding the default method for compute the offset projection and view matrices.*/
+        struct ComputeStereoMatricesCallback : public osg::Referenced
+        {
+            virtual osg::Matrixd computeLeftEyeProjection(const osg::Matrixd& projection) const = 0;
+            virtual osg::Matrixd computeLeftEyeView(const osg::Matrixd& view) const = 0;
+
+            virtual osg::Matrixd computeRightEyeProjection(const osg::Matrixd& projection) const = 0;
+            virtual osg::Matrixd computeRightEyeView(const osg::Matrixd& view) const = 0;
+        };
+        
+        void setComputeStereoMatricesCallback(ComputeStereoMatricesCallback* callback) { _computeStereoMatricesCallback=callback; }
+        ComputeStereoMatricesCallback* getComputeStereoMatricesCallback() { return _computeStereoMatricesCallback.get(); }
+        const ComputeStereoMatricesCallback* getComputeStereoMatricesCallback() const { return _computeStereoMatricesCallback.get(); }
+
+        /** Calculate the object coordinates of a point in window coordinates.
+            Note, current implementation requires that SceneView::draw() has been previously called
+            for projectWindowIntoObject to produce valid values.  Consistent with OpenGL
+            windows coordinates are calculated relative to the bottom left of the window.
+            Returns true on successful projection.
+        */
+        bool projectWindowIntoObject(const osg::Vec3& window,osg::Vec3& object) const;
+
+        /** Calculate the object coordinates of a window x,y when projected onto the near and far planes.
+            Note, current implementation requires that SceneView::draw() has been previously called
+            for projectWindowIntoObject to produce valid values.  Consistent with OpenGL
+            windows coordinates are calculated relative to the bottom left of the window.
+            Returns true on successful projection.
+        */
+        bool projectWindowXYIntoObject(int x,int y,osg::Vec3& near_point,osg::Vec3& far_point) const;
+
+        /** Calculate the window coordinates of a point in object coordinates.
+            Note, current implementation requires that SceneView::draw() has been previously called
+            for projectWindowIntoObject to produce valid values.  Consistent with OpenGL
+            windows coordinates are calculated relative to the bottom left of the window,
+            whereas window API's normally have the top left as the origin,
+            so you may need to pass in (mouseX,window_height-mouseY,...).
+            Returns true on successful projection.
+        */
+        bool projectObjectIntoWindow(const osg::Vec3& object,osg::Vec3& window) const;
+
+
+        /** Set the frame stamp for the current frame.*/
+        inline void setFrameStamp(osg::FrameStamp* fs) { _frameStamp = fs; }
+
+        /** Get the frame stamp for the current frame.*/
+        inline const osg::FrameStamp* getFrameStamp() const { return _frameStamp.get(); }
+
+
+
+
+        inline osg::Matrixd computeLeftEyeProjection(const osg::Matrixd& projection)  const
+        {
+            if (_computeStereoMatricesCallback.valid()) return _computeStereoMatricesCallback->computeLeftEyeProjection(projection);
+            else return computeLeftEyeProjectionImplementation(projection);
+        }
+
+        inline osg::Matrixd computeLeftEyeView(const osg::Matrixd& view) const
+        {
+            if (_computeStereoMatricesCallback.valid()) return _computeStereoMatricesCallback->computeLeftEyeView(view);
+            else return computeLeftEyeViewImplementation(view);
+        }
+        
+        inline osg::Matrixd computeRightEyeProjection(const osg::Matrixd& projection)  const
+        {
+            if (_computeStereoMatricesCallback.valid()) return _computeStereoMatricesCallback->computeRightEyeProjection(projection);
+            else return computeRightEyeProjectionImplementation(projection);
+        }
+
+        inline osg::Matrixd computeRightEyeView(const osg::Matrixd& view) const
+        {
+            if (_computeStereoMatricesCallback.valid()) return _computeStereoMatricesCallback->computeRightEyeView(view);
+            else return computeRightEyeViewImplementation(view);
+        }
+
+        virtual osg::Matrixd computeLeftEyeProjectionImplementation(const osg::Matrixd& projection) const;
+        virtual osg::Matrixd computeLeftEyeViewImplementation(const osg::Matrixd& view) const;
+
+        virtual osg::Matrixd computeRightEyeProjectionImplementation(const osg::Matrixd& projection) const;
+        virtual osg::Matrixd computeRightEyeViewImplementation(const osg::Matrixd& view) const;
+
+        /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/
+        virtual void inheritCullSettings(const osg::CullSettings& settings) { inheritCullSettings(settings, _inheritanceMask); }
+
+        /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/
+        virtual void inheritCullSettings(const osg::CullSettings& settings, unsigned int inheritanceMask);
+
+
+        /** Do init traversal of attached scene graph using Init NodeVisitor.
+          * The init traversal is called once for each SceneView, and should
+          * be used to compile display list, texture objects intialize data
+          * not otherwise intialized during scene graph loading. Note, is
+          * called automatically by update & cull if it hasn't already been called
+          * elsewhere. Also init() should only ever be called within a valid
+          * graphics context.*/
+        virtual void init();
+
+        /** Do app traversal of attached scene graph using App NodeVisitor.*/
+        virtual void update();
+
+        /** Do cull traversal of attached scene graph using Cull NodeVisitor.*/
+        virtual void cull();
+
+        /** Do draw traversal of draw bins generated by cull traversal.*/
+        virtual void draw();
+        
+        /** Compute the number of dynamic objects that will be held in the rendering backend */
+        unsigned int getDynamicObjectCount() const { return _dynamicObjectCount; }
+        
+        /** Release all OpenGL objects from the scene graph, such as texture objects, display lists etc.
+          * These released scene graphs placed in the respective delete GLObjects cache, which
+          * then need to be deleted in OpenGL by SceneView::flushAllDeleteGLObjects(). */
+        virtual void releaseAllGLObjects();
+
+        /** Flush all deleted OpenGL objects, such as texture objects, display lists etc.*/
+        virtual void flushAllDeletedGLObjects();
+
+        /** Flush deleted OpenGL objects, such as texture objects, display lists etc within specified available time.*/
+        virtual void flushDeletedGLObjects(double& availableTime);
+        
+        /** Extract stats for current draw list. */
+        bool getStats(Statistics& primStats); 
+
+    protected:
+
+        virtual ~SceneView();
+
+        /** Do cull traversal of attached scene graph using Cull NodeVisitor. Return true if computeNearFar has been done during the cull traversal.*/
+        virtual bool cullStage(const osg::Matrixd& projection,const osg::Matrixd& modelview,osgUtil::CullVisitor* cullVisitor, osgUtil::StateGraph* rendergraph, osgUtil::RenderStage* renderStage, osg::Viewport *viewport);
+        
+        void computeLeftEyeViewport(const osg::Viewport *viewport);
+        void computeRightEyeViewport(const osg::Viewport *viewport);
+
+        const osg::Matrix computeMVPW() const;
+
+        void clearArea(int x,int y,int width,int height,const osg::Vec4& color);
+
+        osg::ref_ptr<osg::StateSet>                 _localStateSet;
+        osg::RenderInfo                             _renderInfo;
+        
+        bool                                        _initCalled;
+        osg::ref_ptr<osg::NodeVisitor>              _initVisitor;
+        osg::ref_ptr<osg::NodeVisitor>              _updateVisitor;
+        osg::ref_ptr<osgUtil::CullVisitor>          _cullVisitor;
+        osg::ref_ptr<osgUtil::StateGraph>           _stateGraph;
+        osg::ref_ptr<osgUtil::RenderStage>          _renderStage;
+
+        osg::ref_ptr<ComputeStereoMatricesCallback> _computeStereoMatricesCallback;
+
+        osg::ref_ptr<osgUtil::CullVisitor>          _cullVisitorLeft;
+        osg::ref_ptr<osgUtil::StateGraph>           _stateGraphLeft;
+        osg::ref_ptr<osgUtil::RenderStage>          _renderStageLeft;
+        osg::ref_ptr<osg::Viewport>                 _viewportLeft;
+
+        osg::ref_ptr<osgUtil::CullVisitor>          _cullVisitorRight;
+        osg::ref_ptr<osgUtil::StateGraph>           _stateGraphRight;
+        osg::ref_ptr<osgUtil::RenderStage>          _renderStageRight;
+        osg::ref_ptr<osg::Viewport>                 _viewportRight;
+
+        osg::ref_ptr<osg::CollectOccludersVisitor>  _collectOccludersVisitor;
+        
+        osg::ref_ptr<osg::FrameStamp>               _frameStamp;
+        
+        osg::observer_ptr<osg::Camera>              _camera;
+        osg::ref_ptr<osg::Camera>                   _cameraWithOwnership;
+        
+        osg::ref_ptr<osg::StateSet>                 _globalStateSet;
+        osg::ref_ptr<osg::Light>                    _light;
+        osg::ref_ptr<osg::DisplaySettings>          _displaySettings;
+        
+        FusionDistanceMode                          _fusionDistanceMode;
+        float                                       _fusionDistanceValue;
+
+        LightingMode                                _lightingMode;
+        
+        bool                                        _prioritizeTextures;
+        
+        bool                                        _requiresFlush;
+        
+        int                                         _activeUniforms;        
+        double                                      _previousFrameTime;
+        double                                      _previousSimulationTime;
+        
+        bool                                        _redrawInterlacedStereoStencilMask;
+        int                                         _interlacedStereoStencilWidth;
+        int                                         _interlacedStereoStencilHeight;
+
+        unsigned int                                _dynamicObjectCount;        
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformCallback
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformCallback (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformCallback (revision 5328)
@@ -0,0 +1,51 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+//C++ header 
+
+#ifndef OSGUTIL_TRANSFORMCALLBACK
+#define OSGUTIL_TRANSFORMCALLBACK 1
+
+#include <osg/Node>
+#include <osgUtil/Export>
+
+namespace osgUtil
+{
+
+/** TransformCallback is now deprecated, use osg::AnimationPathCallback instead.*/
+class OSGUTIL_EXPORT TransformCallback : public osg::NodeCallback
+{
+
+    public:
+
+        TransformCallback(const osg::Vec3& pivot,const osg::Vec3& axis,float angularVelocity);
+
+        void setPause(bool pause) { _pause = pause; }
+
+        /** implements the callback*/
+        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
+
+    protected:
+    
+        float               _angular_velocity;
+        osg::Vec3           _pivot;
+        osg::Vec3           _axis;
+
+        int                 _previousTraversalNumber;
+        double              _previousTime;
+        bool                _pause;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/LineSegmentIntersector
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/LineSegmentIntersector (revision 8275)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/LineSegmentIntersector (revision 8275)
@@ -0,0 +1,113 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_LINESEGMENTINTERSECTOR
+#define OSGUTIL_LINESEGMENTINTERSECTOR 1
+
+#include <osgUtil/IntersectionVisitor>
+
+namespace osgUtil
+{
+
+/** Concrete class for implementing line intersections with the scene graph.
+  * To be used in conjunction with IntersectionVisitor. */
+class OSGUTIL_EXPORT LineSegmentIntersector : public Intersector
+{
+    public:
+
+        /** Construct a LineSegmentIntersector the runs between the specified start and end points in MODEL coordinates. */
+        LineSegmentIntersector(const osg::Vec3d& start, const osg::Vec3d& end);
+        
+        /** Construct a LineSegmentIntersector the runs between the specified start and end points in the specified coordinate frame. */
+        LineSegmentIntersector(CoordinateFrame cf, const osg::Vec3d& start, const osg::Vec3d& end);
+        
+        /** Convenience constructor for supporting picking in WINDOW, or PROJECTION coordinates
+          * In WINDOW coordinates creates a start value of (x,y,0) and end value of (x,y,1).
+          * In PROJECTION coordinates (clip space cube) creates a start value of (x,y,-1) and end value of (x,y,1).
+          * In VIEW and MODEL coordinates creates a start value of (x,y,0) and end value of (x,y,1).*/
+        LineSegmentIntersector(CoordinateFrame cf, double x, double y);
+        
+        struct Intersection
+        {
+            Intersection():
+                ratio(-1.0),
+                primitiveIndex(0) {}
+        
+            bool operator < (const Intersection& rhs) const { return ratio < rhs.ratio; }
+
+            typedef std::vector<unsigned int>   IndexList;
+            typedef std::vector<double>         RatioList;
+
+            double                          ratio;
+            osg::NodePath                   nodePath;
+            osg::ref_ptr<osg::Drawable>     drawable;
+            osg::ref_ptr<osg::RefMatrix>    matrix;
+            osg::Vec3d                      localIntersectionPoint;
+            osg::Vec3                       localIntersectionNormal;
+            IndexList                       indexList;
+            RatioList                       ratioList;
+            unsigned int                    primitiveIndex;
+            
+            const osg::Vec3d& getLocalIntersectPoint() const { return localIntersectionPoint; }
+            osg::Vec3d getWorldIntersectPoint() const { return matrix.valid() ? localIntersectionPoint * (*matrix) : localIntersectionPoint; }
+            
+            const osg::Vec3& getLocalIntersectNormal() const { return localIntersectionNormal; }
+            osg::Vec3 getWorldIntersectNormal() const { return matrix.valid() ? osg::Matrix::transform3x3(osg::Matrix::inverse(*matrix),localIntersectionNormal) : localIntersectionNormal; }
+        };
+        
+        typedef std::multiset<Intersection> Intersections;
+        
+        inline void insertIntersection(const Intersection& intersection) { getIntersections().insert(intersection); }
+
+        inline Intersections& getIntersections() { return _parent ? _parent->_intersections : _intersections; }
+
+        inline Intersection getFirstIntersection() { Intersections& intersections = getIntersections(); return intersections.empty() ? Intersection() : *(intersections.begin()); }
+        
+        inline void setStart(const osg::Vec3d& start) { _start = start; }
+        inline const osg::Vec3d& getStart() const { return _start; }
+
+        inline void setEnd(const osg::Vec3d& end) { _end = end; }
+        inline const osg::Vec3d& getEnd() const { return _end; }
+
+    public:
+
+        virtual Intersector* clone(osgUtil::IntersectionVisitor& iv);
+        
+        virtual bool enter(const osg::Node& node);
+        
+        virtual void leave();
+        
+        virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable);
+        
+        virtual void reset();
+
+        virtual bool containsIntersections() { return !_intersections.empty(); }
+
+    protected:
+    
+        bool intersects(const osg::BoundingSphere& bs);
+        bool intersectAndClip(osg::Vec3d& s, osg::Vec3d& e,const osg::BoundingBox& bb);
+
+        LineSegmentIntersector* _parent;
+
+        osg::Vec3d  _start;
+        osg::Vec3d  _end;
+        
+        Intersections _intersections;
+    
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HalfWayMapGenerator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HalfWayMapGenerator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HalfWayMapGenerator (revision 5328)
@@ -0,0 +1,53 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+#ifndef OSGUTIL_HALFWAYMAPGENERATOR_
+#define OSGUTIL_HALFWAYMAPGENERATOR_
+
+#include <osgUtil/Export>
+
+#include <osgUtil/CubeMapGenerator>
+
+namespace osgUtil
+{
+
+    /** This cube map generator produces an Half-way vector map, useful for 
+      * hardware-based specular lighting effects.
+      * It computes: C = normalize(R - L), where C is the resulting color, 
+      * R is the reflection vector and L is the light direction.
+      */
+    class OSGUTIL_EXPORT HalfWayMapGenerator: public CubeMapGenerator {
+    public:
+        HalfWayMapGenerator(const osg::Vec3 &light_direction, int texture_size = 64);
+        HalfWayMapGenerator(const HalfWayMapGenerator &copy, const osg::CopyOp &copyop);
+
+    protected:
+        virtual ~HalfWayMapGenerator() {}
+        HalfWayMapGenerator &operator=(const HalfWayMapGenerator &) { return *this; }
+
+        inline virtual osg::Vec4 compute_color(const osg::Vec3 &R) const;
+
+    private:
+        osg::Vec3 ldir_;
+    };
+
+    // INLINE METHODS
+
+    inline osg::Vec4 HalfWayMapGenerator::compute_color(const osg::Vec3 &R) const
+    {
+        const osg::Vec3 V = (R / R.length()) - ldir_;
+        return vector_to_color(V / V.length());
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/OperationArrayFunctor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/OperationArrayFunctor (revision 7752)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/OperationArrayFunctor (revision 7752)
@@ -0,0 +1,116 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_OPERATIONARRAYFUNCTOR
+#define OSGUTIL_OPERATIONARRAYFUNCTOR 1
+
+
+#include <osg/Array>
+#include <osgUtil/ConvertVec>
+
+// ** template ArrayVisitor to handle all method in one template.
+// **  Only use when process done on each array could be templated
+
+namespace osgUtil {
+
+template <class T>
+class OperationArrayFunctor : public osg::ArrayVisitor, public T
+{
+    public:
+        
+        virtual void apply(osg::Array&) {}
+//        virtual void apply(osg::ByteArray& array) { T::process<osg::ByteArray>(array); }
+//        virtual void apply(osg::ShortArray& array) { T::process(array); }
+//        virtual void apply(osg::IntArray& array) { T::process<osg::IntArray>(array); }
+//        virtual void apply(osg::UByteArray& array) { T::process<osg::UByteArray>(array); }
+//        virtual void apply(osg::UShortArray& array) { T::process<osg::UShortArray>(array); }
+//        virtual void apply(osg::UIntArray& array) { T::process<osg::UIntArray>(array); }
+//        virtual void apply(osg::FloatArray& array) { T::process<osg::FloatArray>(array); }
+//        virtual void apply(osg::DoubleArray& array) { T::process<osg::DoubleArray>(array); }
+
+        virtual void apply(osg::Vec2Array & array) { T::process(array); }
+        virtual void apply(osg::Vec3Array& array) { T::process(array); }
+        virtual void apply(osg::Vec4Array& array) { T::process(array); }
+
+        virtual void apply(osg::Vec4ubArray& array) { T::process(array); }
+
+        virtual void apply(osg::Vec2bArray& array) { T::process(array); }
+        virtual void apply(osg::Vec3bArray& array) { T::process(array); }
+        virtual void apply(osg::Vec4bArray& array) { T::process(array); }
+
+        virtual void apply(osg::Vec2sArray& array) { T::process(array); }
+        virtual void apply(osg::Vec3sArray& array) { T::process(array); }
+        virtual void apply(osg::Vec4sArray& array) { T::process(array); }
+
+        virtual void apply(osg::Vec2dArray& array) { T::process(array); }
+        virtual void apply(osg::Vec3dArray& array) { T::process(array); }
+        virtual void apply(osg::Vec4dArray& array) { T::process(array); }
+};
+
+struct AddRangeOperator
+{
+    template <typename ArrayType>
+    void process(ArrayType & array) 
+    {   
+        typedef typename ArrayType::ElementDataType ElementDataType;
+                
+        ElementDataType convertedVector;
+        osgUtil::ConvertVec<osg::Vec3d, ElementDataType>::convert(_vector, convertedVector);
+        
+        typename ArrayType::iterator it = array.begin();
+        std::advance(it, _begin);
+        
+        typename ArrayType::iterator end = it;
+        std::advance(end, _count);
+        
+        for (; it < end; ++it)
+            (*it) += convertedVector;
+    }
+
+    unsigned int _begin;
+    unsigned int _count;
+    
+    osg::Vec3d _vector;
+};
+typedef OperationArrayFunctor<AddRangeOperator> AddRangeFunctor;
+
+struct MultiplyRangeOperator
+{
+    template <typename ArrayType>
+    void process(ArrayType & array) 
+    {   
+        typedef typename ArrayType::ElementDataType ElementDataType;
+                
+        ElementDataType convertedVector;
+        osgUtil::ConvertVec<osg::Vec3d, ElementDataType>::convert(_vector, convertedVector);
+        
+        typename ArrayType::iterator it = array.begin();
+        std::advance(it, _begin);
+        
+        typename ArrayType::iterator end = it;
+        std::advance(end, _count);
+        
+        for (; it < end; ++it)
+            (*it) *= convertedVector;
+    }
+
+    unsigned int _begin;
+    unsigned int _count;
+    
+    osg::Vec3d _vector;
+};
+typedef OperationArrayFunctor<MultiplyRangeOperator> MultiplyRangeFunctor;
+
+} // end osgUtil namespace
+
+#endif // ** OPERATIONARRAYFUNCTOR ** //
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Tessellator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Tessellator (revision 8649)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Tessellator (revision 8649)
@@ -0,0 +1,246 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_Tessellator
+#define OSGUTIL_Tessellator
+
+#include <osg/Geometry>
+
+#include <osgUtil/Export>
+
+#include <osg/GLU>
+
+#include <vector>
+
+/* Win32 calling conventions. (or a least thats what the GLUT example tess.c uses.)*/
+#ifndef CALLBACK
+#define CALLBACK
+#endif
+
+
+namespace osgUtil {
+
+/** Originally a simple class for tessellating a single polygon boundary.
+  * Using old style glu tessellation functions for portability.
+  * Upgraded Jan 2004 to use the modern glu tessellation functions.*/
+
+class OSGUTIL_EXPORT Tessellator : public osg::Referenced
+{
+    public:
+   
+        Tessellator();
+        ~Tessellator();
+
+        /** The winding rule, see red book ch 11. */
+        enum WindingType{
+            TESS_WINDING_ODD          = GLU_TESS_WINDING_ODD,
+            TESS_WINDING_NONZERO      = GLU_TESS_WINDING_NONZERO     ,
+            TESS_WINDING_POSITIVE     = GLU_TESS_WINDING_POSITIVE    ,
+            TESS_WINDING_NEGATIVE     = GLU_TESS_WINDING_NEGATIVE    ,
+            TESS_WINDING_ABS_GEQ_TWO  =    GLU_TESS_WINDING_ABS_GEQ_TWO
+        } ;
+
+        /** we interpret all contours in the geometry as a single set to be tessellated or
+         * each separate drawable's contours needs to be tessellated. */
+        enum TessellationType {
+            TESS_TYPE_GEOMETRY, // tessellate everything in the geometry object
+            TESS_TYPE_DRAWABLE, // tessellate each polygon, triangles & quads drawables in geometry separately
+            TESS_TYPE_POLYGONS // tessellate ONLY polygon drawables in geometry separately
+        };
+
+        /** Set and get tessellation request boundary only on/off */
+        void setBoundaryOnly (const bool tt) { _boundaryOnly=tt;}
+        inline bool getBoundaryOnly ( ) { return _boundaryOnly;}
+
+        /** Set and get tessellation windong rule */
+        void setWindingType (const WindingType wt) { _wtype=wt;}
+        inline WindingType getWindingType ( ) { return _wtype;}
+
+        /** Set and get tessellation type */
+        void setTessellationType (const TessellationType tt) { _ttype=tt;}
+        inline TessellationType getTessellationType ( ) { return _ttype;}
+
+        /** Change the contours lists of the geometry into tessellated primitives (the
+          * list of primitives in the original geometry is stored in the Tessellator for
+          * possible re-use. 
+          * The name remains retessellatePolygons although it now handles trifans, strips, quads etc.
+          * as well as Polygons so as to not break old codes relying on this function name. */
+        void retessellatePolygons(osg::Geometry &cxgeom);
+
+        /** Define the normal to the tessellated polygon - this provides a hint how to
+         *  tessellate the contours; see gluTessNormal in red book or man pages.
+         *  GWM July 2005. Can improve teselation
+         *  "For example, if you know that all polygons lie in the x-y plane, 
+         *   call gluTessNormal(tess, 0.0, 0.0, 1.0) before rendering any polygons."
+         */
+        void setTessellationNormal(const osg::Vec3 norm) { tessNormal=norm;}
+
+        osg::Geometry::PrimitiveSetList  getContours() { return _Contours;}
+
+        typedef std::vector<osg::Vec3*> VertexPointList;
+        
+        struct Prim : public osg::Referenced
+        {
+            Prim(GLenum mode):_mode(mode) {}
+        
+            typedef std::vector<osg::Vec3*> VecList;
+
+            GLenum  _mode;
+            VecList _vertices;
+        };
+        
+        void beginTessellation();
+        
+        void beginContour();
+        void addVertex(osg::Vec3* vertex);
+        void endContour();
+        
+        void endTessellation();
+
+        typedef std::vector< osg::ref_ptr<Prim> > PrimList;
+        
+        PrimList& getPrimList() { return _primList; }        
+        
+        void reset();
+        
+    protected:
+
+        /** remove unused parts of the array, eg for wehn retessellating
+         * tessellation can introduce extra vertices for concave or crossing boundaries,
+         * these will leak memory if not removed when retessellating. */
+        void reduceArray(osg::Array * cold, const unsigned int nnu);
+
+        void collectTessellation(osg::Geometry &cxgeom, unsigned int originalIndex);
+        
+        typedef std::map<osg::Vec3*,unsigned int> VertexPtrToIndexMap;
+        void addContour(GLenum  mode, unsigned int first, unsigned int last, osg::Vec3Array* vertices);
+        void addContour(osg::PrimitiveSet* primitive, osg::Vec3Array* vertices);
+        void handleNewVertices(osg::Geometry& geom,VertexPtrToIndexMap &vertexPtrToIndexMap);
+
+        void begin(GLenum mode);
+        void vertex(osg::Vec3* vertex);
+        void combine(osg::Vec3* vertex,void* vertex_data[4],GLfloat weight[4]);
+        void end();
+        void error(GLenum errorCode);
+
+    
+        static void CALLBACK beginCallback(GLenum which, void* userData);
+        static void CALLBACK vertexCallback(GLvoid *data, void* userData);
+        static void CALLBACK combineCallback(GLdouble coords[3], void* vertex_data[4],
+                              GLfloat weight[4], void** outData,
+                              void* useData);
+        static void CALLBACK endCallback(void* userData);
+        static void CALLBACK errorCallback(GLenum errorCode, void* userData);
+        
+        
+        struct Vec3d
+        {
+            double _v[3];
+        };
+
+
+        struct NewVertex
+        {
+        
+            NewVertex():
+                _vpos(0),
+                _f1(0),
+                _v1(0),
+                _f2(0),
+                _v2(0),
+                _f3(0),
+                _v3(0),
+                _f4(0),
+                _v4(0) {}
+            
+            NewVertex(const NewVertex& nv):
+                _vpos(nv._vpos),
+                _f1(nv._f1),
+                _v1(nv._v1),
+                _f2(nv._f2),
+                _v2(nv._v2),
+                _f3(nv._f3),
+                _v3(nv._v3),
+                _f4(nv._f4),
+                _v4(nv._v4) {}
+
+            NewVertex(osg::Vec3* vx,
+                      float f1,osg::Vec3* v1,
+                      float f2,osg::Vec3* v2,
+                      float f3,osg::Vec3* v3,
+                      float f4,osg::Vec3* v4):
+                _vpos(vx),
+                _f1(f1),
+                _v1(v1),
+                _f2(f2),
+                _v2(v2),
+                _f3(f3),
+                _v3(v3),
+                _f4(f4),
+                _v4(v4) {}
+
+            osg::Vec3  *_vpos; // added gwm Jan 2004 the vertex coords s.t. NewVertex can be used in a std::vector
+        
+            float       _f1;
+            osg::Vec3*  _v1;
+
+            float       _f2;
+            osg::Vec3*  _v2;
+
+            float       _f3;
+            osg::Vec3*  _v3;
+
+            float       _f4;
+            osg::Vec3*  _v4;
+            
+        };
+        
+        //change NewVertexList from std::map<osg::Vec3*,NewVertex> NewVertexList;
+        // because this has undefined order of insertion for new vertices. 
+        // which occasionally corrupted the texture mapping.
+        typedef std::vector<NewVertex> NewVertexList;
+        typedef std::vector<Vec3d*> Vec3dList;
+
+        GLUtesselator*  _tobj;
+        PrimList        _primList;
+        Vec3dList       _coordData;
+        NewVertexList   _newVertexList;
+        GLenum          _errorCode;
+
+        /** winding rule, which parts will become solid */
+        WindingType _wtype; 
+
+        /** tessellation rule, which parts will become solid */
+        TessellationType _ttype;
+
+        bool _boundaryOnly; // see gluTessProperty - if true: make the boundary edges only.
+
+        /** number of vertices that are part of the 'original' set of contours */
+        unsigned int _numberVerts;
+
+        /** List of primitives that define the contours */
+        osg::Geometry::PrimitiveSetList                _Contours;
+
+        /** count number of primitives in a geometry to get right no. of norms/colurs etc for per_primitive attributes. */
+        unsigned int _index;
+
+        /** the gluTessNormal for tessellation hint */
+        osg::Vec3 tessNormal;
+
+        /** count of number of extra primitives added */
+        unsigned int _extraPrimitives;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/StateGraph
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/StateGraph (revision 7375)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/StateGraph (revision 7375)
@@ -0,0 +1,317 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_STATEGRAPH
+#define OSGUTIL_STATEGRAPH 1
+
+#include <osg/Matrix>
+#include <osg/Drawable>
+#include <osg/StateSet>
+#include <osg/State>
+#include <osg/Light>
+
+#include <osgUtil/RenderLeaf>
+
+#include <set>
+#include <vector>
+#include <algorithm>
+
+namespace osgUtil {
+
+struct LessDepthSortFunctor
+{
+    bool operator() (const osg::ref_ptr<RenderLeaf>& lhs,const osg::ref_ptr<RenderLeaf>& rhs)
+    {
+        return (lhs->_depth < rhs->_depth);
+    }
+};
+
+/** StateGraph - contained in a renderBin, defines the scene to be drawn.
+  */
+class OSGUTIL_EXPORT StateGraph : public osg::Referenced
+{
+    public:
+    
+
+        typedef std::map< const osg::StateSet*, osg::ref_ptr<StateGraph> >   ChildList;
+        typedef std::vector< osg::ref_ptr<RenderLeaf> >                 LeafList;
+
+        StateGraph*                         _parent;
+
+#ifdef OSGUTIL_RENDERBACKEND_USE_REF_PTR
+        osg::ref_ptr<const osg::StateSet> _stateset;
+#else
+        const osg::StateSet* _stateset;
+#endif
+
+        int                                 _depth;
+        ChildList                           _children;
+        LeafList                            _leaves;
+        
+        mutable float                       _averageDistance;
+        mutable float                       _minimumDistance;
+        
+        osg::ref_ptr<osg::Referenced>       _userData;
+
+        bool                                _dynamic;
+
+        StateGraph():
+            osg::Referenced(false),
+            _parent(NULL),
+            _stateset(NULL),
+            _depth(0),
+            _averageDistance(0),
+            _minimumDistance(0),
+            _userData(NULL),
+            _dynamic(false)
+        {
+        }
+
+        StateGraph(StateGraph* parent,const osg::StateSet* stateset):
+            osg::Referenced(false),
+            _parent(parent),
+            _stateset(stateset),
+            _depth(0),
+            _averageDistance(0),
+            _minimumDistance(0),
+            _userData(NULL),
+            _dynamic(false)
+        {
+            if (_parent) _depth = _parent->_depth + 1;
+            
+            if (_parent && _parent->_dynamic) _dynamic = true;
+            else _dynamic = stateset->getDataVariance()==osg::Object::DYNAMIC;
+        }
+            
+        ~StateGraph() {}
+        
+        StateGraph* cloneType() const { return new StateGraph; }
+        
+        void setUserData(osg::Referenced* obj) { _userData = obj; }
+        osg::Referenced* getUserData() { return _userData.get(); }
+        const osg::Referenced* getUserData() const { return _userData.get(); }
+        
+#ifdef OSGUTIL_RENDERBACKEND_USE_REF_PTR
+        const osg::StateSet* getStateSet() const { return _stateset.get(); }
+#else
+        const osg::StateSet* getStateSet() const { return _stateset; }
+#endif
+
+        /** return true if all of drawables, lights and children are empty.*/
+        inline bool empty() const
+        {
+            return _leaves.empty() && _children.empty();
+        }
+        
+        inline bool leaves_empty() const
+        {
+            return _leaves.empty();
+        }
+
+
+        inline float getAverageDistance() const
+        {
+            if (_averageDistance==FLT_MAX && !_leaves.empty())
+            {
+                _averageDistance = 0.0f;
+                for(LeafList::const_iterator itr=_leaves.begin();
+                    itr!=_leaves.end();
+                    ++itr)
+                {
+                   _averageDistance += (*itr)->_depth;
+                }
+                _averageDistance /= (float)_leaves.size();
+                
+            }
+            return _averageDistance;
+        }
+        
+        inline float getMinimumDistance() const
+        {
+            if (_minimumDistance==FLT_MAX && !_leaves.empty())
+            {
+                LeafList::const_iterator itr=_leaves.begin();
+                _minimumDistance = (*itr)->_depth;
+                ++itr;
+                for(;
+                    itr!=_leaves.end();
+                    ++itr)
+                {
+                   if ((*itr)->_depth<_minimumDistance) _minimumDistance=(*itr)->_depth;
+                }
+                
+            }
+            return _minimumDistance;
+        }
+
+        inline void sortFrontToBack()
+        {
+            std::sort(_leaves.begin(),_leaves.end(),LessDepthSortFunctor());
+        }
+
+        /** Reset the internal contents of a StateGraph, including deleting all children.*/
+        void reset();
+
+        /** Recursively clean the StateGraph of all its drawables, lights and depths.
+          * Leaves children intact, and ready to be populated again.*/
+        void clean();
+
+        /** Recursively prune the StateGraph of empty children.*/
+        void prune();
+        
+        
+        inline StateGraph* find_or_insert(const osg::StateSet* stateset)
+        {
+            // search for the appropriate state group, return it if found.
+            ChildList::iterator itr = _children.find(stateset);
+            if (itr!=_children.end()) return itr->second.get();
+            
+            // create a state group and insert it into the children list
+            // then return the state group.
+            StateGraph* sg = new StateGraph(this,stateset);
+            _children[stateset] = sg;
+            return sg;
+        }
+
+        /** add a render leaf.*/
+        inline void addLeaf(RenderLeaf* leaf)
+        {
+            if (leaf)
+            {
+                _averageDistance = FLT_MAX; // signify dirty.
+                _minimumDistance = FLT_MAX; // signify dirty.
+                _leaves.push_back(leaf);
+                leaf->_parent = this;
+                if (_dynamic) leaf->_dynamic = true;
+            }
+        }
+
+        static inline void moveStateGraph(osg::State& state,StateGraph* sg_curr,StateGraph* sg_new)
+        {
+            if (sg_new==sg_curr || sg_new==NULL) return;
+
+            if (sg_curr==NULL)
+            {
+
+                // use return path to trace back steps to sg_new.
+                std::vector<StateGraph*> return_path;
+
+                // need to pop back root render graph.
+                do 
+                {
+                    return_path.push_back(sg_new);
+                    sg_new = sg_new->_parent;
+                } while (sg_new);
+
+                for(std::vector<StateGraph*>::reverse_iterator itr=return_path.rbegin();
+                    itr!=return_path.rend();
+                    ++itr)
+                {
+                    StateGraph* rg = (*itr);
+                    if (rg->getStateSet()) state.pushStateSet(rg->getStateSet());
+                }
+                return;
+            }
+        
+
+            // first handle the typical case which is two state groups
+            // are neighbours.
+            if (sg_curr->_parent==sg_new->_parent)
+            {
+                
+                // state has changed so need to pop old state.
+                if (sg_curr->getStateSet()) state.popStateSet();
+                // and push new state.
+                if (sg_new->getStateSet()) state.pushStateSet(sg_new->getStateSet());
+                return;
+            }
+        
+
+            // need to pop back up to the same depth as the new state group.
+            while (sg_curr->_depth>sg_new->_depth)
+            {
+                if (sg_curr->getStateSet()) state.popStateSet();
+                sg_curr = sg_curr->_parent;
+            }
+            
+            // use return path to trace back steps to sg_new.
+            std::vector<StateGraph*> return_path;
+
+            // need to pop back up to the same depth as the curr state group.
+            while (sg_new->_depth>sg_curr->_depth)
+            {
+                return_path.push_back(sg_new);
+                sg_new = sg_new->_parent;
+            }
+            
+            // now pop back up both parent paths until they agree.
+
+            // DRT - 10/22/02
+            // should be this to conform with above case where two StateGraph
+            // nodes have the same parent
+            while (sg_curr != sg_new)
+            {
+                if (sg_curr->getStateSet()) state.popStateSet();
+                sg_curr = sg_curr->_parent;
+
+                return_path.push_back(sg_new);
+                sg_new = sg_new->_parent;
+            }
+            
+            for(std::vector<StateGraph*>::reverse_iterator itr=return_path.rbegin();
+                itr!=return_path.rend();
+                ++itr)
+            {
+                StateGraph* rg = (*itr);
+                if (rg->getStateSet()) state.pushStateSet(rg->getStateSet());
+            }
+
+        }
+
+        inline static void moveToRootStateGraph(osg::State& state,StateGraph* sg_curr)
+        {
+            // need to pop back all statesets and matrices.
+            while (sg_curr)
+            {
+                if (sg_curr->getStateSet()) state.popStateSet();
+                sg_curr = sg_curr->_parent;
+            }
+            
+        }
+        
+        inline static int numToPop(StateGraph* sg_curr)
+        {
+            int numToPop = 0;
+            // need to pop back all statesets and matrices.
+            while (sg_curr)
+            {
+                if (sg_curr->getStateSet()) ++numToPop;
+                sg_curr = sg_curr->_parent;
+            }
+            
+            return numToPop;
+        }
+
+    private:
+
+        /// disallow copy construction.
+        StateGraph(const StateGraph&):osg::Referenced() {}
+        /// disallow copy operator.
+        StateGraph& operator = (const StateGraph&) { return *this; }
+
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderStage
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderStage (revision 8447)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderStage (revision 8447)
@@ -0,0 +1,282 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_RENDERSTAGE
+#define OSGUTIL_RENDERSTAGE 1
+
+#include <osg/ColorMask>
+#include <osg/Viewport>
+#include <osg/Texture>
+#include <osg/FrameBufferObject>
+#include <osg/Camera>
+
+#include <osgUtil/RenderBin>
+#include <osgUtil/PositionalStateContainer>
+
+namespace osgUtil {
+
+/**
+ * RenderStage base class. Used for encapsulate a complete stage in
+ * rendering - setting up of viewport, the projection and model
+ * matrices and rendering the RenderBin's enclosed with this RenderStage.
+ * RenderStage also has a dependency list of other RenderStages, each
+ * of which must be called before the rendering of this stage.  These
+ * 'pre' rendering stages are used for advanced rendering techniques
+ * like multistage pixel shading or impostors.
+ */
+class OSGUTIL_EXPORT RenderStage : public RenderBin
+{
+    public:
+    
+
+        RenderStage();
+        RenderStage(SortMode mode);
+        
+        RenderStage(const RenderStage& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        virtual osg::Object* cloneType() const { return new RenderStage(); }
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new RenderStage(*this,copyop); } // note only implements a clone of type.
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const RenderStage*>(obj)!=0L; }
+        virtual const char* className() const { return "RenderStage"; }
+
+        virtual void reset();
+        
+        
+        /** Set the draw buffer used at the start of each frame draw. */
+        void setDrawBuffer(GLenum buffer) { _drawBuffer = buffer; }
+
+        /** Get the draw buffer used at the start of each frame draw. */
+        GLenum getDrawBuffer() const { return _drawBuffer; }
+
+        /** Set the read buffer for any required copy operations to use. */
+        void setReadBuffer(GLenum buffer) { _readBuffer = buffer; }
+
+        /** Get the read buffer for any required copy operations to use. */
+        GLenum getReadBuffer() const { return _readBuffer; }
+
+
+        /** Set the viewport.*/
+        void setViewport(osg::Viewport* viewport) { _viewport = viewport; }
+
+        /** Get the const viewport. */
+        const osg::Viewport* getViewport() const { return _viewport.get(); }
+
+        /** Get the viewport. */
+        osg::Viewport* getViewport() { return _viewport.get(); }
+
+        /** Set the clear mask used in glClear(..).
+          * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */
+        void setClearMask(GLbitfield mask) { _clearMask = mask; }
+
+        /** Get the clear mask.*/
+        GLbitfield getClearMask() const { return _clearMask; }
+
+
+        void setColorMask(osg::ColorMask* cm) { _colorMask = cm; }
+        osg::ColorMask* getColorMask() { return _colorMask.get(); }
+        const osg::ColorMask* getColorMask() const { return _colorMask.get(); }
+
+
+        /** Set the clear color used in glClearColor(..). 
+          * glClearColor is only called if mask & GL_COLOR_BUFFER_BIT is true*/
+        void setClearColor(const osg::Vec4& color) { _clearColor=color; }
+        
+        /** Get the clear color.*/
+        const osg::Vec4& getClearColor() const { return _clearColor; }
+        
+        /** Set the clear accum used in glClearAccum(..). 
+          * glClearAcumm is only called if mask & GL_ACCUM_BUFFER_BIT is true. */
+        void setClearAccum(const osg::Vec4& color) { _clearAccum=color; }
+        
+        /** Get the clear accum.*/
+        const osg::Vec4& getClearAccum() const { return _clearAccum; }
+        
+        /** Set the clear depth used in glClearDepth(..). Defaults to 1.0
+          * glClearDepth is only called if mask & GL_DEPTH_BUFFER_BIT is true. */
+        void setClearDepth(double depth) { _clearDepth=depth; }
+        
+        /** Get the clear depth.*/
+        double getClearDepth() const { return _clearDepth; }
+
+        /** Set the clear stencil value used in glClearStencil(). Defaults to 0;
+          * glClearStencil is only called if mask & GL_STENCIL_BUFFER_BIT is true*/
+        void setClearStencil(int stencil) { _clearStencil=stencil; }
+        
+        /** Get the clear color.*/
+        int getClearStencil() const { return _clearStencil; }
+        
+
+        void setCamera(osg::Camera* camera) { if (_camera!=camera) { _camera = camera; _cameraRequiresSetUp = true; } }
+        osg::Camera* getCamera() { return _camera; }
+        const osg::Camera* getCamera() const { return _camera; }
+
+        void setCameraRequiresSetUp(bool flag) { _cameraRequiresSetUp = flag; }
+        bool getCameraRequiresSetUp() const { return _cameraRequiresSetUp; }
+        
+        /** Attempt the set the RenderStage from the Camera settings.*/
+        void runCameraSetUp(osg::RenderInfo& renderInfo);
+        
+        void setTexture(osg::Texture* texture, unsigned int level = 0, unsigned int face=0) { _texture = texture; _level = level; _face = face; }
+        osg::Texture* getTexture() { return _texture.get(); }
+        
+        void setImage(osg::Image* image) { _image = image; }
+        osg::Image* getImage() { return _image.get(); }
+        
+        void setImageReadPixelFormat(GLenum format) { _imageReadPixelFormat = format; }
+        GLenum getImageReadPixelFormat() const { return _imageReadPixelFormat; }
+
+        void setImageReadPixelDataType(GLenum type) { _imageReadPixelDataType = type; }
+        GLenum getImageReadPixelDataType() const { return _imageReadPixelDataType; }
+
+        /** Set a framebuffer object to render into. It is permissible for the
+          * framebuffer object to be multisampled, in which case you should also
+          * set a resolve framebuffer object - see setMultisampleResolveFramebufferObject(). */
+        void setFrameBufferObject(osg::FrameBufferObject* fbo) { _fbo = fbo; }
+        osg::FrameBufferObject* getFrameBufferObject() { return _fbo.get(); }
+        const osg::FrameBufferObject* getFrameBufferObject() const { return _fbo.get(); }
+
+        /** Sets the destination framebuffer object for glBlitFramebufferEXT to
+          * resolve a multisampled framebuffer object after the RenderStage is
+          * drawn. The resolve framebuffer object must not be multisampled. The
+          * resolve framebuffer object is only necessary if the primary framebuffer
+          * object is multisampled, if not then leave it set to null. */
+        void setMultisampleResolveFramebufferObject(osg::FrameBufferObject* fbo);
+        osg::FrameBufferObject* getMultisampleResolveFramebufferObject() { return _resolveFbo.get(); }
+        const osg::FrameBufferObject* getMultisampleResolveFramebufferObject() const { return _resolveFbo.get(); }
+
+        /** Set whether the framebuffer object should be unbound after
+          * rendering. By default this is set to true. Set it to false if the
+          * unbinding is not required. */
+        void setDisableFboAfterRender(bool disable) {_disableFboAfterRender = disable;}
+        bool getDisableFboAfterRender() const {return _disableFboAfterRender;}
+
+        void setGraphicsContext(osg::GraphicsContext* context) { _graphicsContext = context; }
+        osg::GraphicsContext* getGraphicsContext() { return _graphicsContext.get(); }
+        const osg::GraphicsContext* getGraphicsContext() const { return _graphicsContext.get(); }
+
+
+
+
+        void setInheritedPositionalStateContainerMatrix(const osg::Matrix& matrix) { _inheritedPositionalStateContainerMatrix = matrix; }
+        const osg::Matrix& getInheritedPositionalStateContainerMatrix() const { return _inheritedPositionalStateContainerMatrix; }
+
+        void setInheritedPositionalStateContainer(PositionalStateContainer* rsl) { _inheritedPositionalStateContainer = rsl; }
+        PositionalStateContainer* getInheritedPositionalStateContainer() { return _inheritedPositionalStateContainer.get(); }
+
+        void setPositionalStateContainer(PositionalStateContainer* rsl) { _renderStageLighting = rsl; }
+
+        PositionalStateContainer* getPositionalStateContainer() const
+        {
+            if (!_renderStageLighting.valid()) _renderStageLighting = new PositionalStateContainer;
+            return _renderStageLighting.get();
+        }
+
+        virtual void addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+        {
+            getPositionalStateContainer()->addPositionedAttribute(matrix,attr);
+        }
+        
+        virtual void addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+        {
+            getPositionalStateContainer()->addPositionedTextureAttribute(textureUnit, matrix,attr);
+        }
+
+        void copyTexture(osg::RenderInfo& renderInfo);
+
+        virtual void sort();
+        
+        virtual void drawPreRenderStages(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+        virtual void draw(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+        virtual void drawInner(osg::RenderInfo& renderInfo,RenderLeaf*& previous, bool& doCopyTexture);
+    
+        virtual void drawPostRenderStages(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+        virtual void drawImplementation(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+
+        void addToDependencyList(RenderStage* rs) { addPreRenderStage(rs); }
+
+        void addPreRenderStage(RenderStage* rs, int order = 0);
+        
+        void addPostRenderStage(RenderStage* rs, int order = 0);
+
+        /** Extract stats for current draw list. */
+        bool getStats(Statistics& stats) const; 
+ 
+        /** Compute the number of dynamic RenderLeaves.*/
+        virtual unsigned int computeNumberOfDynamicRenderLeaves() const;
+
+        struct Attachment
+        {
+            osg::ref_ptr<osg::Image>                _image;
+            GLenum                                  _imageReadPixelFormat;
+            GLenum                                  _imageReadPixelDataType;
+        };
+       
+        void attach(osg::Camera::BufferComponent buffer, osg::Image* image);
+        
+    protected:
+        
+        virtual ~RenderStage();
+
+        typedef std::pair< int , osg::ref_ptr<RenderStage> > RenderStageOrderPair;
+        typedef std::list< RenderStageOrderPair > RenderStageList;
+
+        bool                                _stageDrawnThisFrame;
+        RenderStageList                     _preRenderList;
+        RenderStageList                     _postRenderList;
+
+        // viewport x,y,width,height.
+        osg::ref_ptr<osg::Viewport>         _viewport;
+        
+        GLenum                              _drawBuffer;
+        GLenum                              _readBuffer;
+        GLbitfield                          _clearMask;
+        osg::ref_ptr<osg::ColorMask>        _colorMask;
+        osg::Vec4                           _clearColor;
+        osg::Vec4                           _clearAccum;
+        double                              _clearDepth;
+        int                                 _clearStencil;
+
+        bool                                _cameraRequiresSetUp;
+        osg::Camera*                        _camera;
+        
+        osg::ref_ptr<osg::Texture>              _texture;
+        unsigned int                            _level;
+        unsigned int                            _face;
+
+        osg::ref_ptr<osg::Image>                _image;
+        GLenum                                  _imageReadPixelFormat;
+        GLenum                                  _imageReadPixelDataType;
+        
+        std::map< osg::Camera::BufferComponent, Attachment> _bufferAttachmentMap;
+        
+        osg::ref_ptr<osg::FrameBufferObject>    _fbo;
+        osg::ref_ptr<osg::FrameBufferObject>    _resolveFbo;
+        osg::ref_ptr<osg::GraphicsContext>      _graphicsContext;
+        bool                                    _disableFboAfterRender;
+
+        mutable osg::Matrix                         _inheritedPositionalStateContainerMatrix;
+        mutable osg::ref_ptr<PositionalStateContainer>   _inheritedPositionalStateContainer;
+        mutable osg::ref_ptr<PositionalStateContainer>   _renderStageLighting;
+        
+    
+
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderLeaf
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderLeaf (revision 7328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderLeaf (revision 7328)
@@ -0,0 +1,113 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_RENDERLEAF
+#define OSGUTIL_RENDERLEAF 1
+
+#include <osg/ref_ptr>
+#include <osg/Matrix>
+#include <osg/Drawable>
+#include <osg/State>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+#define OSGUTIL_RENDERBACKEND_USE_REF_PTR
+
+// Forward declare StateGraph
+class StateGraph;
+
+/** Container class for all data required for rendering of drawables.
+  */
+class OSGUTIL_EXPORT RenderLeaf : public osg::Referenced
+{
+    public:
+    
+
+        inline RenderLeaf(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* modelview, float depth=0.0f):
+            osg::Referenced(false),
+            _parent(0),
+            _drawable(drawable),
+            _projection(projection),
+            _modelview(modelview),
+            _depth(depth)
+        {
+            _dynamic = (drawable->getDataVariance()==osg::Object::DYNAMIC);
+        }
+
+        
+        inline void set(osg::Drawable* drawable,osg::RefMatrix* projection,osg::RefMatrix* modelview, float depth=0.0f)
+        {
+            _parent = 0;
+            _drawable = drawable;
+            _projection = projection,
+            _modelview = modelview,
+            _depth = depth;
+            _dynamic = (drawable->getDataVariance()==osg::Object::DYNAMIC);
+        }
+        
+        inline void reset()
+        {
+            _parent = 0;
+            _drawable = 0;
+            _projection = 0;
+            _modelview = 0;
+            _depth = 0.0f;
+            _dynamic = false;
+        }
+    
+        virtual void render(osg::RenderInfo& renderInfo,RenderLeaf* previous);
+        
+        /// Allow StateGraph to change the RenderLeaf's _parent.
+        friend class osgUtil::StateGraph;
+
+    public:
+    
+    
+    
+        StateGraph*                     _parent;
+
+#ifdef OSGUTIL_RENDERBACKEND_USE_REF_PTR
+        osg::ref_ptr<osg::Drawable>     _drawable;
+        const osg::Drawable* getDrawable() const { return _drawable.get(); }
+#else
+        osg::Drawable*                  _drawable;
+        const osg::Drawable* getDrawable() const { return _drawable; }
+#endif        
+        osg::ref_ptr<osg::RefMatrix>    _projection;
+        osg::ref_ptr<osg::RefMatrix>    _modelview;
+        float                           _depth;
+        bool                            _dynamic;
+
+    private:
+
+        /// disallow creation of blank RenderLeaf as this isn't useful.
+        RenderLeaf():
+            osg::Referenced(false),
+            _parent(0),
+            _drawable(0),
+            _projection(0),
+            _modelview(0),
+            _depth(0.0f) {}
+
+        /// disallow copy construction.
+        RenderLeaf(const RenderLeaf&):osg::Referenced(false) {}
+        /// disallow copy operator.
+        RenderLeaf& operator = (const RenderLeaf&) { return *this; }
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/EdgeCollector
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/EdgeCollector (revision 7781)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/EdgeCollector (revision 7781)
@@ -0,0 +1,210 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_EDGECOLLECTOR
+#define OSGUTIL_EDGECOLLECTOR 1
+
+
+#include <set>
+#include <map>
+#include <list>
+#include <vector>
+#include <algorithm>
+
+#include <osg/Array>
+#include <osg/Geometry>
+#include <osg/ref_ptr>
+
+#include <osgUtil/Export>
+
+
+namespace osgUtil {
+
+    struct dereference_less
+    {
+        template<class T, class U>
+        inline bool operator() (const T& lhs,const U& rhs) const
+        {
+            return *lhs < *rhs;
+        }
+    };
+
+    template<class T>
+    bool dereference_check_less(const T& lhs,const T& rhs)
+    {
+        if (lhs==rhs) return false;
+        if (!lhs) return true;
+        if (!rhs) return false;
+        return *lhs < *rhs;
+    }
+
+    struct dereference_clear
+    {
+        template<class T>
+        inline void operator() (const T& t)
+        {
+            T& non_const_t = const_cast<T&>(t);
+            non_const_t->clear();
+        }
+    };
+
+
+class OSGUTIL_EXPORT EdgeCollector
+{
+public:
+    
+    struct Triangle;
+    struct Edge;
+    struct Edgeloop;
+    struct Point;
+
+    typedef std::list<osg::ref_ptr<osg::UIntArray> > IndexArrayList;
+    
+    ~EdgeCollector();
+
+    void setGeometry(osg::Geometry* geometry);
+    osg::Geometry* getGeometry() { return _geometry; }
+
+    unsigned int getNumOfTriangles() { return _triangleSet.size(); }
+
+    typedef std::set<osg::ref_ptr<Edge>,dereference_less >                      EdgeSet;
+    typedef std::vector<osg::ref_ptr<Edge> >                                    EdgeList;
+    typedef std::list< osg::ref_ptr<Edgeloop> >                                 EdgeloopList;
+    typedef std::set< osg::ref_ptr<Point>,dereference_less >                    PointSet;
+    typedef std::vector< osg::ref_ptr<Point> >                                  PointList;
+    typedef std::list< osg::ref_ptr<Triangle> >                                 TriangleList;
+    typedef std::set< osg::ref_ptr<Triangle> >                                  TriangleSet;
+    typedef std::map< osg::ref_ptr<Triangle>, unsigned int, dereference_less >  TriangleMap;
+
+    struct OSGUTIL_EXPORT Point : public osg::Referenced
+    {
+        Point(): _protected(false), _index(0) {}
+        
+        bool _protected;
+
+        unsigned int _index;
+
+        osg::Vec3d          _vertex;
+        TriangleSet         _triangles;
+
+        void clear() { _triangles.clear(); }
+
+        bool operator < ( const Point& rhs) const { return _vertex < rhs._vertex; }
+        
+        bool isBoundaryPoint() const;
+    };
+
+    struct OSGUTIL_EXPORT Edge : public osg::Referenced
+    {
+        void clear();
+
+        osg::ref_ptr<Point> _p1;
+        osg::ref_ptr<Point> _p2;
+        
+        osg::ref_ptr<Point> _op1;
+        osg::ref_ptr<Point> _op2;
+        
+        TriangleSet _triangles;
+
+        
+        bool operator < ( const Edge& rhs) const;
+        
+        bool operator == ( const Edge& rhs) const;
+
+        bool operator != ( const Edge& rhs) const;
+        
+        void setOrderedPoints(Point* p1, Point* p2);
+        
+        void addTriangle(Triangle* triangle) { _triangles.insert(triangle); }
+        
+        bool isBoundaryEdge() const { return _triangles.size()<=1; }
+        
+        bool isAdjacentToBoundary() const { return isBoundaryEdge() || _p1->isBoundaryPoint() || _p2->isBoundaryPoint(); }
+        
+        bool endConnected(const Edge& rhs) const { return (_op2 == rhs._op1); }
+        
+        bool beginConnected(const Edge& rhs) const { return (_op1 == rhs._op2); }
+    };
+
+    struct OSGUTIL_EXPORT Triangle : public osg::Referenced
+    {
+        Triangle() {}
+        
+        void clear();
+
+        bool operator < (const Triangle& rhs) const;
+
+        void setOrderedPoints(Point* p1, Point* p2, Point* p3);
+        
+        float distance(const osg::Vec3& vertex) const { return _plane.distance(vertex); }
+        
+        bool isBoundaryTriangle() const
+        { return (_e1->isBoundaryEdge() || _e2->isBoundaryEdge() ||  _e3->isBoundaryEdge()); }
+
+       
+        osg::ref_ptr<Point> _p1;
+        osg::ref_ptr<Point> _p2;
+        osg::ref_ptr<Point> _p3;
+        
+        osg::ref_ptr<Point> _op1;
+        osg::ref_ptr<Point> _op2;
+        osg::ref_ptr<Point> _op3;
+        
+        osg::ref_ptr<Edge> _e1;
+        osg::ref_ptr<Edge> _e2;
+        osg::ref_ptr<Edge> _e3;
+        
+        osg::Plane _plane;        
+    };
+
+    struct OSGUTIL_EXPORT Edgeloop : public osg::Referenced
+    {
+        typedef std::vector<osg::ref_ptr<Edge> > EdgeList;
+        
+        bool isClosed() { return (_edgeList.back()->endConnected(*_edgeList.front().get())); }
+        
+        osg::UIntArray * toIndexArray() const;
+        
+        EdgeList _edgeList;
+    };
+
+
+    
+    Triangle* addTriangle(unsigned int p1, unsigned int p2, unsigned int p3);
+    Triangle* addTriangle(Point* p1, Point* p2, Point* p3);
+
+    Edge* addEdge(Triangle* triangle, Point* p1, Point* p2);
+    
+    Point* addPoint(Triangle* triangle, unsigned int p1) { return addPoint(triangle,_originalPointList[p1].get()); }
+    Point* addPoint(Triangle* triangle, Point* point);
+    
+    void getBoundaryEdgeList(EdgeList & el);
+    bool extractBoundaryEdgeloop(EdgeList & el, Edgeloop & edgeloop);
+    bool extractBoundaryEdgeloopList(EdgeList & el, EdgeloopList & edgeloopList);
+    
+    void getEdgeloopIndexList(IndexArrayList & ial);
+    
+//protected:
+    
+    osg::Geometry*                  _geometry;
+    
+    EdgeSet                         _edgeSet;
+    TriangleSet                     _triangleSet;
+    PointSet                        _pointSet;
+    PointList                       _originalPointList;
+    
+};
+
+} // end of osgUtil namespace
+
+#endif // ** OSGUTIL_EDGECOLLECTOR ** //
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ConvertVec
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ConvertVec (revision 7724)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ConvertVec (revision 7724)
@@ -0,0 +1,139 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_CONVERTVEC
+#define OSGUTIL_CONVERTVEC 1
+
+namespace osgUtil {
+
+template <typename InType, typename OutType, 
+          unsigned int InSize = InType::num_components, 
+          unsigned int OutSize = OutType::num_components>
+struct ConvertVec
+{
+    static void convert(InType & in, OutType & out)
+    {}
+};
+
+
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 2, 2>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y())); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 2, 3>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y()), 
+                static_cast<typename OutType::value_type>(0.0)); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 2, 4>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y()), 
+                static_cast<typename OutType::value_type>(0.0), 
+                static_cast<typename OutType::value_type>(1.0)); 
+    }
+};
+
+
+
+
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 3, 2>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y())); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 3, 3>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y()), 
+                static_cast<typename OutType::value_type>(in.z())); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 3, 4>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y()), 
+                static_cast<typename OutType::value_type>(in.z()), 
+                static_cast<typename OutType::value_type>(1.0)); 
+    }
+};
+
+
+
+
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 4, 2>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()/in.w()), 
+                static_cast<typename OutType::value_type>(in.y()/in.w())); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 4, 3>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()/in.w()), 
+                static_cast<typename OutType::value_type>(in.y()/in.w()), 
+                static_cast<typename OutType::value_type>(in.z()/in.w())); 
+    }
+};
+
+template <typename InType, typename OutType>
+struct ConvertVec<InType, OutType, 4, 4>
+{
+    static void convert(InType & in, OutType & out)
+    { 
+        out.set(static_cast<typename OutType::value_type>(in.x()), 
+                static_cast<typename OutType::value_type>(in.y()), 
+                static_cast<typename OutType::value_type>(in.z()), 
+                static_cast<typename OutType::value_type>(in.w())); 
+    }
+};
+
+} // end of osg namespace
+
+#endif // ** OSG_CONVERTVEC ** //
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Export
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Export (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Export (revision 5328)
@@ -0,0 +1,50 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+// The following symbol has a underscore suffix for compatibility.
+#ifndef OSGUTIL_EXPORT_
+#define OSGUTIL_EXPORT_ 1
+
+#if defined(_MSC_VER)
+    #pragma warning( disable : 4244 )
+    #pragma warning( disable : 4251 )
+    #pragma warning( disable : 4267 )
+    #pragma warning( disable : 4275 )
+    #pragma warning( disable : 4290 )
+    #pragma warning( disable : 4786 )
+    #pragma warning( disable : 4305 )
+    #pragma warning( disable : 4996 )
+#endif
+
+#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__)
+    #  if defined( OSG_LIBRARY_STATIC )
+    #    define OSGUTIL_EXPORT
+    #  elif defined( OSGUTIL_LIBRARY )
+    #    define OSGUTIL_EXPORT   __declspec(dllexport)
+    #  else
+    #    define OSGUTIL_EXPORT   __declspec(dllimport)
+    #endif
+#else
+    #define OSGUTIL_EXPORT 
+#endif 
+
+/**
+
+\namespace osgUtil
+
+The osgUtil library provides general purpose utility classes such as update, cull and draw traverses, scene graph operators such a scene graph optimisation, tri stripping, and tessellation.
+
+*/
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Optimizer
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Optimizer (revision 9245)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Optimizer (revision 9245)
@@ -0,0 +1,847 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_OPTIMIZER
+#define OSGUTIL_OPTIMIZER
+
+#include <osg/NodeVisitor>
+#include <osg/Matrix>
+#include <osg/Geometry>
+#include <osg/Transform>
+#include <osg/Texture2D>
+
+#include <osgUtil/Export>
+
+#include <set>
+
+namespace osgUtil {
+
+// forward declare
+class Optimizer;
+
+/** Helper base class for implementing Optimizer techniques.*/
+class OSGUTIL_EXPORT BaseOptimizerVisitor : public osg::NodeVisitor
+{
+    public:
+
+        BaseOptimizerVisitor(Optimizer* optimizer, unsigned int operation):
+            osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
+            _optimizer(optimizer),
+            _operationType(operation)
+        {
+            setNodeMaskOverride(0xffffffff);
+        }
+
+        inline bool isOperationPermissibleForObject(const osg::StateSet* object) const;
+        inline bool isOperationPermissibleForObject(const osg::StateAttribute* object) const;
+        inline bool isOperationPermissibleForObject(const osg::Drawable* object) const;        
+        inline bool isOperationPermissibleForObject(const osg::Node* object) const;
+
+    protected:
+
+        Optimizer*      _optimizer;
+        unsigned int _operationType;
+};
+
+/** Traverses scene graph to improve efficiency. See OptimizationOptions.
+  * For example of usage see examples/osgimpostor or osgviewer.
+  */
+  
+class OSGUTIL_EXPORT Optimizer
+{
+
+    public:
+
+        Optimizer() {}
+        virtual ~Optimizer() {}
+
+        enum OptimizationOptions
+        {
+            FLATTEN_STATIC_TRANSFORMS = (1 << 0),
+            REMOVE_REDUNDANT_NODES =    (1 << 1),
+            REMOVE_LOADED_PROXY_NODES = (1 << 2),
+            COMBINE_ADJACENT_LODS =     (1 << 3),
+            SHARE_DUPLICATE_STATE =     (1 << 4),
+            MERGE_GEOMETRY =            (1 << 5),
+            CHECK_GEOMETRY =            (1 << 6),
+            SPATIALIZE_GROUPS =         (1 << 7),
+            COPY_SHARED_NODES =         (1 << 8),
+            TRISTRIP_GEOMETRY =         (1 << 9),
+            TESSELLATE_GEOMETRY =       (1 << 10),
+            OPTIMIZE_TEXTURE_SETTINGS = (1 << 11),
+            MERGE_GEODES =              (1 << 12),
+            FLATTEN_BILLBOARDS =        (1 << 13),
+            TEXTURE_ATLAS_BUILDER =     (1 << 14),
+            STATIC_OBJECT_DETECTION =   (1 << 15),
+            FLATTEN_STATIC_TRANSFORMS_DUPLICATING_SHARED_SUBGRAPHS = (1 << 16),
+            DEFAULT_OPTIMIZATIONS = FLATTEN_STATIC_TRANSFORMS |
+                                REMOVE_REDUNDANT_NODES |
+                                REMOVE_LOADED_PROXY_NODES |
+                                COMBINE_ADJACENT_LODS |
+                                SHARE_DUPLICATE_STATE |
+                                MERGE_GEOMETRY |
+                                CHECK_GEOMETRY |
+                                OPTIMIZE_TEXTURE_SETTINGS |
+                                STATIC_OBJECT_DETECTION,
+            ALL_OPTIMIZATIONS = FLATTEN_STATIC_TRANSFORMS_DUPLICATING_SHARED_SUBGRAPHS |
+                                REMOVE_REDUNDANT_NODES |
+                                REMOVE_LOADED_PROXY_NODES |
+                                COMBINE_ADJACENT_LODS |
+                                SHARE_DUPLICATE_STATE |
+                                MERGE_GEODES |
+                                MERGE_GEOMETRY |
+                                CHECK_GEOMETRY |
+                                SPATIALIZE_GROUPS |
+                                COPY_SHARED_NODES |
+                                TRISTRIP_GEOMETRY |
+                                OPTIMIZE_TEXTURE_SETTINGS |
+                                TEXTURE_ATLAS_BUILDER |
+                                STATIC_OBJECT_DETECTION
+        };
+
+        /** Reset internal data to initial state - the getPermissibleOptionsMap is cleared.*/
+        void reset();
+        
+        /** Traverse the node and its subgraph with a series of optimization
+          * visitors, specified by the OptimizationOptions.*/
+        void optimize(osg::Node* node);
+
+        /** Traverse the node and its subgraph with a series of optimization
+          * visitors, specified by the OptimizationOptions.*/
+        virtual void optimize(osg::Node* node, unsigned int options);
+
+
+        /** Callback for customizing what operations are permitted on objects in the scene graph.*/        
+        struct IsOperationPermissibleForObjectCallback : public osg::Referenced
+        {
+            virtual bool isOperationPermissibleForObjectImplementation(const Optimizer* optimizer, const osg::StateSet* stateset,unsigned int option) const
+            {
+                return optimizer->isOperationPermissibleForObjectImplementation(stateset,option);
+            }
+            
+            virtual bool isOperationPermissibleForObjectImplementation(const Optimizer* optimizer, const osg::StateAttribute* attribute,unsigned int option) const
+            {
+                return optimizer->isOperationPermissibleForObjectImplementation(attribute,option);
+            }
+            
+            virtual bool isOperationPermissibleForObjectImplementation(const Optimizer* optimizer, const osg::Drawable* drawable,unsigned int option) const
+            {
+                return optimizer->isOperationPermissibleForObjectImplementation(drawable,option);
+            }
+            
+            virtual bool isOperationPermissibleForObjectImplementation(const Optimizer* optimizer, const osg::Node* node,unsigned int option) const
+            {
+                return optimizer->isOperationPermissibleForObjectImplementation(node,option);
+            }
+            
+        };
+        
+        /** Set the callback for customizing what operations are permitted on objects in the scene graph.*/        
+        void setIsOperationPermissibleForObjectCallback(IsOperationPermissibleForObjectCallback* callback) { _isOperationPermissibleForObjectCallback=callback; }
+
+        /** Get the callback for customizing what operations are permitted on objects in the scene graph.*/        
+        IsOperationPermissibleForObjectCallback* getIsOperationPermissibleForObjectCallback() { return _isOperationPermissibleForObjectCallback.get(); }
+
+        /** Get the callback for customizing what operations are permitted on objects in the scene graph.*/        
+        const IsOperationPermissibleForObjectCallback* getIsOperationPermissibleForObjectCallback() const { return _isOperationPermissibleForObjectCallback.get(); }
+
+
+        inline void setPermissibleOptimizationsForObject(const osg::Object* object, unsigned int options)
+        {
+            _permissibleOptimizationsMap[object] = options;
+        }
+        
+        inline unsigned int getPermissibleOptimizationsForObject(const osg::Object* object) const
+        {
+            PermissibleOptimizationsMap::const_iterator itr = _permissibleOptimizationsMap.find(object);
+            if (itr!=_permissibleOptimizationsMap.end()) return itr->second;
+            else return 0xffffffff;
+        }
+
+
+        inline bool isOperationPermissibleForObject(const osg::StateSet* object, unsigned int option) const
+        {
+            if (_isOperationPermissibleForObjectCallback.valid())
+                return _isOperationPermissibleForObjectCallback->isOperationPermissibleForObjectImplementation(this,object,option);
+            else 
+                return isOperationPermissibleForObjectImplementation(object,option); 
+        }
+
+        inline bool isOperationPermissibleForObject(const osg::StateAttribute* object, unsigned int option) const
+        {
+            if (_isOperationPermissibleForObjectCallback.valid())
+                return _isOperationPermissibleForObjectCallback->isOperationPermissibleForObjectImplementation(this,object,option);
+            else 
+                return isOperationPermissibleForObjectImplementation(object,option); 
+        }
+
+        inline bool isOperationPermissibleForObject(const osg::Drawable* object, unsigned int option) const
+        {
+            if (_isOperationPermissibleForObjectCallback.valid())
+                return _isOperationPermissibleForObjectCallback->isOperationPermissibleForObjectImplementation(this,object,option);
+            else 
+                return isOperationPermissibleForObjectImplementation(object,option); 
+        }
+
+        inline bool isOperationPermissibleForObject(const osg::Node* object, unsigned int option) const
+        {
+            if (_isOperationPermissibleForObjectCallback.valid())
+                return _isOperationPermissibleForObjectCallback->isOperationPermissibleForObjectImplementation(this,object,option);
+            else 
+                return isOperationPermissibleForObjectImplementation(object,option); 
+        }
+
+        bool isOperationPermissibleForObjectImplementation(const osg::StateSet* stateset, unsigned int option) const
+        {
+            return (option & getPermissibleOptimizationsForObject(stateset))!=0;
+        }
+        
+        bool isOperationPermissibleForObjectImplementation(const osg::StateAttribute* attribute, unsigned int option) const
+        {
+            return (option & getPermissibleOptimizationsForObject(attribute))!=0;
+        }
+
+        bool isOperationPermissibleForObjectImplementation(const osg::Drawable* drawable, unsigned int option) const
+        {
+            if (option & (REMOVE_REDUNDANT_NODES|MERGE_GEOMETRY))
+            {
+                if (drawable->getUserData()) return false;
+                if (drawable->getUpdateCallback()) return false;
+                if (drawable->getEventCallback()) return false;
+                if (drawable->getCullCallback()) return false;
+            }
+            return (option & getPermissibleOptimizationsForObject(drawable))!=0;
+        }
+
+        bool isOperationPermissibleForObjectImplementation(const osg::Node* node, unsigned int option) const
+        {
+            if (option & (REMOVE_REDUNDANT_NODES|COMBINE_ADJACENT_LODS|FLATTEN_STATIC_TRANSFORMS))
+            {
+                if (node->getUserData()) return false;
+                if (node->getUpdateCallback()) return false;
+                if (node->getEventCallback()) return false;
+                if (node->getCullCallback()) return false;
+                if (node->getNumDescriptions()>0) return false;
+                if (node->getStateSet()) return false;
+                if (node->getNodeMask()!=0xffffffff) return false;
+                // if (!node->getName().empty()) return false;
+            }
+
+            return (option & getPermissibleOptimizationsForObject(node))!=0;
+        }
+        
+    protected:
+
+        osg::ref_ptr<IsOperationPermissibleForObjectCallback> _isOperationPermissibleForObjectCallback;
+
+        typedef std::map<const osg::Object*,unsigned int> PermissibleOptimizationsMap;
+        PermissibleOptimizationsMap _permissibleOptimizationsMap;    
+    
+    public:
+
+        /** Flatten Static Transform nodes by applying their transform to the
+          * geometry on the leaves of the scene graph, then removing the 
+          * now redundant transforms.  Static transformed Subgraphs that have multiple
+          * parental paths above them are not flattened, if you require this then
+          * the subgraphs have to be duplicated - for this use the 
+          * FlattenStaticTransformsDuplicatingSharedSubgraphsVisitor. */
+        class OSGUTIL_EXPORT FlattenStaticTransformsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                FlattenStaticTransformsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, FLATTEN_STATIC_TRANSFORMS) {}
+
+                virtual void apply(osg::Node& geode);
+                virtual void apply(osg::Geode& geode);
+                virtual void apply(osg::Billboard& geode);
+                virtual void apply(osg::ProxyNode& node);
+                virtual void apply(osg::PagedLOD& node);
+                virtual void apply(osg::Transform& transform);
+
+                bool removeTransforms(osg::Node* nodeWeCannotRemove);
+
+            protected:
+
+                typedef std::vector<osg::Transform*>                TransformStack;
+                typedef std::set<osg::Drawable*>                    DrawableSet;
+                typedef std::set<osg::Billboard*>                   BillboardSet;
+                typedef std::set<osg::Node* >                       NodeSet;
+                typedef std::set<osg::Transform*>                   TransformSet;
+                
+                TransformStack  _transformStack;
+                NodeSet         _excludedNodeSet;
+                DrawableSet     _drawableSet;
+                BillboardSet    _billboardSet;
+                TransformSet    _transformSet;
+        };
+
+        /** FlattenStaticTransformsDuplicatingSharedSubgraphsVisitor is similar to
+          * to FlattenStaticTransformsVisitor in that is desgined to remove static transforms
+          * from the scene graph, pushing down the transforms to the geometry leaves of the scene graph,
+          * but with the difference that any subgraphs that are shared between different transforms
+          * of duplicated and flatten individually.  This results in more static transforms
+          * being removed, but also means that more data is generated, and as a result may
+          * not always be the most appropriate flatten visitor to use.*/  
+        class OSGUTIL_EXPORT FlattenStaticTransformsDuplicatingSharedSubgraphsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                FlattenStaticTransformsDuplicatingSharedSubgraphsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, FLATTEN_STATIC_TRANSFORMS_DUPLICATING_SHARED_SUBGRAPHS) {}
+
+                virtual void reset();
+
+                virtual void apply(osg::Group& group);
+                virtual void apply(osg::Transform& transform);
+                virtual void apply(osg::LOD& lod);
+                virtual void apply(osg::Geode& geode);
+                virtual void apply(osg::Billboard& billboard);
+
+            protected:
+
+                void transformGeode(osg::Geode& geode);
+                void transformDrawable(osg::Drawable& drawable);
+                void transformBillboard(osg::Billboard& billboard);
+
+                std::vector<osg::Matrix> _matrixStack;
+
+        };
+
+        /** Combine Static Transform nodes that sit above one another.*/        
+        class OSGUTIL_EXPORT CombineStaticTransformsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                CombineStaticTransformsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, FLATTEN_STATIC_TRANSFORMS) {}
+
+                virtual void apply(osg::MatrixTransform& transform);
+
+                bool removeTransforms(osg::Node* nodeWeCannotRemove);
+
+            protected:
+
+                typedef std::set<osg::MatrixTransform*> TransformSet;
+                TransformSet  _transformSet;
+        };
+
+        /** Remove rendundant nodes, such as groups with one single child.*/
+        class OSGUTIL_EXPORT RemoveEmptyNodesVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+
+                typedef std::set<osg::Node*> NodeList;
+                NodeList                     _redundantNodeList;
+
+                RemoveEmptyNodesVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, REMOVE_REDUNDANT_NODES) {}
+
+                virtual void apply(osg::Geode& geode);
+                virtual void apply(osg::Group& group);
+                
+                void removeEmptyNodes();
+
+        };
+
+        /** Remove redundant nodes, such as groups with one single child.*/
+        class OSGUTIL_EXPORT RemoveRedundantNodesVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                typedef std::set<osg::Node*> NodeList;
+                NodeList                     _redundantNodeList;
+
+                RemoveRedundantNodesVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, REMOVE_REDUNDANT_NODES) {}
+                
+                virtual void apply(osg::Group& group);
+                virtual void apply(osg::Transform& transform);
+                
+                bool isOperationPermissible(osg::Node& node);
+                
+                void removeRedundantNodes();
+
+        };
+
+        /** Remove loaded proxy nodes.*/
+        class OSGUTIL_EXPORT RemoveLoadedProxyNodesVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                typedef std::set<osg::Node*> NodeList;
+                NodeList                     _redundantNodeList;
+
+                RemoveLoadedProxyNodesVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, REMOVE_LOADED_PROXY_NODES) {}
+                
+                virtual void apply(osg::ProxyNode& group);
+                
+                void removeRedundantNodes();
+
+        };
+
+        /** Tessellate all geodes, to remove POLYGONS.*/
+        class OSGUTIL_EXPORT TessellateVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                typedef std::set<osg::Group*>  GroupList;
+                GroupList                      _groupList;
+
+                TessellateVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, TESSELLATE_GEOMETRY) {}
+
+                virtual void apply(osg::Geode& geode);
+
+        };
+
+        /** Optimize the LOD groups, by combining adjacent LOD's which have
+          * complementary ranges.*/
+        class OSGUTIL_EXPORT CombineLODsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                typedef std::set<osg::Group*>  GroupList;
+                GroupList                      _groupList;
+
+                CombineLODsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, COMBINE_ADJACENT_LODS) {}
+
+                virtual void apply(osg::LOD& lod);
+
+                void combineLODs();
+
+        };
+ 
+        /** Optimize State in the scene graph by removing duplicate state,
+          * replacing it with shared instances, both for StateAttributes,
+          * and whole StateSets.*/
+        class OSGUTIL_EXPORT StateVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                StateVisitor(bool combineDynamicState,
+                             bool combineStaticState,
+                             bool combineUnspecifiedState,
+                             Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, SHARE_DUPLICATE_STATE)
+                {
+                    _optimize[osg::Object::DYNAMIC] = combineDynamicState;
+                    _optimize[osg::Object::STATIC] = combineStaticState;
+                    _optimize[osg::Object::UNSPECIFIED] = combineUnspecifiedState;
+                }
+
+                /** empty visitor, make it ready for next traversal.*/        
+                virtual void reset();
+
+                virtual void apply(osg::Node& node);
+
+                virtual void apply(osg::Geode& geode);
+
+                void optimize();
+
+            protected:
+
+                void addStateSet(osg::StateSet* stateset,osg::Object* obj);
+                
+                inline bool optimize(osg::Object::DataVariance variance)
+                {
+                    return _optimize[variance];
+                }
+
+                typedef std::set<osg::Object*>              ObjectSet;
+                typedef std::map<osg::StateSet*,ObjectSet>  StateSetMap;
+
+                // note, one element for DYNAMIC, STATIC and UNSPECIFIED
+                bool _optimize[3];
+                
+                StateSetMap _statesets;
+
+        };
+
+        /** Combine geodes
+          */
+        class OSGUTIL_EXPORT MergeGeodesVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                MergeGeodesVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, MERGE_GEODES) {}
+
+                virtual void apply(osg::Group& group);
+
+                bool mergeGeodes(osg::Group& group);
+
+            protected:
+
+                bool mergeGeode(osg::Geode& lhs, osg::Geode& rhs);
+
+        };
+
+        class OSGUTIL_EXPORT CheckGeometryVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                CheckGeometryVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, CHECK_GEOMETRY) {}
+
+                virtual void apply(osg::Geode& geode) { checkGeode(geode); }
+
+                void checkGeode(osg::Geode& geode);
+                
+        };
+        
+        class OSGUTIL_EXPORT MergeGeometryVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                MergeGeometryVisitor(Optimizer* optimizer=0) :
+                    BaseOptimizerVisitor(optimizer, MERGE_GEOMETRY),
+                    _targetMaximumNumberOfVertices(10000) {}
+
+                void setTargetMaximumNumberOfVertices(unsigned int num)
+                {
+                    _targetMaximumNumberOfVertices = num;
+                }
+                
+                unsigned int getTargetMaximumNumberOfVertices() const
+                {
+                    return _targetMaximumNumberOfVertices;
+                }
+
+                virtual void apply(osg::Geode& geode) { mergeGeode(geode); }
+                virtual void apply(osg::Billboard&) { /* don't do anything*/ }
+
+                bool mergeGeode(osg::Geode& geode);
+
+                static bool geometryContainsSharedArrays(osg::Geometry& geom);
+
+                static bool mergeGeometry(osg::Geometry& lhs,osg::Geometry& rhs);
+
+                static bool mergePrimitive(osg::DrawArrays& lhs,osg::DrawArrays& rhs);
+                static bool mergePrimitive(osg::DrawArrayLengths& lhs,osg::DrawArrayLengths& rhs);
+                static bool mergePrimitive(osg::DrawElementsUByte& lhs,osg::DrawElementsUByte& rhs);
+                static bool mergePrimitive(osg::DrawElementsUShort& lhs,osg::DrawElementsUShort& rhs);
+                static bool mergePrimitive(osg::DrawElementsUInt& lhs,osg::DrawElementsUInt& rhs);
+
+            protected:
+
+                unsigned int _targetMaximumNumberOfVertices;
+
+        };
+
+        /** Spatialize scene into a balanced quad/oct tree.*/
+        class OSGUTIL_EXPORT SpatializeGroupsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                SpatializeGroupsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, SPATIALIZE_GROUPS) {}
+                
+                virtual void apply(osg::Group& group);
+                virtual void apply(osg::Geode& geode);
+                
+                bool divide(unsigned int maxNumTreesPerCell=8);
+                
+                bool divide(osg::Group* group, unsigned int maxNumTreesPerCell);
+                bool divide(osg::Geode* geode, unsigned int maxNumTreesPerCell);
+                
+                typedef std::set<osg::Group*> GroupsToDivideList;
+                GroupsToDivideList _groupsToDivideList;
+
+                typedef std::set<osg::Geode*> GeodesToDivideList;
+                GeodesToDivideList _geodesToDivideList;
+        };
+
+        /** Copy any shared subgraphs, enabling flattening of static transforms.*/
+        class OSGUTIL_EXPORT CopySharedSubgraphsVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                CopySharedSubgraphsVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, COPY_SHARED_NODES) {}
+                
+                virtual void apply(osg::Node& node);
+
+                void copySharedNodes();
+                
+                typedef std::set<osg::Node*> SharedNodeList;
+                SharedNodeList _sharedNodeList;
+                
+        };
+
+
+        /** For all textures apply settings.*/
+        class OSGUTIL_EXPORT TextureVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                TextureVisitor(bool changeAutoUnRef, bool valueAutoUnRef,
+                               bool changeClientImageStorage, bool valueClientImageStorage,
+                               bool changeAnisotropy, float valueAnisotropy,
+                               Optimizer* optimizer=0):
+                        BaseOptimizerVisitor(optimizer, OPTIMIZE_TEXTURE_SETTINGS),
+                        _changeAutoUnRef(changeAutoUnRef), _valueAutoUnRef(valueAutoUnRef),
+                        _changeClientImageStorage(changeClientImageStorage), _valueClientImageStorage(valueClientImageStorage),
+                        _changeAnisotropy(changeAnisotropy), _valueAnisotropy(valueAnisotropy) {}
+                
+                virtual void apply(osg::Geode& node);
+                virtual void apply(osg::Node& node);
+
+                void apply(osg::StateSet& stateset);
+                void apply(osg::Texture& texture);
+
+                bool            _changeAutoUnRef, _valueAutoUnRef;
+                bool            _changeClientImageStorage, _valueClientImageStorage;
+                bool            _changeAnisotropy;
+                float           _valueAnisotropy;
+
+        };
+        
+        /** Flatten MatrixTransform/Billboard pairs.*/
+        class OSGUTIL_EXPORT FlattenBillboardVisitor : public BaseOptimizerVisitor
+        {
+            public:
+                FlattenBillboardVisitor(Optimizer* optimizer=0):
+                        BaseOptimizerVisitor(optimizer, FLATTEN_BILLBOARDS) {}
+
+                typedef std::vector<osg::NodePath> NodePathList;
+                typedef std::map<osg::Billboard*, NodePathList > BillboardNodePathMap;
+
+                virtual void reset();
+
+                virtual void apply(osg::Billboard& billboard);
+
+                void process();    
+
+                BillboardNodePathMap _billboards;
+
+        };
+        
+        /** Texture Atlas Builder creates a set of textures/images which each contain multiple images.
+          * Texture Atlas' are used to make it possible to use much wider batching of data. */
+        class OSGUTIL_EXPORT TextureAtlasBuilder
+        {
+        public:
+            TextureAtlasBuilder();
+            
+            void reset();
+            
+            void setMaximumAtlasSize(unsigned int width, unsigned int height);
+
+            unsigned int getMaximumAtlasWidth() const { return _maximumAtlasWidth; }
+            unsigned int getMaximumAtlasHeight() const { return _maximumAtlasHeight; }
+            
+            void setMargin(unsigned int margin);
+            unsigned int getMargin() const { return _margin; }
+
+            void addSource(const osg::Image* image);
+            void addSource(const osg::Texture2D* texture);
+            
+            unsigned int getNumSources() const { return _sourceList.size(); }
+            const osg::Image* getSourceImage(unsigned int i) { return _sourceList[i]->_image.get(); }
+            const osg::Texture2D* getSourceTexture(unsigned int i) { return _sourceList[i]->_texture.get(); }
+            
+            void buildAtlas();
+            
+            osg::Image* getImageAtlas(unsigned int i);
+            osg::Texture2D* getTextureAtlas(unsigned int i);
+            osg::Matrix getTextureMatrix(unsigned int i);
+            
+            osg::Image* getImageAtlas(const osg::Image* image);
+            osg::Texture2D* getTextureAtlas(const osg::Image* image);
+            osg::Matrix getTextureMatrix(const osg::Image* image);
+            
+            osg::Image* getImageAtlas(const osg::Texture2D* textue);
+            osg::Texture2D* getTextureAtlas(const osg::Texture2D* texture);
+            osg::Matrix getTextureMatrix(const osg::Texture2D* texture);
+            
+        protected:
+        
+            unsigned int _maximumAtlasWidth;
+            unsigned int _maximumAtlasHeight;
+            unsigned int _margin;
+            
+
+            // forward declare
+            class Atlas;
+            
+            class Source : public osg::Referenced
+            {
+            public:
+                Source():
+                    _x(0),_y(0),_atlas(0) {}
+
+                Source(const osg::Image* image):
+                    _x(0),_y(0),_atlas(0),_image(image) {}
+
+                Source(const osg::Texture2D* texture):
+                    _x(0),_y(0),_atlas(0),_texture(texture) { if (texture) _image = texture->getImage(); }
+            
+                unsigned int _x;
+                unsigned int _y;
+                Atlas* _atlas;
+
+                osg::ref_ptr<const osg::Image> _image;
+                osg::ref_ptr<const osg::Texture2D> _texture;
+                
+                bool suitableForAtlas(unsigned int maximumAtlasWidth, unsigned int maximumAtlasHeight, unsigned int margin);
+                osg::Matrix computeTextureMatrix() const;
+                
+                
+            protected:
+            
+                virtual ~Source() {}
+            };
+            
+            typedef std::vector< osg::ref_ptr<Source> > SourceList;
+
+            class Atlas : public osg::Referenced
+            {
+            public:
+                Atlas(unsigned int width, unsigned height, unsigned margin):
+                    _maximumAtlasWidth(width),
+                    _maximumAtlasHeight(height),
+                    _margin(margin),
+                    _x(0),
+                    _y(0),
+                    _width(0),
+                    _height(0){}
+        
+                unsigned int _maximumAtlasWidth;
+                unsigned int _maximumAtlasHeight;
+                unsigned int _margin;
+
+                osg::ref_ptr<osg::Texture2D> _texture;
+                osg::ref_ptr<osg::Image> _image;
+            
+                SourceList _sourceList;
+                
+                unsigned int _x;
+                unsigned int _y;
+                unsigned int _width;
+                unsigned int _height;
+                
+                bool doesSourceFit(Source* source);
+                bool addSource(Source* source);
+                void clampToNearestPowerOfTwoSize();
+                void copySources();
+                
+            protected:
+            
+                virtual ~Atlas() {}
+            };
+            
+            typedef std::vector< osg::ref_ptr<Atlas> > AtlasList;
+            
+            Source* getSource(const osg::Image* image);
+            Source* getSource(const osg::Texture2D* texture);
+
+            SourceList _sourceList;
+            AtlasList _atlasList;    
+        };
+
+ 
+        /** Optimize texture usage in the scene graph by combining textures into texture atlas 
+          * Use of texture atlas cuts down on the number of seperate states in the scene, reducing
+          * state changes and improving the chances of use larger batches of geomertry.*/
+        class OSGUTIL_EXPORT TextureAtlasVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                TextureAtlasVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, TEXTURE_ATLAS_BUILDER) {}
+
+
+                TextureAtlasBuilder& getTextureAtlasBuilder() { return _builder; }
+
+                /** empty visitor, make it ready for next traversal.*/        
+                virtual void reset();
+
+                virtual void apply(osg::Node& node);
+
+                virtual void apply(osg::Geode& geode);
+
+                void optimize();
+
+            protected:
+
+                bool pushStateSet(osg::StateSet* stateset);
+                void popStateSet();
+
+                typedef std::set<osg::Drawable*>  Drawables;
+                typedef std::map<osg::StateSet*, Drawables>  StateSetMap;
+                typedef std::set<osg::Texture2D*>  Textures;
+                typedef std::vector<osg::StateSet*>  StateSetStack;
+
+                TextureAtlasBuilder _builder;
+
+                StateSetMap     _statesetMap;
+                StateSetStack   _statesetStack;
+                Textures        _textures;
+
+        };
+
+        /** Optimize the setting of StateSet and Geometry objects in scene so that they have a STATIC DataVariance
+          * when they don't have any callbacks associated with them. */
+        class OSGUTIL_EXPORT StaticObjectDetectionVisitor : public BaseOptimizerVisitor
+        {
+            public:
+
+                /// default to traversing all children.
+                StaticObjectDetectionVisitor(Optimizer* optimizer=0):
+                    BaseOptimizerVisitor(optimizer, STATIC_OBJECT_DETECTION) {}
+
+                virtual void apply(osg::Node& node);
+
+                virtual void apply(osg::Geode& geode);
+
+            protected:
+
+                void applyStateSet(osg::StateSet& stateset);
+                
+                void applyDrawable(osg::Drawable& drawable);
+
+        };
+};
+
+inline bool BaseOptimizerVisitor::isOperationPermissibleForObject(const osg::StateSet* object) const
+{
+    return _optimizer ? _optimizer->isOperationPermissibleForObject(object,_operationType) :  true; 
+}
+
+inline bool BaseOptimizerVisitor::isOperationPermissibleForObject(const osg::StateAttribute* object) const
+{
+    return _optimizer ? _optimizer->isOperationPermissibleForObject(object,_operationType) :  true; 
+}
+
+inline bool BaseOptimizerVisitor::isOperationPermissibleForObject(const osg::Drawable* object) const
+{
+    return _optimizer ? _optimizer->isOperationPermissibleForObject(object,_operationType) :  true; 
+}
+
+inline bool BaseOptimizerVisitor::isOperationPermissibleForObject(const osg::Node* object) const
+{
+    return _optimizer ? _optimizer->isOperationPermissibleForObject(object,_operationType) :  true; 
+}
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PositionalStateContainer
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PositionalStateContainer (revision 6060)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PositionalStateContainer (revision 6060)
@@ -0,0 +1,77 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_POSTIONALSTATECONTIANER
+#define OSGUTIL_POSTIONALSTATECONTIANER 1
+
+#include <osg/Object>
+#include <osg/Light>
+#include <osg/State>
+
+#include <osgUtil/RenderLeaf>
+#include <osgUtil/StateGraph>
+
+namespace osgUtil {
+
+/**
+ * PositionalStateContainer base class. Used in RenderStage class.
+ */
+class OSGUTIL_EXPORT PositionalStateContainer : public osg::Object
+{
+    public:
+    
+
+        PositionalStateContainer();
+        virtual osg::Object* cloneType() const { return new PositionalStateContainer(); }
+        virtual osg::Object* clone(const osg::CopyOp&) const { return new PositionalStateContainer(); } // note only implements a clone of type.
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const PositionalStateContainer*>(obj)!=0L; }
+        virtual const char* libraryName() const { return "osgUtil"; }
+        virtual const char* className() const { return "PositionalStateContainer"; }
+
+        virtual void reset();
+        
+        typedef std::pair< osg::ref_ptr<const osg::StateAttribute> , osg::ref_ptr<osg::RefMatrix> >    AttrMatrixPair;
+        typedef std::vector< AttrMatrixPair >                                            AttrMatrixList;
+        typedef std::map< unsigned int, AttrMatrixList >                                 TexUnitAttrMatrixListMap;
+
+        AttrMatrixList& getAttrMatrixList() { return _attrList; }
+
+        virtual void addPositionedAttribute(osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+        {
+            _attrList.push_back(AttrMatrixPair(attr,matrix));
+        }
+
+        TexUnitAttrMatrixListMap& getTexUnitAttrMatrixListMap() { return _texAttrListMap; }
+
+        virtual void addPositionedTextureAttribute(unsigned int textureUnit, osg::RefMatrix* matrix,const osg::StateAttribute* attr)
+        {
+            _texAttrListMap[textureUnit].push_back(AttrMatrixPair(attr,matrix));
+        }
+
+        virtual void draw(osg::State& state,RenderLeaf*& previous, const osg::Matrix* postMultMatrix = 0);
+        
+    public:
+        
+        AttrMatrixList              _attrList;
+        TexUnitAttrMatrixListMap    _texAttrListMap;
+        
+    protected:
+    
+        virtual ~PositionalStateContainer();
+
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DisplayRequirementsVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DisplayRequirementsVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DisplayRequirementsVisitor (revision 9377)
@@ -0,0 +1,61 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_DISPLAYREQUIREMENTSVISITOR
+#define OSGUTIL_DISPLAYREQUIREMENTSVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/DisplaySettings>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** A visitor for traversing a scene graph establishing which OpenGL visuals are
+  * required to support rendering of that scene graph.  The results can then be used by
+  * applications to set up their windows with the correct visuals.  Have a look at
+  * src/osgGLUT/Viewer.cpp's Viewer::open() method for an example of how to use it.
+  */
+class OSGUTIL_EXPORT DisplayRequirementsVisitor : public osg::NodeVisitor
+{
+    public:
+
+        /** Default to traversing all children, and requiresDoubleBuffer,
+          * requiresRGB and requiresDepthBuffer to true and with
+          * alpha and stencil off.*/
+        DisplayRequirementsVisitor();
+        
+        META_NodeVisitor("osgUtil","DisplayRequirementsVisitor")
+
+        /** Set the DisplaySettings. */
+        inline void setDisplaySettings(osg::DisplaySettings* ds) { _ds = ds; }
+        
+        /** Get the DisplaySettings */
+        inline const osg::DisplaySettings* getDisplaySettings() const { return _ds.get(); }
+        
+        virtual void applyStateSet(osg::StateSet& stateset);
+
+        virtual void apply(osg::Node& node);
+
+        virtual void apply(osg::Geode& geode);
+        
+    protected:
+    
+        osg::ref_ptr<osg::DisplaySettings> _ds;
+    
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Statistics
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Statistics (revision 9552)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Statistics (revision 9552)
@@ -0,0 +1,221 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_STATISTICS
+#define OSGUTIL_STATISTICS 1
+
+#include <osgUtil/Export>
+
+#include <osg/PrimitiveSet>
+#include <osg/Drawable>
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/LOD>
+#include <osg/Switch>
+#include <osg/Geometry>
+#include <osg/Transform>
+
+#include <map>
+#include <set>
+#include <ostream>
+
+namespace osgUtil {
+
+/**
+ * Statistics base class. Used to extract primitive information from 
+ * the renderBin(s).  Add a case of getStats(osgUtil::Statistics *stat)
+ * for any new drawable (or drawable derived class) that you generate 
+ * (eg see Geometry.cpp).  There are 20 types of drawable counted - actually only
+ * 14 cases can occur in reality.  these represent sets of GL_POINTS, GL_LINES
+ * GL_LINESTRIPS, LOOPS, TRIANGLES, TRI-fans, tristrips, quads, quadstrips etc
+ * The number of triangles rendered is inferred:
+ * each triangle = 1 triangle (number of vertices/3)
+ * each quad = 2 triangles (nverts/2)
+ * each trifan or tristrip = (length-2) triangles and so on.
+ */
+
+class OSGUTIL_EXPORT Statistics : public osg::PrimitiveFunctor
+{
+    public:
+
+        typedef std::pair<unsigned int,unsigned int>    PrimitivePair;
+        typedef std::map<GLenum,PrimitivePair>          PrimitiveValueMap;
+        typedef std::map<GLenum, unsigned int>          PrimitiveCountMap;
+
+
+        Statistics();
+
+        enum StatsType
+        {
+            STAT_NONE, // default
+            STAT_FRAMERATE, 
+            STAT_GRAPHS,
+            STAT_PRIMS, 
+            STAT_PRIMSPERVIEW, 
+            STAT_PRIMSPERBIN,
+            STAT_DC,
+            STAT_RESTART // hint to restart the stats
+        };
+        
+        void reset();
+
+        void setType(StatsType t) {stattype=t;}
+        
+        virtual void setVertexArray(unsigned int count,const osg::Vec3*) { _vertexCount += count; }
+        virtual void setVertexArray(unsigned int count,const osg::Vec2*) { _vertexCount += count; }
+        virtual void setVertexArray(unsigned int count,const osg::Vec4*) { _vertexCount += count; }
+        virtual void setVertexArray(unsigned int count,const osg::Vec3d*) { _vertexCount += count; }
+        virtual void setVertexArray(unsigned int count,const osg::Vec2d*) { _vertexCount += count; }
+        virtual void setVertexArray(unsigned int count,const osg::Vec4d*) { _vertexCount += count; }
+
+        virtual void drawArrays(GLenum mode,GLint,GLsizei count);
+        virtual void drawElements(GLenum mode,GLsizei count,const GLubyte*);
+        virtual void drawElements(GLenum mode,GLsizei count,const GLushort*);
+        virtual void drawElements(GLenum mode,GLsizei count,const GLuint*);
+
+        virtual void begin(GLenum mode);
+
+        inline void vertex() 
+        { 
+            PrimitivePair& prim = _primitiveCount[_currentPrimitiveFunctorMode]; 
+            ++prim.second; 
+           _number_of_vertexes++;
+        }
+        
+        virtual void vertex(float,float,float) { vertex(); }
+        virtual void vertex(const osg::Vec3&)  { vertex(); }
+        virtual void vertex(const osg::Vec2&)  { vertex(); }
+        virtual void vertex(const osg::Vec4&)  { vertex(); }
+        virtual void vertex(float,float)   { vertex(); }
+        virtual void vertex(float,float,float,float)  { vertex(); }
+
+        virtual void end();
+        
+        void addDrawable() { numDrawables++;}
+        void addMatrix() { nummat++;}
+        void addLight(int np) { nlights+=np;}
+        void addImpostor(int np) { nimpostor+= np; }
+        inline int getBins() { return nbins;}
+        void setDepth(int d) { depth=d; }
+        void addBins(int np) { nbins+= np; }
+
+        void setBinNo(int n) { _binNo=n;}
+        
+        void add(const Statistics& stats);
+                
+    public:
+                
+        PrimitiveCountMap& getPrimitiveCountMap() { return _primitives_count; }
+        const PrimitiveCountMap& getPrimitiveCountMap() const { return _primitives_count; }
+        
+        /// deprecated
+        PrimitiveCountMap::iterator GetPrimitivesBegin() { return _primitives_count.begin(); }
+        /// deprecated
+        PrimitiveCountMap::iterator GetPrimitivesEnd() { return _primitives_count.end(); }
+
+        int numDrawables, nummat, nbins;
+        int nlights;
+        int depth; // depth into bins - eg 1.1,1.2,1.3 etc
+        int _binNo;
+        StatsType stattype;
+        int nimpostor; // number of impostors rendered
+        
+        unsigned int        _vertexCount;
+        PrimitiveValueMap    _primitiveCount;
+        GLenum              _currentPrimitiveFunctorMode;
+
+    private:
+        PrimitiveCountMap                     _primitives_count;
+
+        unsigned int                         _total_primitives_count;
+        unsigned int                         _number_of_vertexes;
+
+        inline unsigned int _calculate_primitives_number_by_mode(GLenum, GLsizei);
+};
+
+inline unsigned int Statistics::_calculate_primitives_number_by_mode(GLenum mode, GLsizei count)
+{
+    switch (mode)
+    {
+        case GL_POINTS: 
+        case GL_LINE_LOOP:
+        case GL_POLYGON:  return count; 
+        case GL_LINES: return count / 2; 
+        case GL_LINE_STRIP: return count - 1; 
+        case GL_TRIANGLES: return count / 3; 
+        case GL_TRIANGLE_STRIP:
+        case GL_TRIANGLE_FAN: return count - 2; 
+        case GL_QUADS: return count / 4; 
+        case GL_QUAD_STRIP: return count / 2 - 1; 
+        default: return 0;
+    }
+}
+
+/** StatsVisitor for collecting statistics about scene graph.*/
+class OSGUTIL_EXPORT StatsVisitor : public osg::NodeVisitor
+{
+public:
+
+    typedef std::set<osg::Node*> NodeSet;
+    typedef std::set<osg::Drawable*> DrawableSet;
+    typedef std::set<osg::StateSet*> StateSetSet;
+
+    StatsVisitor();
+        
+    META_NodeVisitor("osgUtil","StatsVisitor")
+
+    void reset();
+    
+    void apply(osg::Node& node);
+
+    void apply(osg::Group& node);
+
+    void apply(osg::Transform& node);
+
+    void apply(osg::LOD& node);
+
+    void apply(osg::Switch& node);
+
+    void apply(osg::Geode& node);
+
+    void apply(osg::Drawable& drawable);
+
+    void totalUpStats();
+    
+    void print(std::ostream& out);
+    
+    unsigned int _numInstancedGroup;
+    unsigned int _numInstancedSwitch;
+    unsigned int _numInstancedLOD;
+    unsigned int _numInstancedTransform;
+    unsigned int _numInstancedGeode;
+    unsigned int _numInstancedDrawable;
+    unsigned int _numInstancedGeometry;
+    unsigned int _numInstancedStateSet;
+
+    NodeSet _groupSet;
+    NodeSet _transformSet;
+    NodeSet _lodSet;
+    NodeSet _switchSet;
+    NodeSet _geodeSet;
+    DrawableSet _drawableSet;
+    DrawableSet _geometrySet;
+    StateSetSet _statesetSet;
+
+    osgUtil::Statistics _uniqueStats;
+    osgUtil::Statistics _instancedStats;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/GLObjectsVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/GLObjectsVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/GLObjectsVisitor (revision 9377)
@@ -0,0 +1,136 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_GLOBJECTSVISITOR
+#define OSGUTIL_GLOBJECTSVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/State>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** Visitor for traversing scene graph and setting each osg::Drawable's _useDisplayList flag, 
+  * with option to immediately compile osg::Drawable OpenGL Display lists and
+  * osg::StateAttribute's.
+  */
+class OSGUTIL_EXPORT GLObjectsVisitor : public osg::NodeVisitor
+{
+    public:
+
+        /** Operation modes of the.*/
+        enum ModeValues
+        {
+            SWITCH_ON_DISPLAY_LISTS             = 0x1,
+            SWITCH_OFF_DISPLAY_LISTS            = 0x2,
+            COMPILE_DISPLAY_LISTS               = 0x4,
+            COMPILE_STATE_ATTRIBUTES            = 0x8,
+            RELEASE_DISPLAY_LISTS               = 0x10,
+            RELEASE_STATE_ATTRIBUTES            = 0x20,
+            SWITCH_ON_VERTEX_BUFFER_OBJECTS     = 0x40,
+            SWITCH_OFF_VERTEX_BUFFER_OBJECTS    = 0x80,
+            CHECK_BLACK_LISTED_MODES            = 0x100
+        };
+        
+        typedef unsigned int Mode;
+
+        /** Construct a GLObjectsVisitor to traverse all children, operating on
+          * node according to specified mode, such as to compile or release 
+          * display list/texture objects etc. Default mode is to compile 
+          * GL objects.
+          */
+        GLObjectsVisitor(Mode mode=COMPILE_DISPLAY_LISTS|COMPILE_STATE_ATTRIBUTES|CHECK_BLACK_LISTED_MODES);      
+ 
+        META_NodeVisitor("osg","GLObjectsVisitor")
+       
+        virtual void reset()
+        {
+            _drawablesAppliedSet.clear();
+            _stateSetAppliedSet.clear();
+        }
+
+        
+        /** Set the operational mode of what operations to do on the scene graph.*/
+        void setMode(Mode mode) { _mode = mode; }
+
+        /** Get the operational mode.*/
+        Mode getMode() const { return _mode; }
+        
+
+        /** Set the State to use during traversal. */
+        void setState(osg::State* state)
+        {
+            _renderInfo.setState(state);
+        }
+        
+        osg::State* getState()
+        {
+            return _renderInfo.getState();
+        }
+
+        void setRenderInfo(osg::RenderInfo& renderInfo)
+        {
+            _renderInfo = renderInfo;
+        }
+        
+        osg::RenderInfo& getRenderInfo()
+        {
+            return _renderInfo;
+        }
+
+        /** Simply traverse using standard NodeVisitor traverse method.*/
+        virtual void apply(osg::Node& node);
+        
+        /** For each Geode visited set the display list usage according to the 
+          * _displayListMode.
+          */
+        virtual void apply(osg::Geode& node);
+
+        void apply(osg::Drawable& drawable);
+        void apply(osg::StateSet& stateset);
+
+    protected:
+
+        typedef std::set<osg::Drawable*> DrawableAppliedSet;
+        typedef std::set<osg::StateSet*> StatesSetAppliedSet;
+
+        Mode                        _mode;
+        osg::RenderInfo             _renderInfo;
+        DrawableAppliedSet          _drawablesAppliedSet;
+        StatesSetAppliedSet         _stateSetAppliedSet;
+        osg::ref_ptr<osg::Program>  _lastCompiledProgram;
+
+};
+
+class OSGUTIL_EXPORT GLObjectsOperation : public osg::GraphicsOperation
+{
+    public:
+
+        GLObjectsOperation(GLObjectsVisitor::Mode mode = GLObjectsVisitor::COMPILE_DISPLAY_LISTS|GLObjectsVisitor::COMPILE_STATE_ATTRIBUTES|GLObjectsVisitor::CHECK_BLACK_LISTED_MODES);
+
+        GLObjectsOperation(osg::Node* subgraph, GLObjectsVisitor::Mode mode = GLObjectsVisitor::COMPILE_DISPLAY_LISTS|GLObjectsVisitor::COMPILE_STATE_ATTRIBUTES|GLObjectsVisitor::CHECK_BLACK_LISTED_MODES);
+
+        virtual void operator () (osg::GraphicsContext* context);
+
+    protected:
+    
+        osg::ref_ptr<osg::Node> _subgraph;
+        GLObjectsVisitor::Mode  _mode;
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DrawElementTypeSimplifier
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DrawElementTypeSimplifier (revision 9767)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DrawElementTypeSimplifier (revision 9767)
@@ -0,0 +1,42 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+#ifndef OSGUTIL_DRAWELEMENTTYPESIMPLIFIER
+#define OSGUTIL_DRAWELEMENTTYPESIMPLIFIER
+
+
+#include <osg/Geometry>
+#include <osg/NodeVisitor>
+
+#include <osgUtil/Export>
+
+namespace osgUtil
+{
+
+class OSGUTIL_EXPORT DrawElementTypeSimplifier
+{
+    public:
+        void simplify(osg::Geometry & geometry) const;
+};
+
+class OSGUTIL_EXPORT DrawElementTypeSimplifierVisitor : public osg::NodeVisitor
+{
+    public:
+        
+        META_NodeVisitor("osgUtil","DrawElementTypeSimplifierVisitor");
+
+        void apply(osg::Geode& node);
+};
+
+}
+
+#endif // ** OSGUTIL_DRAWELEMENTTYPESIMPLIFIER ** //
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PolytopeIntersector
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PolytopeIntersector (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/PolytopeIntersector (revision 7648)
@@ -0,0 +1,130 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_POLYTOPEINTERSECTOR
+#define OSGUTIL_POLYTOPEINTERSECTOR 1
+
+#include <osgUtil/IntersectionVisitor>
+
+namespace osgUtil
+{
+
+/** Concrete class for implementing polytope intersections with the scene graph.
+  * To be used in conjunction with IntersectionVisitor. */
+class OSGUTIL_EXPORT PolytopeIntersector : public Intersector
+{
+    public:
+        /// dimension enum to specify primitive types to check.
+        enum {
+            DimZero = (1<<0),    ///< check for points
+            DimOne = (1<<1),     ///< check for lines
+            DimTwo = (1<<2),     ///< check for triangles, quad
+            AllDims = (DimZero | DimOne | DimTwo)
+        };
+
+        /** Construct a PolytopeIntersector using specified polytope in MODEL coordinates.*/
+        PolytopeIntersector(const osg::Polytope& polytope);
+
+        /** Construct a PolytopeIntersector using specified polytope in specified coordinate frame.*/
+        PolytopeIntersector(CoordinateFrame cf, const osg::Polytope& polytope);
+
+        /** Convenience constructor for supporting picking in WINDOW, or PROJECTION coordinates
+          * In WINDOW coordinates (clip space cube) creates a five sided polytope box that has a front face at 0.0 and sides around box xMin, yMin, xMax, yMax.
+          * In PROJECTION coordinates (clip space cube) creates a five sided polytope box that has a front face at -1 and sides around box xMin, yMin, xMax, yMax.
+          * In VIEW and MODEL coordinates (clip space cube) creates a five sided polytope box that has a front face at 0.0 and sides around box xMin, yMin, xMax, yMax.*/
+        PolytopeIntersector(CoordinateFrame cf, double xMin, double yMin, double xMax, double yMax);
+
+        struct Intersection
+        {
+            Intersection() {}
+
+            bool operator < (const Intersection& rhs) const
+            {
+                if (distance < rhs.distance) return true;
+                if (rhs.distance < distance) return false;
+                if (primitiveIndex < rhs.primitiveIndex) return true;
+                if (rhs.primitiveIndex < primitiveIndex) return false;
+                if (nodePath < rhs.nodePath) return true;
+                if (rhs.nodePath < nodePath ) return false;
+                return (drawable < rhs.drawable);
+            }
+
+            enum { MaxNumIntesectionPoints=6 };
+
+            double                          distance;     ///< distance from reference plane
+            double                          maxDistance;  ///< maximum distance of intersection points from reference plane
+            osg::NodePath                   nodePath;
+            osg::ref_ptr<osg::Drawable>     drawable;
+            osg::ref_ptr<osg::RefMatrix>    matrix;
+            osg::Vec3                       localIntersectionPoint;  ///< center of all intersection points
+            unsigned int                    numIntersectionPoints;
+            osg::Vec3                       intersectionPoints[MaxNumIntesectionPoints];
+            unsigned int                    primitiveIndex; ///< primitive index
+        };
+        
+        typedef std::set<Intersection> Intersections;
+        
+        inline void insertIntersection(const Intersection& intersection) { getIntersections().insert(intersection); }
+
+        inline Intersections& getIntersections() { return _parent ? _parent->_intersections : _intersections; }
+
+        inline Intersection getFirstIntersection() { Intersections& intersections = getIntersections(); return intersections.empty() ? Intersection() : *(intersections.begin()); }
+
+        inline unsigned int getDimensionMask() const { return _dimensionMask; }
+
+        /** set the dimension mask.
+         * As polytope-triangle and polytope-quad intersections are expensive to compute
+         * it is possible to turn them off by calling setDimensionMask( DimZero | DimOne )
+         */
+        inline void setDimensionMask(unsigned int dimensionMask) { _dimensionMask = dimensionMask; }
+
+        inline const osg::Plane& getReferencePlane() const { return _referencePlane; }
+
+        /** set the plane used to sort the intersections.
+         * The intersections are sorted by the distance of the localIntersectionPoint
+         * and the reference plane. The default for the reference plane is the
+         * last plane of the polytope.
+         */
+        inline void setReferencePlane(const osg::Plane& plane) { _referencePlane = plane; }
+
+    public:
+
+        virtual Intersector* clone(osgUtil::IntersectionVisitor& iv);
+        
+        virtual bool enter(const osg::Node& node);
+        
+        virtual void leave();
+        
+        virtual void intersect(osgUtil::IntersectionVisitor& iv, osg::Drawable* drawable);
+        
+        virtual void reset();
+
+        virtual bool containsIntersections() { return !_intersections.empty(); }
+
+    protected:
+
+        PolytopeIntersector* _parent;
+
+        osg::Polytope _polytope;
+
+        unsigned int _dimensionMask; ///< mask which dimensions should be checked
+        osg::Plane _referencePlane; ///< plane to use for sorting intersections
+
+        Intersections _intersections;
+    
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DelaunayTriangulator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DelaunayTriangulator (revision 6446)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/DelaunayTriangulator (revision 6446)
@@ -0,0 +1,231 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_DELAUNAYTRIANGULATOR_
+#define OSGUTIL_DELAUNAYTRIANGULATOR_
+
+#include <list>
+
+#include <osg/ref_ptr>
+#include <osg/Array>
+#include <osg/Referenced>
+#include <osg/CopyOp>
+#include <osg/PrimitiveSet>
+#include <osg/Geometry>
+
+#include <osgUtil/Export>
+
+namespace osgUtil 
+{
+
+/** DelaunayTriangulator: Utility class that triangulates an irregular network of sample points.
+    Just create a DelaunayTriangulator, assign it the sample point array and call
+    its triangulate() method to start the triangulation. Then you can obtain the
+    generated primitive by calling the getTriangles() method.
+
+    Add DelaunayConstraints (or derived class) to control the triangulation edges.
+*/
+class OSGUTIL_EXPORT DelaunayConstraint: public osg::Geometry {
+    // controls the edges in a Delaunay triangulation.
+    // constraints can be linear (with width), areal (contains an area)
+    // uses: to replace part of a terrain with an alternative textured model (roads, lakes).
+    // the primitive sets in this are either LINE_LOOP or LINE_STRIP
+public:
+    DelaunayConstraint() { }
+
+    /** Each primitiveset is a list of vertices which may be closed by joining up to its start 
+     * to make a loop.  Constraints should be simple lines, not crossing themselves.
+     * Constraints which cross other constraints can cause difficulties - see the example
+     * for methods of dealing with them. */
+
+     /** collect up indices of triangle from delaunay triangles.
+      *  The delaunay triangles inside the DelaunayConstraint area can be used to fill
+      *  the area or generate geometry that terrain follows the area in some way.
+      *  These triangles can form a canopy or a field. */
+    void addtriangle(int i1, int i2, int i3);
+
+    /** Get the filling primitive. One:
+     * triangulate must have bneen called and
+     * two:  triangle list is filled when 
+     * DelaunayTriangulator::removeInternalTriangles is called.
+     * These return the triangles removed from the delaunay triangulation by 
+     * DelaunayTriangulator::removeInternalTriangles. */
+    inline const osg::DrawElementsUInt *getTriangles() const;
+    inline osg::DrawElementsUInt *getTriangles();
+
+    /** Call BEFORE makeDrawable to reorder points to make optimised set
+     */
+    osg::Vec3Array *getPoints(const osg::Vec3Array *points);
+
+    /** converts simple list of triangles into a drawarray.
+     */
+    osg::DrawElementsUInt *makeDrawable();
+
+    /** Add vertices and constraint loops from dco
+     * Can be used to generate extra vertices where dco crosses 'this' using
+     * osgUtil::Tessellator to insert overlap vertices.
+     */
+    void merge(DelaunayConstraint *dco);
+
+    /** remove from line the vertices that are inside dco
+     */
+    void removeVerticesInside(const DelaunayConstraint *dco);
+    
+     /** return winding number as a float of loop around testpoint; may use multiple loops
+      * does not reject points on the edge or very very close to the edge */
+    float windingNumber(const osg::Vec3 &testpoint) const ;
+
+     /** true if testpoint is internal (or external) to constraint. */
+    virtual bool contains(const osg::Vec3 &testpoint) const;
+    virtual bool outside(const osg::Vec3 &testpoint) const;
+
+    /** Tessellate the constraint loops so that the crossing points are interpolated
+     * and added to the contraints for the triangulation. */
+    void handleOverlaps(void);
+
+protected:
+    virtual ~DelaunayConstraint() {}
+
+    typedef std::vector< int* > trilist; // array of indices in points array defining triangles
+
+    trilist _interiorTris; // list of triangles that fits the area.
+
+    osg::ref_ptr<osg::DrawElementsUInt> prim_tris_; // returns a PrimitiveSet to draw the interior of this DC
+};
+
+
+class OSGUTIL_EXPORT DelaunayTriangulator: public osg::Referenced {
+public:
+
+    DelaunayTriangulator();
+    explicit DelaunayTriangulator(osg::Vec3Array *points, osg::Vec3Array *normals = 0);
+    DelaunayTriangulator(const DelaunayTriangulator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY);
+
+    typedef std::vector< osg::ref_ptr<DelaunayConstraint> > linelist;
+
+    /** Get the const input point array. */
+    inline const osg::Vec3Array *getInputPointArray() const;
+
+    /** Get the input point array. */
+    inline osg::Vec3Array *getInputPointArray();
+
+    /** Set the input point array. */
+    inline void setInputPointArray(osg::Vec3Array *points);
+
+    /** Add an input constraint loop.
+     ** the edges of the loop will constrain the triangulation.
+     ** if remove!=0, the internal triangles of the constraint will be removed;
+     ** the user may the replace the constraint line with an equivalent geometry.
+     ** GWM July 2005 */
+    void addInputConstraint(DelaunayConstraint *dc) {
+        constraint_lines.push_back(dc);
+        return;
+    }
+
+
+    /** Get the const output normal array (optional). */
+    inline const osg::Vec3Array *getOutputNormalArray() const;
+
+    /** Get the output normal array (optional). */
+    inline osg::Vec3Array *getOutputNormalArray();
+
+    /** Set the output normal array (optional). */
+    inline void setOutputNormalArray(osg::Vec3Array *normals);
+
+    /** Start triangulation. */
+    bool triangulate();
+
+    /** Get the generated primitive (call triangulate() first). */
+    inline const osg::DrawElementsUInt *getTriangles() const;
+
+    /** Get the generated primitive (call triangulate() first). */
+    inline osg::DrawElementsUInt *getTriangles();
+    
+    /** remove the triangles internal to the constraint loops.
+     * (Line strips cannot remove any internal triangles). */
+    void removeInternalTriangles(DelaunayConstraint *constraint);
+
+protected:
+    virtual ~DelaunayTriangulator();
+    DelaunayTriangulator &operator=(const DelaunayTriangulator &) { return *this; }
+    int getindex(const osg::Vec3 &pt,const osg::Vec3Array *points);
+
+private:
+    osg::ref_ptr<osg::Vec3Array> points_;
+    osg::ref_ptr<osg::Vec3Array> normals_;
+    osg::ref_ptr<osg::DrawElementsUInt> prim_tris_;
+
+    // GWM these lines provide required edges in the triangulated shape.
+    linelist constraint_lines;
+
+    void _uniqueifyPoints();
+    
+};
+
+// INLINE METHODS
+
+inline const osg::Vec3Array *DelaunayTriangulator::getInputPointArray() const
+{
+    return points_.get();
+}
+
+inline osg::Vec3Array *DelaunayTriangulator::getInputPointArray()
+{
+    return points_.get();
+}
+
+inline void DelaunayTriangulator::setInputPointArray(osg::Vec3Array *points)
+{
+    points_ = points;
+}
+
+inline const osg::Vec3Array *DelaunayTriangulator::getOutputNormalArray() const
+{
+    return normals_.get();
+}
+
+inline osg::Vec3Array *DelaunayTriangulator::getOutputNormalArray()
+{
+    return normals_.get();
+}
+
+inline void DelaunayTriangulator::setOutputNormalArray(osg::Vec3Array *normals)
+{
+    normals_ = normals;
+}
+
+inline const osg::DrawElementsUInt *DelaunayTriangulator::getTriangles() const
+{
+    return prim_tris_.get();
+}
+
+inline osg::DrawElementsUInt *DelaunayTriangulator::getTriangles()
+{
+    return prim_tris_.get();
+}
+
+inline const osg::DrawElementsUInt *DelaunayConstraint::getTriangles() const
+{
+    return prim_tris_.get();
+}
+
+inline osg::DrawElementsUInt *DelaunayConstraint::getTriangles()
+{
+    return prim_tris_.get();
+}
+
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReflectionMapGenerator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReflectionMapGenerator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReflectionMapGenerator (revision 5328)
@@ -0,0 +1,55 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+#ifndef OSGUTIL_REFLECTIONMAPGENERATOR_
+#define OSGUTIL_REFLECTIONMAPGENERATOR_
+
+#include <osgUtil/CubeMapGenerator>
+
+namespace osgUtil
+{
+
+    /** This is the most simple cube map generator. It performs a direct association 
+        between reflection vector and RGBA color (C = R).
+    */
+    class ReflectionMapGenerator: public CubeMapGenerator {
+    public:
+        inline ReflectionMapGenerator(int texture_size = 64);
+        inline ReflectionMapGenerator(const ReflectionMapGenerator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY);
+
+    protected:
+        virtual ~ReflectionMapGenerator() {}
+        ReflectionMapGenerator &operator=(const ReflectionMapGenerator &) { return *this; }
+
+        inline virtual osg::Vec4 compute_color(const osg::Vec3 &R) const;
+    };
+
+    // INLINE METHODS
+
+    inline ReflectionMapGenerator::ReflectionMapGenerator(int texture_size)
+        : CubeMapGenerator(texture_size)
+    {
+    }
+
+    inline ReflectionMapGenerator::ReflectionMapGenerator(const ReflectionMapGenerator &copy, const osg::CopyOp &copyop)
+        : CubeMapGenerator(copy, copyop)
+    {
+    }
+
+    inline osg::Vec4 ReflectionMapGenerator::compute_color(const osg::Vec3 &R) const
+    {
+        return vector_to_color(R / R.length());
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TriStripVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TriStripVisitor (revision 8651)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TriStripVisitor (revision 8651)
@@ -0,0 +1,91 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_TRISTRIPVISITOR
+#define OSGUTIL_TRISTRIPVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/Geometry>
+
+#include <osgUtil/Optimizer>
+
+#include <set>
+
+namespace osgUtil {
+
+/** A tri stripping visitor for converting Geometry surface primitives into tri strips.
+  * The current implemention is based upon Tanguy Fautre's triangulation code.
+  */
+class OSGUTIL_EXPORT TriStripVisitor : public BaseOptimizerVisitor
+{
+    public:
+
+        /// default to traversing all children.
+        TriStripVisitor(Optimizer* optimizer=0) : 
+                BaseOptimizerVisitor( optimizer, Optimizer::TRISTRIP_GEOMETRY), 
+                _cacheSize( 16 ),
+                _minStripSize( 2 ),
+                _generateFourPointPrimitivesQuads ( false)
+        {}
+
+        /** Convert mesh primitives in Geometry into Tri Strips.
+          * Converts all primitive types except points
+          * and lines, linestrips which it leaves unchanged.
+          */
+        void stripify(osg::Geometry& drawable);
+
+        /** Stripify (make into strips of tria or quads) the accumulated list of Geometry drawables.*/
+        void stripify();
+
+        /// Accumulate the Geometry drawables to make into strips.
+        virtual void apply(osg::Geode& geode);
+
+        inline void setCacheSize( unsigned int size )
+        {
+            _cacheSize = size;
+        }
+        
+        inline unsigned int getCacheSize() const
+        {
+            return _cacheSize;
+        }
+        
+        inline void setMinStripSize( unsigned int size )
+        {
+            _minStripSize = size;
+        }
+        
+        inline unsigned int getMinStripSize() const
+        {
+            return _minStripSize;
+        }
+        
+        
+        void setGenerateFourPointPrimitivesQuads(bool flag) { _generateFourPointPrimitivesQuads = flag; }
+        bool getGenerateFourPointPrimitivesQuads() const { return _generateFourPointPrimitivesQuads; }
+        
+
+    private:
+    
+        typedef std::set<osg::Geometry*> GeometryList;
+
+        unsigned int _cacheSize;
+        unsigned int _minStripSize;
+        GeometryList _geometryList;
+        bool         _generateFourPointPrimitivesQuads;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformAttributeFunctor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformAttributeFunctor (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/TransformAttributeFunctor (revision 5328)
@@ -0,0 +1,45 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_TRANSFORMATTRIBUTEFUNCTOR
+#define OSGUTIL_TRANSFORMATTRIBUTEFUNCTOR 1
+
+#include <osg/Drawable>
+#include <osg/Notify>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** Functor for transforming a drawable's vertex and normal attributes by specified matrix.
+  * typically used for flattening transform down onto drawable leaves. */
+class OSGUTIL_EXPORT TransformAttributeFunctor : public osg::Drawable::AttributeFunctor
+{
+    public:
+    
+        /** Construct a functor to transform a drawable's vertex and normal attributes by specified matrix.*/
+        TransformAttributeFunctor(const osg::Matrix& m);
+            
+        virtual ~TransformAttributeFunctor();
+
+        /** Do the work of transforming vertex and normal attributes. */
+        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin);
+
+        osg::Matrix _m;
+        osg::Matrix _im;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/UpdateVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/UpdateVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/UpdateVisitor (revision 9377)
@@ -0,0 +1,114 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_UPDATEVISITOR
+#define OSGUTIL_UPDATEVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/Node>
+#include <osg/Geode>
+#include <osg/Billboard>
+#include <osg/LOD>
+#include <osg/Switch>
+#include <osg/LightSource>
+#include <osg/Transform>
+#include <osg/Projection>
+#include <osg/OccluderNode>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/**
+ * Basic UpdateVisitor implementation for animating a scene.
+ * This visitor traverses the scene graph, calling each nodes appCallback if
+ * it exists. 
+ */
+class OSGUTIL_EXPORT UpdateVisitor : public osg::NodeVisitor
+{
+    public:
+
+        UpdateVisitor();
+        virtual ~UpdateVisitor();
+
+        META_NodeVisitor("osgUtil","UpdateVisitor")
+
+        virtual void reset();
+
+        /** During traversal each type of node calls its callbacks and its children traversed. */
+        virtual void apply(osg::Node& node)         { handle_callbacks_and_traverse(node); }
+        
+        virtual void apply(osg::Geode& node)        { handle_geode_callbacks(node); }
+        virtual void apply(osg::Billboard& node)    { handle_geode_callbacks(node); }
+        
+        virtual void apply(osg::LightSource& node)  { handle_callbacks_and_traverse(node); }
+        
+        virtual void apply(osg::Group& node)        { handle_callbacks_and_traverse(node); }
+        virtual void apply(osg::Transform& node)    { handle_callbacks_and_traverse(node); }
+        virtual void apply(osg::Projection& node)   { handle_callbacks_and_traverse(node); }
+        virtual void apply(osg::Switch& node)       { handle_callbacks_and_traverse(node); }
+        virtual void apply(osg::LOD& node)          { handle_callbacks_and_traverse(node); }
+        virtual void apply(osg::OccluderNode& node) { handle_callbacks_and_traverse(node); }
+
+
+    protected:
+
+//         /** Prevent unwanted copy construction.*/
+//         UpdateVisitor(const UpdateVisitor&):osg::NodeVisitor() {}
+
+        /** Prevent unwanted copy operator.*/
+        UpdateVisitor& operator = (const UpdateVisitor&) { return *this; }
+        
+        inline void handle_callbacks(osg::StateSet* stateset)
+        {
+            if (stateset && stateset->requiresUpdateTraversal())
+            {
+                stateset->runUpdateCallbacks(this);
+            }
+        }
+        
+        inline void handle_callbacks_and_traverse(osg::Node& node)
+        {
+            handle_callbacks(node.getStateSet());
+
+            osg::NodeCallback* callback = node.getUpdateCallback();
+            if (callback) (*callback)(&node,this);
+            else if (node.getNumChildrenRequiringUpdateTraversal()>0) traverse(node);
+        }
+
+        inline void handle_geode_callbacks(osg::Geode& geode)
+        {
+            handle_callbacks(geode.getStateSet());
+
+            osg::NodeCallback* callback = geode.getUpdateCallback();
+            if (callback) (*callback)(&geode,this);
+
+            // Call the app callbacks on the drawables.
+            for(unsigned int i=0;i<geode.getNumDrawables();++i)
+            {
+                osg::Drawable::UpdateCallback* callback = geode.getDrawable(i)->getUpdateCallback();
+                if (callback) callback->update(this,geode.getDrawable(i));
+                
+                handle_callbacks(geode.getDrawable(i)->getStateSet());
+            }
+            
+            // should we traverse just in case a subclass of Geode adds children??  Won't for now as
+            // Geode's arn't designed to have children.
+            // traverse(geode);
+        }    
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Simplifier
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Simplifier (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/Simplifier (revision 9377)
@@ -0,0 +1,121 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_SIMPLIFIER
+#define OSGUTIL_SIMPLIFIER 1
+
+#include <osg/NodeVisitor>
+#include <osg/Geode>
+#include <osg/Geometry>
+
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+/** A simplifier for reducing the number of traingles in osg::Geometry.
+  */
+class OSGUTIL_EXPORT Simplifier : public osg::NodeVisitor
+{
+    public:
+
+        Simplifier(double sampleRatio=1.0, double maximumError=FLT_MAX, double maximumLength=0.0);
+
+        META_NodeVisitor("osgUtil","Simplifier")
+
+        void setSampleRatio(float sampleRatio) { _sampleRatio = sampleRatio; }
+        float getSampleRatio() const { return _sampleRatio; }
+
+        /** Set the maximum point error that all point removals must be less than to permit removal of a point.
+          * Note, Only used when down sampling. i.e. sampleRatio < 1.0*/
+        void setMaximumError(float error) { _maximumError = error; }
+        float getMaximumError() const { return _maximumError; }
+
+        /** Set the maximum length target that all edges must be shorted than.
+          * Note, Only used when up sampling i.e. sampleRatio > 1.0.*/
+        void setMaximumLength(float length) { _maximumLength = length; }
+        float getMaximumLength() const { return _maximumLength; }
+
+        void setDoTriStrip(bool on) { _triStrip = on; }
+        bool getDoTriStrip() const { return _triStrip; }
+
+        void setSmoothing(bool on) { _smoothing = on; }
+        bool getSmoothing() const { return _smoothing; }
+        
+        class ContinueSimplificationCallback : public osg::Referenced
+        {
+            public:
+                /** return true if mesh should be continued to be simplified, return false to stop simplification.*/
+                virtual bool continueSimplification(const Simplifier& simplifier, float nextError, unsigned int numOriginalPrimitives, unsigned int numRemainingPrimitives) const
+                {
+                    return simplifier.continueSimplificationImplementation(nextError, numOriginalPrimitives, numRemainingPrimitives);
+                }
+            
+            protected:
+                virtual ~ContinueSimplificationCallback() {}
+        };
+        
+        void setContinueSimplificationCallback(ContinueSimplificationCallback* cb) { _continueSimplificationCallback = cb; }
+        ContinueSimplificationCallback* getContinueSimplificationCallback() { return _continueSimplificationCallback.get(); }
+        const ContinueSimplificationCallback* getContinueSimplificationCallback() const { return _continueSimplificationCallback.get(); }
+        
+        
+        bool continueSimplification(float nextError, unsigned int numOriginalPrimitives, unsigned int numRemainingPrimitives) const
+        {
+            if (_continueSimplificationCallback.valid()) return _continueSimplificationCallback->continueSimplification(*this, nextError, numOriginalPrimitives, numRemainingPrimitives);
+            else return continueSimplificationImplementation(nextError, numOriginalPrimitives, numRemainingPrimitives);
+        }
+
+        virtual bool continueSimplificationImplementation(float nextError, unsigned int numOriginalPrimitives, unsigned int numRemainingPrimitives) const
+        {
+            if (getSampleRatio()<1.0) return ((float)numRemainingPrimitives > ((float)numOriginalPrimitives) * getSampleRatio()) && nextError<=getMaximumError();
+            else return ((float)numRemainingPrimitives < ((float)numOriginalPrimitives) * getSampleRatio()) && nextError>getMaximumLength();
+        }
+
+
+        virtual void apply(osg::Geode& geode)
+        {
+            for(unsigned int i=0;i<geode.getNumDrawables();++i)
+            {
+                osg::Geometry* geometry = geode.getDrawable(i)->asGeometry();
+                if (geometry)
+                {
+                    simplify(*geometry);
+                }
+            }
+        }
+
+        /** simply the geometry.*/
+        void simplify(osg::Geometry& geometry);
+        
+        typedef std::vector<unsigned int> IndexList; /// a list of point indices
+
+        /** simply the geometry, whilst protecting key points from being modified.*/
+        void simplify(osg::Geometry& geometry, const IndexList& protectedPoints);
+
+
+    protected:
+    
+        double _sampleRatio;
+        double _maximumError;
+        double _maximumLength;
+        bool  _triStrip;
+        bool  _smoothing;
+        
+        osg::ref_ptr<ContinueSimplificationCallback> _continueSimplificationCallback;
+    
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReversePrimitiveFunctor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReversePrimitiveFunctor (revision 7791)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/ReversePrimitiveFunctor (revision 7791)
@@ -0,0 +1,60 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_REVERSEPRIMITIVEFUNCTOR
+#define OSGUTIL_REVERSEPRIMITIVEFUNCTOR 1
+
+#include <osg/PrimitiveSet>
+#include <osg/Notify>
+#include <osgUtil/Export>
+
+namespace osgUtil {
+
+
+class OSGUTIL_EXPORT ReversePrimitiveFunctor : public osg::PrimitiveIndexFunctor
+{
+    public:
+    
+        virtual ~ReversePrimitiveFunctor() {}
+    
+        osg::PrimitiveSet * getReversedPrimitiveSet() { return _reversedPrimitiveSet.get(); }
+        
+        virtual void setVertexArray(unsigned int , const osg::Vec2* ) {}
+        virtual void setVertexArray(unsigned int , const osg::Vec3* ) {}
+        virtual void setVertexArray(unsigned int , const osg::Vec4* ) {}
+        virtual void setVertexArray(unsigned int , const osg::Vec2d* ) {}
+        virtual void setVertexArray(unsigned int , const osg::Vec3d* ) {}
+        virtual void setVertexArray(unsigned int , const osg::Vec4d* ) {}
+    
+        virtual void drawArrays(GLenum mode,GLint first,GLsizei count);
+        virtual void drawElements(GLenum mode,GLsizei count, const GLubyte* indices);
+        virtual void drawElements(GLenum mode,GLsizei count, const GLushort* indices);
+        virtual void drawElements(GLenum mode,GLsizei count, const GLuint* indices);
+     
+    
+        /// Mimics the OpenGL \c glBegin() function.
+        virtual void begin(GLenum mode);
+        virtual void vertex(unsigned int /*pos*/);
+        virtual void end();
+        
+        
+        osg::ref_ptr<osg::PrimitiveSet> _reversedPrimitiveSet;
+    
+    private:
+    
+        bool _running;
+};
+
+} // end osgUtil namespace
+
+#endif // ** OSGUTIL_REVERSEFACEVISITOR ** //
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderBin
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderBin (revision 6069)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/RenderBin (revision 6069)
@@ -0,0 +1,194 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSGUTIL_RENDERBIN
+#define OSGUTIL_RENDERBIN 1
+
+#include <osgUtil/StateGraph>
+
+#include <map>
+#include <vector>
+#include <string>
+
+namespace osgUtil {
+
+class RenderStage;
+class Statistics;
+/**
+ * RenderBin base class. Renderbin contains geometries to be rendered as a group, 
+ * renderbins are rendered once each.  They can improve efficiency or 
+ * use different rendering algorithms.
+ * A renderBin can contain further renderBins producing a tree hierarchy of renderBins.
+ */
+class OSGUTIL_EXPORT RenderBin : public osg::Object
+{
+    public:
+    
+        typedef std::vector<RenderLeaf*>                    RenderLeafList; 
+        typedef std::vector<StateGraph*>                    StateGraphList;
+        typedef std::map< int, osg::ref_ptr<RenderBin> >    RenderBinList; 
+
+        enum SortMode
+        {
+            SORT_BY_STATE,
+            SORT_BY_STATE_THEN_FRONT_TO_BACK,
+            SORT_FRONT_TO_BACK,
+            SORT_BACK_TO_FRONT
+        };
+
+        // static methods.
+        static RenderBin* createRenderBin(const std::string& binName);
+        static RenderBin* getRenderBinPrototype(const std::string& binName);
+        static void addRenderBinPrototype(const std::string& binName,RenderBin* proto);
+        static void removeRenderBinPrototype(RenderBin* proto);
+        
+        static void setDefaultRenderBinSortMode(SortMode mode);
+        static SortMode getDefaultRenderBinSortMode();
+
+
+
+        RenderBin();
+        
+        RenderBin(SortMode mode);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        RenderBin(const RenderBin& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        virtual osg::Object* cloneType() const { return new RenderBin(); }
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new RenderBin(*this,copyop); } // note only implements a clone of type.
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const RenderBin*>(obj)!=0L; }
+        virtual const char* libraryName() const { return "osgUtil"; }
+        virtual const char* className() const { return "RenderBin"; }
+
+        virtual void reset();
+        
+        void setStateSet(osg::StateSet* stateset) { _stateset = stateset; }
+        osg::StateSet* getStateSet() { return _stateset.get(); }
+        const osg::StateSet* getStateSet() const { return _stateset.get(); }
+        
+        
+        RenderBin* getParent() { return _parent; }
+        const RenderBin* getParent() const { return _parent; }
+
+        RenderStage* getStage() { return _stage; }
+        const RenderStage* getStage() const { return _stage; }
+
+        int getBinNum() const { return _binNum; }
+
+        StateGraphList& getStateGraphList() { return _stateGraphList; }
+        const StateGraphList& getStateGraphList() const { return _stateGraphList; }
+
+        RenderBinList& getRenderBinList() { return _bins; }
+        const RenderBinList& getRenderBinList() const { return _bins; }
+
+        RenderLeafList& getRenderLeafList() { return _renderLeafList; }
+        const RenderLeafList& getRenderLeafList() const { return _renderLeafList; }
+
+
+        RenderBin* find_or_insert(int binNum,const std::string& binName);
+
+        void addStateGraph(StateGraph* rg)
+        {
+            _stateGraphList.push_back(rg);
+        }
+
+        virtual void sort();
+
+        virtual void sortImplementation();
+    
+        void setSortMode(SortMode mode);
+        SortMode getSortMode() const { return _sortMode; }
+
+        virtual void sortByState();
+        virtual void sortByStateThenFrontToBack();
+        virtual void sortFrontToBack();
+        virtual void sortBackToFront();
+        
+        struct SortCallback : public osg::Referenced    
+        {
+            virtual void sortImplementation(RenderBin*) = 0;
+        };
+
+        void setSortCallback(SortCallback* sortCallback) { _sortCallback = sortCallback; }
+        SortCallback* getSortCallback() { return _sortCallback.get(); }
+        const SortCallback* getSortCallback() const { return _sortCallback.get(); }
+
+
+
+        virtual void draw(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+        virtual void drawImplementation(osg::RenderInfo& renderInfo,RenderLeaf*& previous);
+
+        struct DrawCallback : public osg::Referenced    
+        {
+            virtual void drawImplementation(RenderBin* bin,osg::RenderInfo& renderInfo,RenderLeaf*& previous) = 0;
+        };
+
+        void setDrawCallback(DrawCallback* drawCallback) { _drawCallback = drawCallback; }
+        DrawCallback* getDrawCallback() { return _drawCallback.get(); }
+        const DrawCallback* getDrawCallback() const { return _drawCallback.get(); }
+
+        /** Extract stats for current draw list. */
+        bool getStats(Statistics& primStats) const;
+        
+        /** Compute the number of dynamic RenderLeaves.*/
+        virtual unsigned int computeNumberOfDynamicRenderLeaves() const;
+
+        void copyLeavesFromStateGraphListToRenderLeafList();
+
+    protected:
+
+        virtual ~RenderBin();
+   
+        int                             _binNum;
+        RenderBin*                      _parent;
+        RenderStage*                    _stage;
+        RenderBinList                   _bins;
+        StateGraphList                  _stateGraphList;
+        RenderLeafList                  _renderLeafList;
+
+        bool                            _sorted;           
+        SortMode                        _sortMode;
+        osg::ref_ptr<SortCallback>      _sortCallback;
+
+        osg::ref_ptr<DrawCallback>      _drawCallback;
+
+        osg::ref_ptr<osg::StateSet>     _stateset;
+
+};
+
+/** Proxy class for automatic registration of renderbins with the RenderBin prototypelist.*/
+class RegisterRenderBinProxy
+{
+    public:
+        RegisterRenderBinProxy(const std::string& binName,RenderBin* proto)
+        {
+            _rb = proto;
+            RenderBin::addRenderBinPrototype(binName,_rb.get());
+        }
+
+        ~RegisterRenderBinProxy()
+        {
+            RenderBin::removeRenderBinPrototype(_rb.get());
+        }
+        
+    protected:
+        osg::ref_ptr<RenderBin> _rb;
+};
+
+
+}
+
+#endif
+
+    
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HighlightMapGenerator
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HighlightMapGenerator (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osgUtil/HighlightMapGenerator (revision 5328)
@@ -0,0 +1,63 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+#ifndef OSGUTIL_HIGHLIGHTMAPGENERATOR_
+#define OSGUTIL_HIGHLIGHTMAPGENERATOR_
+
+#include <osgUtil/Export>
+
+#include <osgUtil/CubeMapGenerator>
+
+namespace osgUtil
+{
+
+    /** This cube map generator produces a specular highlight map. 
+      * The vector-color association is: C = (R dot (-L)) ^ n, where C is the 
+      * resulting color, R is the reflection vector, L is the light direction 
+      * and n is the specular exponent.
+      */
+    class OSGUTIL_EXPORT HighlightMapGenerator: public CubeMapGenerator {
+    public:
+        HighlightMapGenerator(
+            const osg::Vec3 &light_direction, 
+            const osg::Vec4 &light_color, 
+            float specular_exponent, 
+            int texture_size = 64);
+
+        HighlightMapGenerator(const HighlightMapGenerator &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY);
+
+    protected:
+        virtual ~HighlightMapGenerator() {}
+        HighlightMapGenerator &operator=(const HighlightMapGenerator &) { return *this; }
+
+        inline virtual osg::Vec4 compute_color(const osg::Vec3 &R) const;
+
+    private:
+        osg::Vec3 ldir_;
+        osg::Vec4 lcol_;
+        float sexp_;
+    };
+
+    // INLINE METHODS
+
+    inline osg::Vec4 HighlightMapGenerator::compute_color(const osg::Vec3 &R) const
+    {
+        float v = -ldir_ * (R / R.length());
+        if (v < 0) v = 0;
+        osg::Vec4 color(lcol_ * powf(v, sexp_));
+        color.w() = 1;
+        return color;
+    }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Viewport
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Viewport (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Viewport (revision 7648)
@@ -0,0 +1,137 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VIEWPORT
+#define OSG_VIEWPORT 1
+
+#include <osg/StateAttribute>
+#include <osg/Matrix>
+
+namespace osg {
+
+/** Encapsulate OpenGL glViewport. */     
+class OSG_EXPORT Viewport : public StateAttribute
+{
+    public :
+
+#if 0
+        typedef int value_type;
+#else
+        typedef double value_type;
+#endif
+        Viewport();
+        
+        Viewport(value_type x,value_type y,value_type width,value_type height):
+            _x(x),
+            _y(y),
+            _width(width),
+            _height(height) {}
+            
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Viewport(const Viewport& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(vp,copyop),
+            _x(vp._x),
+            _y(vp._y),
+            _width(vp._width),
+            _height(vp._height) {}
+
+        META_StateAttribute(osg, Viewport,VIEWPORT);
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(Viewport,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_x)
+            COMPARE_StateAttribute_Parameter(_y)
+            COMPARE_StateAttribute_Parameter(_width)
+            COMPARE_StateAttribute_Parameter(_height)
+            
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+        inline void setViewport(value_type x,value_type y,value_type width,value_type height)
+        {
+            _x = x;
+            _y = y;
+            _width = width;
+            _height = height;
+        }
+
+#if 0        
+        void getViewport(int& x,int& y,int& width,int& height) const
+        {
+            x = _x;
+            y = _y;
+            width = _width;
+            height = _height;
+        }
+
+        void getViewport(double& x,double& y,double& width,double& height) const
+        {
+            x = _x;
+            y = _y;
+            width = _width;
+            height = _height;
+        }
+#endif
+        inline value_type& x() { return _x; }
+        inline value_type x() const { return _x; }
+
+        inline value_type& y() { return _y; }
+        inline value_type y() const { return _y; }
+
+        inline value_type& width() { return _width; }
+        inline value_type width() const { return _width; }
+
+        inline value_type& height() { return _height; }
+        inline value_type height() const { return _height; }
+
+        inline bool valid() const { return _width>0 && _height>0; }
+
+        /** Return the aspectRatio of the viewport, which is equal to width/height.
+          * If height is zero, the potential division by zero is avoided by simply returning 1.0f.
+        */
+        inline double aspectRatio() const { if (_height!=0) return (double)_width/(double)_height; else return 1.0; }
+        
+        /** Compute the Window Matrix which takes projected coords into Window coordinates.
+          * To convert local coordinates into window coordinates use v_window = v_local * MVPW matrix,
+          * where the MVPW matrix is ModelViewMatrix * ProjectionMatrix * WindowMatrix, the latter supplied by
+          * Viewport::computeWindowMatrix(), the ModelView and Projection Matrix can either be sourced from the
+          * current osg::State object, via osgUtil::SceneView or CullVisitor.
+        */
+        inline const osg::Matrix computeWindowMatrix() const
+        {
+            return osg::Matrix::translate(1.0,1.0,1.0)*osg::Matrix::scale(0.5*width(),0.5*height(),0.5f)*osg::Matrix::translate(x(),y(),0.0f);
+        }
+
+        virtual void apply(State& state) const;
+
+    protected:
+    
+        virtual ~Viewport();
+
+        value_type _x;
+        value_type _y;
+        value_type _width;
+        value_type _height;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PointSprite
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PointSprite (revision 6311)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PointSprite (revision 6311)
@@ -0,0 +1,80 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+ */
+
+#ifndef OSG_POINTSPRITE
+#define OSG_POINTSPRITE 1
+
+#include <osg/GL>
+#include <osg/StateAttribute>
+
+#ifndef GL_ARB_point_sprite
+#define GL_POINT_SPRITE_ARB               0x8861
+#define GL_COORD_REPLACE_ARB              0x8862
+#endif
+
+#ifndef GL_POINT_SPRITE_COORD_ORIGIN
+#define GL_POINT_SPRITE_COORD_ORIGIN      0x8CA0
+#define GL_LOWER_LEFT                     0x8CA1
+#define GL_UPPER_LEFT                     0x8CA2
+#endif
+
+namespace osg {
+
+/** PointSprite base class which encapsulates enabling of point sprites .*/
+class OSG_EXPORT PointSprite : public osg::StateAttribute {
+public:
+
+        PointSprite();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        PointSprite(const PointSprite& ps,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY):        
+            StateAttribute(ps,copyop),
+            _coordOriginMode(ps._coordOriginMode) {}
+
+
+        META_StateAttribute(osg, PointSprite, POINTSPRITE);
+
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const;
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_POINT_SPRITE_ARB);
+            return true;
+        }
+
+        virtual bool checkValidityOfAssociatedModes(osg::State&) const;
+
+        virtual bool isTextureAttribute() const { return true; }
+
+        virtual void apply(osg::State& state) const;
+
+        static bool isPointSpriteSupported(unsigned int context);
+        
+        enum CoordOriginMode {
+            UPPER_LEFT = GL_UPPER_LEFT,
+            LOWER_LEFT = GL_LOWER_LEFT
+        };
+        
+        inline void setCoordOriginMode(CoordOriginMode mode) { _coordOriginMode = mode; }
+        inline CoordOriginMode getCoordOriginMode() const { return _coordOriginMode; }
+
+protected:
+        virtual ~PointSprite();
+        
+        CoordOriginMode _coordOriginMode;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Node
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Node (revision 9617)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Node (revision 9617)
@@ -0,0 +1,433 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+
+#ifndef OSG_NODE
+#define OSG_NODE 1
+
+#include <osg/Object>
+#include <osg/StateSet>
+#include <osg/BoundingSphere>
+#include <osg/NodeCallback>
+
+#include <string>
+#include <vector>
+
+namespace osg {
+
+class NodeVisitor;
+class Group;
+class Transform;
+class Node;
+class Switch;
+class Geode;
+
+/** A vector of Nodes pointers which is used to describe the path from a root node to a descendant.*/
+typedef std::vector< Node* > NodePath;
+
+/** A vector of NodePath, typically used to describe all the paths from a node to the potential root nodes it has.*/
+typedef std::vector< NodePath > NodePathList;
+
+/** A vector of NodePath, typically used to describe all the paths from a node to the potential root nodes it has.*/
+typedef std::vector< Matrix > MatrixList;
+
+/** META_Node macro define the standard clone, isSameKindAs, className
+  * and accept methods.  Use when subclassing from Node to make it
+  * more convenient to define the required pure virtual methods.*/
+#define META_Node(library,name) \
+        virtual osg::Object* cloneType() const { return new name (); } \
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const name *>(obj)!=NULL; } \
+        virtual const char* className() const { return #name; } \
+        virtual const char* libraryName() const { return #library; } \
+        virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } \
+        
+
+/** Base class for all internal nodes in the scene graph.
+    Provides interface for most common node operations (Composite Pattern).
+*/
+class OSG_EXPORT Node : public Object
+{
+    public:
+
+        /** Construct a node.
+            Initialize the parent list to empty, node name to "" and 
+            bounding sphere dirty flag to true.*/
+        Node();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Node(const Node&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        /** clone an object of the same type as the node.*/
+        virtual Object* cloneType() const { return new Node(); }
+
+        /** return a clone of a node, with Object* return type.*/
+        virtual Object* clone(const CopyOp& copyop) const { return new Node(*this,copyop); }
+
+        /** return true if this and obj are of the same kind of object.*/
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Node*>(obj)!=NULL; }
+
+        /** return the name of the node's library.*/
+        virtual const char* libraryName() const { return "osg"; }
+
+        /** return the name of the node's class type.*/
+        virtual const char* className() const { return "Node"; }
+
+        /** convert 'this' into a Group pointer if Node is a Group, otherwise return 0.
+          * Equivalent to dynamic_cast<Group*>(this).*/
+        virtual Group* asGroup() { return 0; }
+        /** convert 'const this' into a const Group pointer if Node is a Group, otherwise return 0.
+          * Equivalent to dynamic_cast<const Group*>(this).*/
+        virtual const Group* asGroup() const { return 0; }
+
+        /** Convert 'this' into a Transform pointer if Node is a Transform, otherwise return 0.
+          * Equivalent to dynamic_cast<Transform*>(this).*/
+        virtual Transform* asTransform() { return 0; }
+
+        /** convert 'const this' into a const Transform pointer if Node is a Transform, otherwise return 0.
+          * Equivalent to dynamic_cast<const Transform*>(this).*/
+        virtual const Transform* asTransform() const { return 0; }
+
+        /** Convert 'this' into a Switch pointer if Node is a Switch, otherwise return 0.
+          * Equivalent to dynamic_cast<Switch*>(this).*/
+        virtual Switch* asSwitch() { return 0; }
+
+        /** convert 'const this' into a const Switch pointer if Node is a Switch, otherwise return 0.
+          * Equivalent to dynamic_cast<const Switch*>(this).*/
+        virtual const Switch* asSwitch() const { return 0; }
+
+        /** Convert 'this' into a Geode pointer if Node is a Geode, otherwise return 0.
+          * Equivalent to dynamic_cast<Geode*>(this).*/
+        virtual Geode* asGeode() { return 0; }
+
+        /** convert 'const this' into a const Geode pointer if Node is a Geode, otherwise return 0.
+          * Equivalent to dynamic_cast<const Geode*>(this).*/
+        virtual const Geode* asGeode() const { return 0; }
+
+        /** Visitor Pattern : calls the apply method of a NodeVisitor with this node's type.*/
+        virtual void accept(NodeVisitor& nv);
+        /** Traverse upwards : calls parents' accept method with NodeVisitor.*/
+        virtual void ascend(NodeVisitor& nv);
+        /** Traverse downwards : calls children's accept method with NodeVisitor.*/
+        virtual void traverse(NodeVisitor& /*nv*/) {}       
+
+        /** A vector of osg::Group pointers which is used to store the parent(s) of node.*/
+        typedef std::vector<Group*> ParentList;
+
+        /** Get the parent list of node. */
+        inline const ParentList& getParents() const { return _parents; }
+
+        /** Get the a copy of parent list of node. A copy is returned to 
+          * prevent modification of the parent list.*/
+        inline ParentList getParents() { return _parents; }
+
+        inline Group* getParent(unsigned int i)  { return _parents[i]; }
+
+        /**
+         * Get a single const parent of node.
+         * @param i index of the parent to get.
+         * @return the parent i.
+         */
+        inline const Group* getParent(unsigned int i) const  { return _parents[i]; }
+
+        /**
+         * Get the number of parents of node.
+         * @return the number of parents of this node.
+         */
+        inline unsigned int getNumParents() const { return static_cast<unsigned int>(_parents.size()); }
+
+        /** Get the list of node paths parent paths.
+          * The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node. */
+        NodePathList getParentalNodePaths(osg::Node* haltTraversalAtNode=0) const;
+
+        /** Get the list of matrices that transform this node from local coordinates to world coordinates.
+          * The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node. */
+        MatrixList getWorldMatrices(const osg::Node* haltTraversalAtNode=0) const;
+        
+
+        /** Set update node callback, called during update traversal. */
+        void setUpdateCallback(NodeCallback* nc);
+
+        /** Get update node callback, called during update traversal. */
+        inline NodeCallback* getUpdateCallback() { return _updateCallback.get(); }
+
+        /** Get const update node callback, called during update traversal. */
+        inline const NodeCallback* getUpdateCallback() const { return _updateCallback.get(); }
+
+        /** Convenience method that sets the update callback of the node if it doesn't exist, or nest it into the existing one. */
+        inline void addUpdateCallback(NodeCallback* nc) {
+            if (nc != NULL) {
+                if (_updateCallback.valid()) _updateCallback->addNestedCallback(nc);
+                else setUpdateCallback(nc);
+            }
+        }
+
+        /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */
+        inline void removeUpdateCallback(NodeCallback* nc) {
+            if (nc != NULL && _updateCallback.valid()) {
+                if (_updateCallback == nc) setUpdateCallback(nc->getNestedCallback());        // replace the callback by the nested one
+                else _updateCallback->removeNestedCallback(nc);
+            }
+        }
+
+        /** Get the number of Children of this node which require Update traversal,
+          * since they have an Update Callback attached to them or their children.*/
+        inline unsigned int getNumChildrenRequiringUpdateTraversal() const { return _numChildrenRequiringUpdateTraversal; }
+
+
+        /** Set event node callback, called during event traversal. */
+        void setEventCallback(NodeCallback* nc);
+
+        /** Get event node callback, called during event traversal. */
+        inline NodeCallback* getEventCallback() { return _eventCallback.get(); }
+
+        /** Get const event node callback, called during event traversal. */
+        inline const NodeCallback* getEventCallback() const { return _eventCallback.get(); }
+
+        /** Convenience method that sets the event callback of the node if it doesn't exist, or nest it into the existing one. */
+        inline void addEventCallback(NodeCallback* nc) {
+            if (nc != NULL) {
+                if (_eventCallback.valid()) _eventCallback->addNestedCallback(nc);
+                else setEventCallback(nc);
+            }
+        }
+
+        /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */
+        inline void removeEventCallback(NodeCallback* nc) {
+            if (nc != NULL && _eventCallback.valid()) {
+                if (_eventCallback == nc) setEventCallback(nc->getNestedCallback());        // replace the callback by the nested one
+                else _eventCallback->removeNestedCallback(nc);
+            }
+        }
+
+        /** Get the number of Children of this node which require Event traversal,
+          * since they have an Event Callback attached to them or their children.*/
+        inline unsigned int getNumChildrenRequiringEventTraversal() const { return _numChildrenRequiringEventTraversal; }
+
+
+        /** Set cull node callback, called during cull traversal. */
+        void setCullCallback(NodeCallback* nc) { _cullCallback = nc; }
+
+        /** Get cull node callback, called during cull traversal. */
+        inline NodeCallback* getCullCallback() { return _cullCallback.get(); }
+
+        /** Get const cull node callback, called during cull traversal. */
+        inline const NodeCallback* getCullCallback() const { return _cullCallback.get(); }
+
+        /** Convenience method that sets the cull callback of the node if it doesn't exist, or nest it into the existing one. */
+        inline void addCullCallback(NodeCallback* nc) {
+            if (nc != NULL) {
+                if (_cullCallback.valid()) _cullCallback->addNestedCallback(nc);
+                else setCullCallback(nc);
+            }
+        }
+
+        /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */
+        inline void removeCullCallback(NodeCallback* nc) {
+            if (nc != NULL && _cullCallback.valid()) {
+                if (_cullCallback == nc) setCullCallback(nc->getNestedCallback());        // replace the callback by the nested one
+                else _cullCallback->removeNestedCallback(nc);
+            }
+        }
+
+        /** Set the view frustum/small feature culling of this node to be active or inactive.
+          * The default value is true for _cullingActive. Used as a guide
+          * to the cull traversal.*/
+        void setCullingActive(bool active);
+
+        /** Get the view frustum/small feature _cullingActive flag for this node. Used as a guide
+          * to the cull traversal.*/
+        inline bool getCullingActive() const { return _cullingActive; }
+
+        /** Get the number of Children of this node which have culling disabled.*/
+        inline unsigned int getNumChildrenWithCullingDisabled() const { return _numChildrenWithCullingDisabled; }
+
+        /** Return true if this node can be culled by view frustum, occlusion or small feature culling during the cull traversal.
+          * Note, returns true only if no children have culling disabled, and the local _cullingActive flag is true.*/
+        inline bool isCullingActive() const { return _numChildrenWithCullingDisabled==0 && _cullingActive && getBound().valid(); }
+
+        /** Get the number of Children of this node which are or have OccluderNode's.*/
+        inline unsigned int getNumChildrenWithOccluderNodes() const { return _numChildrenWithOccluderNodes; }
+
+        
+        /** return true if this node is an OccluderNode or the subgraph below this node are OccluderNodes.*/
+        bool containsOccluderNodes() const;
+
+
+        typedef unsigned int NodeMask;
+        /** Set the node mask.*/
+        inline void setNodeMask(NodeMask nm) { _nodeMask = nm; }
+        /** Get the node Mask.*/
+        inline NodeMask getNodeMask() const { return _nodeMask; }
+
+
+
+        /** A vector of std::string's which are used to describe the object.*/
+        typedef std::vector<std::string> DescriptionList;
+
+        /** Set the description list of the node.*/        
+        inline void setDescriptions(const DescriptionList& descriptions) { _descriptions=descriptions; }
+
+        /** Get the description list of the node.*/        
+        inline DescriptionList& getDescriptions() { return _descriptions; }
+
+        /** Get the const description list of the const node.*/        
+        inline const DescriptionList& getDescriptions() const { return _descriptions; }
+
+        /** Get a single const description of the const node.*/
+        inline const std::string& getDescription(unsigned int i) const { return _descriptions[i]; }
+
+        /** Get a single description of the node.*/
+        inline std::string& getDescription(unsigned int i) { return _descriptions[i]; }
+
+        /** Get the number of descriptions of the node.*/
+        inline unsigned int getNumDescriptions() const { return static_cast<unsigned int>(_descriptions.size()); }
+
+        /** Add a description string to the node.*/
+        void addDescription(const std::string& desc) { _descriptions.push_back(desc); }
+
+
+        /** Set the node's StateSet.*/
+        void setStateSet(osg::StateSet* stateset);
+
+        /** return the node's StateSet, if one does not already exist create it
+          * set the node and return the newly created StateSet. This ensures
+          * that a valid StateSet is always returned and can be used directly.*/
+        osg::StateSet* getOrCreateStateSet();
+
+        /** Return the node's StateSet. returns NULL if a stateset is not attached.*/
+        inline osg::StateSet* getStateSet() { return _stateset.get(); }
+
+        /** Return the node's const StateSet. Returns NULL if a stateset is not attached.*/
+        inline const osg::StateSet* getStateSet() const { return _stateset.get(); }
+
+        /** Set the initial bounding volume to use when computing the overall bounding volume.*/
+        void setInitialBound(const osg::BoundingSphere& bsphere) { _initialBound = bsphere; dirtyBound(); }
+
+        /** Set the initial bounding volume to use when computing the overall bounding volume.*/
+        const BoundingSphere& getInitialBound() const { return _initialBound; }
+
+        /** Mark this node's bounding sphere dirty.
+            Forcing it to be computed on the next call to getBound().*/
+        void dirtyBound();
+
+        /** Get the bounding sphere of node.
+           Using lazy evaluation computes the bounding sphere if it is 'dirty'.*/
+        inline const BoundingSphere& getBound() const
+        {
+            if(!_boundingSphereComputed)
+            {
+                _boundingSphere = _initialBound;
+                if (_computeBoundCallback.valid()) 
+                    _boundingSphere.expandBy(_computeBoundCallback->computeBound(*this));
+                else
+                    _boundingSphere.expandBy(computeBound());
+                    
+                _boundingSphereComputed = true;
+            }
+            return _boundingSphere;
+        }
+
+
+        /** Compute the bounding sphere around Node's geometry or children.
+            This method is automatically called by getBound() when the bounding
+            sphere has been marked dirty via dirtyBound().*/
+        virtual BoundingSphere computeBound() const;
+
+        /** Callback to allow users to override the default computation of bounding volume.*/
+        struct ComputeBoundingSphereCallback : public osg::Object
+        {
+            ComputeBoundingSphereCallback() {}
+
+            ComputeBoundingSphereCallback(const ComputeBoundingSphereCallback&,const CopyOp&) {}
+
+            META_Object(osg,ComputeBoundingSphereCallback);
+
+           virtual BoundingSphere computeBound(const osg::Node&) const { return BoundingSphere(); }
+        };
+
+        /** Set the compute bound callback to override the default computeBound.*/
+        void setComputeBoundingSphereCallback(ComputeBoundingSphereCallback* callback) { _computeBoundCallback = callback; }
+
+        /** Get the compute bound callback.*/
+        ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() { return _computeBoundCallback.get(); }
+
+        /** Get the const compute bound callback.*/
+        const ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() const { return _computeBoundCallback.get(); }
+
+        /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/
+        virtual void setThreadSafeRefUnref(bool threadSafe);
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/);
+
+        /** If State is non-zero, this function releases any associated OpenGL objects for
+           * the specified graphics context. Otherwise, releases OpenGL objects
+           * for all graphics contexts. */
+        virtual void releaseGLObjects(osg::State* = 0) const;
+
+
+    protected:
+
+        /** Node destructor. Note, is protected so that Nodes cannot
+            be deleted other than by being dereferenced and the reference
+            count being zero (see osg::Referenced), preventing the deletion
+            of nodes which are still in use. This also means that
+            Nodes cannot be created on stack i.e Node node will not compile,
+            forcing all nodes to be created on the heap i.e Node* node
+            = new Node().*/
+        virtual ~Node();
+
+
+
+        BoundingSphere                          _initialBound;
+        ref_ptr<ComputeBoundingSphereCallback>  _computeBoundCallback;
+        mutable BoundingSphere                  _boundingSphere;
+        mutable bool                            _boundingSphereComputed;
+
+        void addParent(osg::Group* node);
+        void removeParent(osg::Group* node);
+
+        ParentList _parents;
+        friend class osg::Group;
+        friend class osg::Drawable;
+        friend class osg::StateSet;
+
+        ref_ptr<NodeCallback> _updateCallback;
+        unsigned int _numChildrenRequiringUpdateTraversal;
+        void setNumChildrenRequiringUpdateTraversal(unsigned int num);
+
+        ref_ptr<NodeCallback> _eventCallback;
+        unsigned int _numChildrenRequiringEventTraversal;
+        void setNumChildrenRequiringEventTraversal(unsigned int num);
+
+        ref_ptr<NodeCallback> _cullCallback;
+
+        bool _cullingActive;
+        unsigned int _numChildrenWithCullingDisabled;        
+        void setNumChildrenWithCullingDisabled(unsigned int num);
+
+        unsigned int _numChildrenWithOccluderNodes;        
+        void setNumChildrenWithOccluderNodes(unsigned int num);
+
+        NodeMask _nodeMask;
+        
+        DescriptionList _descriptions;
+
+        ref_ptr<StateSet> _stateset;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullStack
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullStack (revision 9576)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullStack (revision 9576)
@@ -0,0 +1,302 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_CULLSTACK
+#define OSG_CULLSTACK 1
+
+#include <osg/CullingSet>
+#include <osg/CullSettings>
+#include <osg/Viewport>
+#include <osg/fast_back_stack>
+#include <osg/Transform>
+
+namespace osg {
+
+/** A CullStack class which accumulates the current project, modelview matrices
+and the CullingSet. */
+class OSG_EXPORT CullStack : public osg::CullSettings
+{
+
+    public:
+    
+    
+        CullStack();
+        CullStack(const CullStack& cs);
+        
+        ~CullStack();
+    
+        typedef std::vector<ShadowVolumeOccluder>   OccluderList;
+
+        void reset();
+        
+        void pushCullingSet();
+        void popCullingSet();
+
+        void setOccluderList(const ShadowVolumeOccluderList& svol) { _occluderList = svol; }
+        ShadowVolumeOccluderList& getOccluderList() { return _occluderList; }
+        const ShadowVolumeOccluderList& getOccluderList() const { return _occluderList; }
+
+        void pushViewport(osg::Viewport* viewport);
+        void popViewport();
+
+        void pushProjectionMatrix(osg::RefMatrix* matrix);
+        void popProjectionMatrix();
+
+        void pushModelViewMatrix(osg::RefMatrix* matrix, Transform::ReferenceFrame referenceFrame);
+        void popModelViewMatrix();
+
+        inline float getFrustumVolume() { if (_frustumVolume<0.0f) computeFrustumVolume(); return _frustumVolume; }
+
+
+        /** Compute the pixel size of an object at position v, with specified radius.*/
+        float pixelSize(const Vec3& v,float radius) const
+        {
+            return getCurrentCullingSet().pixelSize(v,radius);
+        }
+        
+        /** Compute the pixel size of the bounding sphere.*/
+        float pixelSize(const BoundingSphere& bs) const
+        {
+            return pixelSize(bs.center(),bs.radius());
+        }
+
+        /** Compute the pixel size of an object at position v, with specified radius. fabs()ed to always be positive. */
+        float clampedPixelSize(const Vec3& v,float radius) const
+        {
+            return getCurrentCullingSet().clampedPixelSize(v,radius);
+        }
+        
+        /** Compute the pixel size of the bounding sphere. fabs()ed to always be positive. */
+        float clampedPixelSize(const BoundingSphere& bs) const
+        {
+            return clampedPixelSize(bs.center(),bs.radius());
+        }
+
+        inline void disableAndPushOccludersCurrentMask(NodePath& nodePath)
+        {
+            getCurrentCullingSet().disableAndPushOccludersCurrentMask(nodePath);
+        }
+
+        inline void popOccludersCurrentMask(NodePath& nodePath)
+        {
+            getCurrentCullingSet().popOccludersCurrentMask(nodePath);
+        }
+
+        inline bool isCulled(const std::vector<Vec3>& vertices)
+        {
+            return getCurrentCullingSet().isCulled(vertices);
+        }
+
+        inline bool isCulled(const BoundingBox& bb)
+        {
+            return bb.valid() && getCurrentCullingSet().isCulled(bb);
+        }
+        
+        inline bool isCulled(const BoundingSphere& bs)
+        {
+            return getCurrentCullingSet().isCulled(bs);
+        }
+        
+        inline bool isCulled(const osg::Node& node)
+        {
+            return node.isCullingActive() && getCurrentCullingSet().isCulled(node.getBound());
+        }
+
+        inline void pushCurrentMask()
+        {
+            getCurrentCullingSet().pushCurrentMask();
+        }
+        
+        inline void popCurrentMask()
+        {
+            getCurrentCullingSet().popCurrentMask();
+        }
+        
+        
+        typedef std::vector< CullingSet > CullingStack;
+
+        inline CullingStack& getClipSpaceCullingStack() { return _clipspaceCullingStack; }
+        
+        inline CullingStack& getProjectionCullingStack() { return _projectionCullingStack; }
+        
+        inline CullingStack& getModelViewCullingStack() { return _modelviewCullingStack; }
+        
+        inline CullingSet& getCurrentCullingSet() { return *_back_modelviewCullingStack; }
+        inline const CullingSet& getCurrentCullingSet() const { return *_back_modelviewCullingStack; }
+        
+        inline osg::Viewport* getViewport();
+        inline osg::RefMatrix* getModelViewMatrix();
+        inline osg::RefMatrix* getProjectionMatrix();
+        inline osg::Matrix getWindowMatrix();
+        inline const osg::RefMatrix* getMVPW();
+        
+        inline const osg::Vec3& getReferenceViewPoint() const { return _referenceViewPoints.back(); }
+        inline void pushReferenceViewPoint(const osg::Vec3& viewPoint) { _referenceViewPoints.push_back(viewPoint); }
+        inline void popReferenceViewPoint() { _referenceViewPoints.pop_back(); }
+
+        inline const osg::Vec3& getEyeLocal() const { return _eyePointStack.back(); }
+
+        inline const osg::Vec3& getViewPointLocal() const { return _viewPointStack.back(); }
+
+        inline const osg::Vec3 getUpLocal() const
+        {
+            const osg::Matrix& matrix = *_modelviewStack.back();
+            return osg::Vec3(matrix(0,1),matrix(1,1),matrix(2,1));
+        }
+
+        inline const osg::Vec3 getLookVectorLocal() const
+        {
+            const osg::Matrix& matrix = *_modelviewStack.back();
+            return osg::Vec3(-matrix(0,2),-matrix(1,2),-matrix(2,2));
+        }
+        
+
+    protected:
+    
+        // base set of shadow volume occluder to use in culling.
+        ShadowVolumeOccluderList                                    _occluderList;
+
+        typedef fast_back_stack< ref_ptr<RefMatrix> >                  MatrixStack;
+
+        MatrixStack                                                 _projectionStack;
+
+        MatrixStack                                                 _modelviewStack;
+        MatrixStack                                                 _MVPW_Stack;
+
+        typedef fast_back_stack<ref_ptr<Viewport> >                 ViewportStack;
+        ViewportStack                                               _viewportStack;
+        
+        typedef fast_back_stack<Vec3>                               EyePointStack;
+        EyePointStack                                               _referenceViewPoints;
+        EyePointStack                                               _eyePointStack;
+        EyePointStack                                               _viewPointStack;
+
+        CullingStack                                                _clipspaceCullingStack;
+        CullingStack                                                _projectionCullingStack;
+
+        CullingStack                                                _modelviewCullingStack;
+        unsigned int                                                _index_modelviewCullingStack;
+        CullingSet*                                                 _back_modelviewCullingStack;
+
+        void computeFrustumVolume();
+        float                                                       _frustumVolume;
+
+        unsigned int                                                _bbCornerNear;
+        unsigned int                                                _bbCornerFar;
+
+        ref_ptr<osg::RefMatrix>                                     _identity;
+        
+        typedef std::vector< osg::ref_ptr<osg::RefMatrix> > MatrixList;
+        MatrixList _reuseMatrixList;
+        unsigned int _currentReuseMatrixIndex;
+        
+        inline osg::RefMatrix* createOrReuseMatrix(const osg::Matrix& value);
+
+        
+};
+
+inline osg::Viewport* CullStack::getViewport()
+{
+    if (!_viewportStack.empty())
+    {
+        return _viewportStack.back().get();
+    }
+    else
+    {
+        return 0L;
+    }
+}
+
+inline osg::RefMatrix* CullStack::getModelViewMatrix()
+{
+    if (!_modelviewStack.empty())
+    {
+        return _modelviewStack.back().get();
+    }
+    else
+    {
+        return _identity.get();
+    }
+}
+
+inline osg::RefMatrix* CullStack::getProjectionMatrix()
+{
+    if (!_projectionStack.empty())
+    {
+        return _projectionStack.back().get();
+    }
+    else
+    {
+        return _identity.get();
+    }
+}
+
+inline osg::Matrix CullStack::getWindowMatrix()
+{
+    if (!_viewportStack.empty())
+    {
+        osg::Viewport* viewport = _viewportStack.back().get();
+        return viewport->computeWindowMatrix();
+    }
+    else
+    {
+        return *_identity;
+    }
+}
+
+inline const osg::RefMatrix* CullStack::getMVPW()
+{
+    if (!_MVPW_Stack.empty())
+    {
+        if (!_MVPW_Stack.back())
+        {
+            _MVPW_Stack.back() = createOrReuseMatrix(*getModelViewMatrix());
+            (*_MVPW_Stack.back()) *= *(getProjectionMatrix());
+            (*_MVPW_Stack.back()) *= getWindowMatrix();
+        }
+        return _MVPW_Stack.back().get();
+    }
+    else
+    {
+        return _identity.get();
+    }
+}
+
+inline RefMatrix* CullStack::createOrReuseMatrix(const osg::Matrix& value)
+{
+    // skip of any already reused matrix.
+    while (_currentReuseMatrixIndex<_reuseMatrixList.size() && 
+           _reuseMatrixList[_currentReuseMatrixIndex]->referenceCount()>1)
+    {
+        ++_currentReuseMatrixIndex;
+    }
+
+    // if still within list, element must be singularly referenced
+    // there return it to be reused.
+    if (_currentReuseMatrixIndex<_reuseMatrixList.size())
+    {
+        RefMatrix* matrix = _reuseMatrixList[_currentReuseMatrixIndex++].get();
+        matrix->set(value);
+        return matrix;
+    }
+
+    // otherwise need to create new matrix.
+    osg::RefMatrix* matrix = new RefMatrix(value);
+    _reuseMatrixList.push_back(matrix);
+    ++_currentReuseMatrixIndex;
+    return matrix;
+}
+
+}    // end of namespace
+
+#endif 
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2D
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2D (revision 8200)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2D (revision 8200)
@@ -0,0 +1,155 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXTURE2D
+#define OSG_TEXTURE2D 1
+
+#include <osg/Texture>
+
+namespace osg {
+
+/** Encapsulates OpenGl 2D texture functionality. Doesn't support cube maps,
+  * so ignore \a face parameters.
+*/
+class OSG_EXPORT Texture2D : public Texture
+{
+
+    public :
+        
+        Texture2D();
+
+        Texture2D(Image* image);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Texture2D(const Texture2D& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+        
+        META_StateAttribute(osg, Texture2D,TEXTURE);
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& rhs) const;
+
+        virtual GLenum getTextureTarget() const { return GL_TEXTURE_2D; }
+
+        /** Sets the texture image. */
+        void setImage(Image* image);
+
+        /** Gets the texture image. */
+        Image* getImage() { return _image.get(); }
+
+        /** Gets the const texture image. */
+        inline const Image* getImage() const { return _image.get(); }
+
+        inline unsigned int& getModifiedCount(unsigned int contextID) const
+        {
+            // get the modified count for the current contextID.
+            return _modifiedCount[contextID];
+        }
+
+
+        /** Sets the texture image, ignoring face. */
+        virtual void setImage(unsigned int, Image* image) { setImage(image); }
+
+        /** Gets the texture image, ignoring face. */
+        virtual Image* getImage(unsigned int) { return _image.get(); }
+
+        /** Gets the const texture image, ignoring face. */
+        virtual const Image* getImage(unsigned int) const { return _image.get(); }
+
+        /** Gets the number of images that can be assigned to the Texture. */
+        virtual unsigned int getNumImages() const { return 1; }
+
+
+        /** Sets the texture width and height. If width or height are zero,
+          * calculate the respective value from the source image size. */
+        inline void setTextureSize(int width, int height) const
+        {
+            _textureWidth = width;
+            _textureHeight = height;
+        }
+
+        void setTextureWidth(int width) { _textureWidth=width; }
+        void setTextureHeight(int height) { _textureHeight=height; }
+
+        virtual int getTextureWidth() const { return _textureWidth; }
+        virtual int getTextureHeight() const { return _textureHeight; }
+        virtual int getTextureDepth() const { return 1; }
+
+        class OSG_EXPORT SubloadCallback : public Referenced
+        {
+            public:
+                virtual void load(const Texture2D& texture,State& state) const = 0;
+                virtual void subload(const Texture2D& texture,State& state) const = 0;
+        };
+        
+        void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; }
+        
+        SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
+
+        const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
+
+
+        /** Helper function. Sets the number of mipmap levels created for this
+          * texture. Should only be called within an osg::Texture::apply(), or
+          * during a custom OpenGL texture load. */
+        void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; }
+
+        /** Gets the number of mipmap levels created. */
+        unsigned int getNumMipmapLevels() const { return _numMipmapLevels; }
+        
+
+        /** Copies pixels into a 2D texture image, as per glCopyTexImage2D.
+          * Creates an OpenGL texture object from the current OpenGL background
+          * framebuffer contents at position \a x, \a y with width \a width and
+          * height \a height. \a width and \a height must be a power of two. */
+        void copyTexImage2D(State& state, int x, int y, int width, int height );
+
+        /** Copies a two-dimensional texture subimage, as per
+          * glCopyTexSubImage2D. Updates a portion of an existing OpenGL
+          * texture object from the current OpenGL background framebuffer
+          * contents at position \a x, \a y with width \a width and height
+          * \a height. Loads framebuffer data into the texture using offsets
+          * \a xoffset and \a yoffset. \a width and \a height must be powers
+          * of two. */
+        void copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height );
+
+
+        /** Bind the texture object. If the texture object hasn't already been
+          * compiled, create the texture mipmap levels. */
+        virtual void apply(State& state) const;
+
+    protected :
+
+        virtual ~Texture2D();
+
+        virtual void computeInternalFormat() const;
+        void allocateMipmap(State& state) const;
+
+
+        ref_ptr<Image> _image;
+
+        /** Subloaded images can have different texture and image sizes. */
+        mutable GLsizei _textureWidth, _textureHeight;
+        
+        /** Number of mipmap levels created. */        
+        mutable GLsizei _numMipmapLevels;
+
+        ref_ptr<SubloadCallback> _subloadCallback;
+
+        typedef buffered_value<unsigned int> ImageModifiedCount;
+        mutable ImageModifiedCount _modifiedCount;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/DisplaySettings
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/DisplaySettings (revision 10349)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/DisplaySettings (revision 10349)
@@ -0,0 +1,247 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_DisplaySettings
+#define OSG_DisplaySettings 1
+
+#include <osg/Referenced>
+
+#include <string>
+#include <vector>
+
+namespace osg {
+
+// forward declare
+class ArgumentParser;
+class ApplicationUsage;
+
+/** DisplaySettings class for encapsulating what visuals are required and
+  * have been set up, and the status of stereo viewing.*/
+class OSG_EXPORT DisplaySettings : public osg::Referenced
+{
+
+    public:
+
+        /** Maintain a DisplaySettings singleton for objects to query at runtime.*/
+        static DisplaySettings* instance();
+
+
+        DisplaySettings():
+            Referenced(true)
+        {
+            setDefaults();
+            readEnvironmentalVariables();
+        }
+        
+        DisplaySettings(ArgumentParser& arguments):
+            Referenced(true)
+        {
+            setDefaults();
+            readEnvironmentalVariables();
+            readCommandLine(arguments);
+        }
+
+        DisplaySettings(const DisplaySettings& vs);
+        
+
+        DisplaySettings& operator = (const DisplaySettings& vs);
+ 
+        void setDisplaySettings(const DisplaySettings& vs);
+        
+        void merge(const DisplaySettings& vs);
+
+        void setDefaults();
+        
+        /** read the environmental variables.*/
+        void readEnvironmentalVariables();
+
+        /** read the commandline arguments.*/
+        void readCommandLine(ArgumentParser& arguments);
+        
+        
+        enum DisplayType
+        {
+            MONITOR,
+            POWERWALL,
+            REALITY_CENTER,
+            HEAD_MOUNTED_DISPLAY
+        };
+
+        void setDisplayType(DisplayType type) { _displayType = type; }
+        
+        DisplayType getDisplayType() const { return _displayType; }
+
+
+        void setStereo(bool on) { _stereo = on; }
+        bool getStereo() const { return _stereo; }
+
+        enum StereoMode
+        {
+            QUAD_BUFFER,
+            ANAGLYPHIC,
+            HORIZONTAL_SPLIT,
+            VERTICAL_SPLIT,
+            LEFT_EYE,
+            RIGHT_EYE,
+            HORIZONTAL_INTERLACE,
+            VERTICAL_INTERLACE,
+            CHECKERBOARD
+        };
+        
+        void setStereoMode(StereoMode mode) { _stereoMode = mode; }
+        StereoMode getStereoMode() const { return _stereoMode; }
+
+        void setEyeSeparation(float eyeSeparation) { _eyeSeparation = eyeSeparation; }
+        float getEyeSeparation() const { return _eyeSeparation; }
+
+        enum SplitStereoHorizontalEyeMapping
+        {
+            LEFT_EYE_LEFT_VIEWPORT,
+            LEFT_EYE_RIGHT_VIEWPORT
+        };
+        
+        void setSplitStereoHorizontalEyeMapping(SplitStereoHorizontalEyeMapping m) { _splitStereoHorizontalEyeMapping = m; }
+        SplitStereoHorizontalEyeMapping getSplitStereoHorizontalEyeMapping() const { return _splitStereoHorizontalEyeMapping; }
+
+        void setSplitStereoHorizontalSeparation(int s) { _splitStereoHorizontalSeparation = s; }
+        int getSplitStereoHorizontalSeparation() const { return _splitStereoHorizontalSeparation; }
+
+        enum SplitStereoVerticalEyeMapping
+        {
+            LEFT_EYE_TOP_VIEWPORT,
+            LEFT_EYE_BOTTOM_VIEWPORT
+        };
+
+        void setSplitStereoVerticalEyeMapping(SplitStereoVerticalEyeMapping m) { _splitStereoVerticalEyeMapping = m; }
+        SplitStereoVerticalEyeMapping getSplitStereoVerticalEyeMapping() const { return _splitStereoVerticalEyeMapping; }
+
+        void setSplitStereoVerticalSeparation(int s) { _splitStereoVerticalSeparation = s; }
+        int getSplitStereoVerticalSeparation() const { return _splitStereoVerticalSeparation; }
+
+        void setSplitStereoAutoAdjustAspectRatio(bool flag) { _splitStereoAutoAdjustAspectRatio=flag; }
+        bool getSplitStereoAutoAdjustAspectRatio() const { return _splitStereoAutoAdjustAspectRatio; }
+
+
+        void setScreenWidth(float width) { _screenWidth = width; }
+        float getScreenWidth() const { return _screenWidth; }
+
+        void setScreenHeight(float height) { _screenHeight = height; }
+        float getScreenHeight() const { return _screenHeight; }
+
+        void setScreenDistance(float distance) { _screenDistance = distance; }
+        float getScreenDistance() const { return _screenDistance; }
+
+
+
+        void setDoubleBuffer(bool flag) { _doubleBuffer = flag; }
+        bool getDoubleBuffer() const { return _doubleBuffer; }
+
+
+        void setRGB(bool flag) { _RGB = flag; }
+        bool getRGB() const { return _RGB; }
+
+
+        void setDepthBuffer(bool flag) { _depthBuffer = flag; }
+        bool getDepthBuffer() const { return _depthBuffer; }
+
+
+        void setMinimumNumAlphaBits(unsigned int bits) { _minimumNumberAlphaBits = bits; }
+        unsigned int getMinimumNumAlphaBits() const { return _minimumNumberAlphaBits; }
+        bool getAlphaBuffer() const { return _minimumNumberAlphaBits!=0; }
+
+        void setMinimumNumStencilBits(unsigned int bits) { _minimumNumberStencilBits = bits; }
+        unsigned int getMinimumNumStencilBits() const { return _minimumNumberStencilBits; }
+        bool getStencilBuffer() const { return _minimumNumberStencilBits!=0; }
+
+        void setMinimumNumAccumBits(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha);
+        unsigned int getMinimumNumAccumRedBits() const { return _minimumNumberAccumRedBits; }
+        unsigned int getMinimumNumAccumGreenBits() const { return _minimumNumberAccumGreenBits; }
+        unsigned int getMinimumNumAccumBlueBits() const { return _minimumNumberAccumBlueBits; }
+        unsigned int getMinimumNumAccumAlphaBits() const { return _minimumNumberAccumAlphaBits; }
+        bool getAccumBuffer() const { return (_minimumNumberAccumRedBits+_minimumNumberAccumGreenBits+_minimumNumberAccumBlueBits+_minimumNumberAccumAlphaBits)!=0; }
+
+
+        void setMaxNumberOfGraphicsContexts(unsigned int num);
+        unsigned int getMaxNumberOfGraphicsContexts() const;
+
+        void setNumMultiSamples(unsigned int samples) { _numMultiSamples = samples; }
+        unsigned int getNumMultiSamples() const { return _numMultiSamples; }
+        bool getMultiSamples() const { return _numMultiSamples!=0; }
+        
+        void setCompileContextsHint(bool useCompileContexts) { _compileContextsHint = useCompileContexts; }
+        bool getCompileContextsHint() const { return _compileContextsHint; }
+        
+        void setSerializeDrawDispatch(bool serializeDrawDispatch) { _serializeDrawDispatch = serializeDrawDispatch; }
+        bool getSerializeDrawDispatch() const { return _serializeDrawDispatch; }
+        
+        /** Set the hint for the total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/
+        void setNumOfDatabaseThreadsHint(unsigned int numThreads) { _numDatabaseThreadsHint = numThreads; }
+
+        /** Get the hint for total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/
+        unsigned int getNumOfDatabaseThreadsHint() const { return _numDatabaseThreadsHint; }
+
+        /** Set the hint for number of threads in the DatbasePager to dedicate to reading http requests.*/
+        void setNumOfHttpDatabaseThreadsHint(unsigned int numThreads) { _numHttpDatabaseThreadsHint = numThreads; }
+
+        /** Get the hint for number of threads in the DatbasePager dedicated to reading http requests.*/
+        unsigned int getNumOfHttpDatabaseThreadsHint() const { return _numHttpDatabaseThreadsHint; }
+        
+        void setApplication(const std::string& application) { _application = application; }
+        const std::string& getApplication() { return _application; }
+
+    protected:
+    
+        virtual ~DisplaySettings();
+
+
+        DisplayType                     _displayType;
+        bool                            _stereo;
+        StereoMode                      _stereoMode;
+        float                           _eyeSeparation;
+        float                           _screenWidth;
+        float                           _screenHeight;
+        float                           _screenDistance;
+
+        SplitStereoHorizontalEyeMapping _splitStereoHorizontalEyeMapping;
+        int                             _splitStereoHorizontalSeparation;
+        SplitStereoVerticalEyeMapping   _splitStereoVerticalEyeMapping;
+        int                             _splitStereoVerticalSeparation;
+        bool                            _splitStereoAutoAdjustAspectRatio;
+    
+        bool                            _doubleBuffer;
+        bool                            _RGB;
+        bool                            _depthBuffer;
+        unsigned int                    _minimumNumberAlphaBits;
+        unsigned int                    _minimumNumberStencilBits;
+        unsigned int                    _minimumNumberAccumRedBits;
+        unsigned int                    _minimumNumberAccumGreenBits;
+        unsigned int                    _minimumNumberAccumBlueBits;
+        unsigned int                    _minimumNumberAccumAlphaBits;
+
+        unsigned int                    _maxNumOfGraphicsContexts;
+        
+        unsigned int                    _numMultiSamples;
+        
+        bool                            _compileContextsHint;
+        bool                            _serializeDrawDispatch;
+
+        unsigned int                    _numDatabaseThreadsHint;
+        unsigned int                    _numHttpDatabaseThreadsHint;
+        
+        std::string                     _application;
+
+};
+
+}
+
+# endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Camera
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Camera (revision 9499)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Camera (revision 9499)
@@ -0,0 +1,578 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_CAMERA
+#define OSG_CAMERA 1
+
+#include <osg/Transform>
+#include <osg/Viewport>
+#include <osg/ColorMask>
+#include <osg/CullSettings>
+#include <osg/Texture>
+#include <osg/Image>
+#include <osg/GraphicsContext>
+#include <osg/Stats>
+
+#include <OpenThreads/Mutex>
+
+namespace osg {
+
+// forward declare View to allow Camera to point back to the View that its within
+class View;
+class RenderInfo;
+
+/** Camera - is a subclass of Transform which represents encapsulates the settings of a Camera.
+*/
+class OSG_EXPORT Camera : public Transform, public CullSettings
+{
+    public :
+
+
+        Camera();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Camera(const Camera&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Node(osg, Camera);
+
+        /** Set the View that this Camera is part of. */
+        void setView(View* view) { _view = view; }
+
+        /** Get the View that this Camera is part of. */
+        View* getView() { return _view; }
+
+        /** Get the const View that this Camera is part of. */
+        const View* getView() const { return _view; }
+
+
+        /** Set the Stats object used for collect various frame related timing and scene graph stats.*/
+        void setStats(osg::Stats* stats) { _stats = stats; }
+
+        /** Get the Stats object.*/
+        osg::Stats* getStats() { return _stats.get(); }
+
+        /** Get the const Stats object.*/
+        const osg::Stats* getStats() const { return _stats.get(); }
+
+
+        /** Set whether this camera allows events to be generated by the associated graphics window to be associated with this camera.*/
+        void setAllowEventFocus(bool focus) { _allowEventFocus = focus; }
+
+        /** Get whether this camera allows events to be generated by the associated graphics window to be associated with this camera.*/
+        bool getAllowEventFocus() const { return _allowEventFocus; }
+
+
+        /** Set the DsplaySettings object associated with this view.*/
+        void setDisplaySettings(osg::DisplaySettings* ds) { _displaySettings = ds; }
+
+        /** Set the DsplaySettings object associated with this view.*/
+        osg::DisplaySettings* getDisplaySettings() { return _displaySettings.get(); }
+
+        /** Set the DsplaySettings object associated with this view.*/
+        const osg::DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); }
+
+
+        /** Set the clear mask used in glClear(..).
+          * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */
+        inline void setClearMask(GLbitfield mask) { _clearMask = mask; }
+
+        /** Get the clear mask.*/
+        inline GLbitfield getClearMask() const { return _clearMask; }
+
+        /** Set the clear color used in glClearColor(..).
+          * glClearColor is only called if mask & GL_COLOR_BUFFER_BIT is true*/
+        void setClearColor(const osg::Vec4& color) { _clearColor=color; applyMaskAction(CLEAR_COLOR); }
+
+        /** Get the clear color.*/
+        const osg::Vec4& getClearColor() const { return _clearColor; }
+
+        /** Set the clear accum used in glClearAccum(..).
+          * glClearAcumm is only called if mask & GL_ACCUM_BUFFER_BIT is true. */
+        void setClearAccum(const osg::Vec4& color) { _clearAccum=color; }
+
+        /** Get the clear accum value.*/
+        const osg::Vec4& getClearAccum() const { return _clearAccum; }
+
+        /** Set the clear depth used in glClearDepth(..). Defaults to 1.0
+          * glClearDepth is only called if mask & GL_DEPTH_BUFFER_BIT is true. */
+        void setClearDepth(double depth) { _clearDepth=depth; }
+
+        /** Get the clear depth value.*/
+        double getClearDepth() const { return _clearDepth; }
+
+        /** Set the clear stencil value used in glClearStencil(). Defaults to 0;
+          * glClearStencil is only called if mask & GL_STENCIL_BUFFER_BIT is true*/
+        void setClearStencil(int stencil) { _clearStencil=stencil; }
+
+        /** Get the clear stencil value.*/
+        int getClearStencil() const { return _clearStencil; }
+
+
+        /** Set the color mask of the camera to use specified osg::ColorMask. */
+        void setColorMask(osg::ColorMask* colorMask);
+
+
+        /** Set the color mask of the camera to specified values. */
+        void setColorMask(bool red, bool green, bool blue, bool alpha);
+
+        /** Get the const ColorMask. */
+        const ColorMask* getColorMask() const { return _colorMask.get(); }
+
+        /** Get the ColorMask. */
+        ColorMask* getColorMask() { return _colorMask.get(); }
+
+
+        /** Set the viewport of the camera to use specified osg::Viewport. */
+        void setViewport(osg::Viewport* viewport);
+
+        /** Set the viewport of the camera to specified dimensions. */
+        void setViewport(int x,int y,int width,int height);
+
+        /** Get the const viewport. */
+        const Viewport* getViewport() const { return _viewport.get(); }
+
+        /** Get the viewport. */
+        Viewport* getViewport() { return _viewport.get(); }
+
+
+        enum TransformOrder
+        {
+            PRE_MULTIPLY,
+            POST_MULTIPLY
+        };
+
+        /** Set the transformation order for world-to-local and local-to-world transformation.*/
+        void setTransformOrder(TransformOrder order) { _transformOrder = order; }
+
+        /** Get the transformation order.*/
+        TransformOrder getTransformOrder() const { return _transformOrder; }
+
+        enum ProjectionResizePolicy
+        {
+            FIXED, /** Keep the projection matrix fixed, despite window resizes.*/
+            HORIZONTAL, /** Adjust the HORIZOTNAL field of view on window resizes.*/
+            VERTICAL /** Adjust the VERTICAL field of view on window resizes.*/
+        };
+
+        /** Set the policy used to determine if and how the projection matrix should be adjusted on window resizes. */
+        inline void setProjectionResizePolicy(ProjectionResizePolicy policy) { _projectionResizePolicy = policy; }
+
+        /** Get the policy used to determine if and how the projection matrix should be adjusted on window resizes. */
+        inline ProjectionResizePolicy getProjectionResizePolicy() const { return _projectionResizePolicy; }
+
+
+        /** Set the projection matrix. Can be thought of as setting the lens of a camera. */
+        inline void setProjectionMatrix(const osg::Matrixf& matrix) { _projectionMatrix.set(matrix); }
+
+        /** Set the projection matrix. Can be thought of as setting the lens of a camera. */
+        inline void setProjectionMatrix(const osg::Matrixd& matrix) { _projectionMatrix.set(matrix); }
+
+        /** Set to an orthographic projection. See OpenGL glOrtho for documentation further details.*/
+        void setProjectionMatrixAsOrtho(double left, double right,
+                                        double bottom, double top,
+                                        double zNear, double zFar);
+
+        /** Set to a 2D orthographic projection. See OpenGL glOrtho2D documentation for further details.*/
+        void setProjectionMatrixAsOrtho2D(double left, double right,
+                                          double bottom, double top);
+
+        /** Set to a perspective projection. See OpenGL glFrustum documentation for further details.*/
+        void setProjectionMatrixAsFrustum(double left, double right,
+                                          double bottom, double top,
+                                          double zNear, double zFar);
+
+        /** Create a symmetrical perspective projection, See OpenGL gluPerspective documentation for further details.
+          * Aspect ratio is defined as width/height.*/
+        void setProjectionMatrixAsPerspective(double fovy,double aspectRatio,
+                                              double zNear, double zFar);
+
+        /** Get the projection matrix.*/
+        osg::Matrixd& getProjectionMatrix() { return _projectionMatrix; }
+
+        /** Get the const projection matrix.*/
+        const osg::Matrixd& getProjectionMatrix() const { return _projectionMatrix; }
+
+        /** Get the orthographic settings of the orthographic projection matrix.
+          * Returns false if matrix is not an orthographic matrix, where parameter values are undefined.*/
+        bool getProjectionMatrixAsOrtho(double& left, double& right,
+                                        double& bottom, double& top,
+                                        double& zNear, double& zFar) const;
+
+        /** Get the frustum setting of a perspective projection matrix.
+          * Returns false if matrix is not a perspective matrix, where parameter values are undefined.*/
+        bool getProjectionMatrixAsFrustum(double& left, double& right,
+                                          double& bottom, double& top,
+                                          double& zNear, double& zFar) const;
+
+        /** Get the frustum setting of a symmetric perspective projection matrix.
+          * Returns false if matrix is not a perspective matrix, where parameter values are undefined.
+          * Note, if matrix is not a symmetric perspective matrix then the shear will be lost.
+          * Asymmetric matrices occur when stereo, power walls, caves and reality center display are used.
+          * In these configurations one should use the 'getProjectionMatrixAsFrustum' method instead.*/
+        bool getProjectionMatrixAsPerspective(double& fovy,double& aspectRatio,
+                                              double& zNear, double& zFar) const;
+
+
+
+        /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */
+        inline void setViewMatrix(const osg::Matrixf& matrix) { _viewMatrix.set(matrix);  dirtyBound();}
+
+        /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */
+        inline void setViewMatrix(const osg::Matrixd& matrix) { _viewMatrix.set(matrix);  dirtyBound();}
+
+        /** Get the view matrix. */
+        osg::Matrixd& getViewMatrix() { return _viewMatrix; }
+
+        /** Get the const view matrix. */
+        const osg::Matrixd& getViewMatrix() const { return _viewMatrix; }
+
+        /** Set to the position and orientation of view matrix, using the same convention as gluLookAt. */
+        void setViewMatrixAsLookAt(const osg::Vec3d& eye,const osg::Vec3d& center,const osg::Vec3d& up);
+
+        /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */
+        void getViewMatrixAsLookAt(osg::Vec3d& eye,osg::Vec3d& center,osg::Vec3d& up,double lookDistance=1.0) const;
+
+        /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */
+        void getViewMatrixAsLookAt(osg::Vec3f& eye,osg::Vec3f& center,osg::Vec3f& up,float lookDistance=1.0f) const;
+
+        /** Get the inverse view matrix.*/
+        Matrixd getInverseViewMatrix() const;
+
+
+        enum RenderOrder
+        {
+            PRE_RENDER,
+            NESTED_RENDER,
+            POST_RENDER
+        };
+
+        /** Set the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within.
+          * For rendering to a texture, one typically uses PRE_RENDER.
+          * For Head Up Displays, one would typically use POST_RENDER.*/
+        void setRenderOrder(RenderOrder order, int orderNum = 0) { _renderOrder = order; _renderOrderNum = orderNum; }
+
+        /** Get the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within.*/
+        RenderOrder getRenderOrder() const { return _renderOrder; }
+
+        /** Get the rendering order number of this camera relative to any sibling cameras in this subgraph.*/
+        int getRenderOrderNum() const { return _renderOrderNum; }
+
+        /** Return true if this Camera is set up as a render to texture camera, i.e. it has textures assigned to it.*/
+        bool isRenderToTextureCamera() const;
+
+        enum RenderTargetImplementation
+        {
+            FRAME_BUFFER_OBJECT,
+            PIXEL_BUFFER_RTT,
+            PIXEL_BUFFER,
+            FRAME_BUFFER,
+            SEPERATE_WINDOW
+        };
+
+        /** Set the render target.*/
+        void setRenderTargetImplementation(RenderTargetImplementation impl);
+
+        /** Set the render target and fall-back that's used if the former isn't available.*/
+        void setRenderTargetImplementation(RenderTargetImplementation impl, RenderTargetImplementation fallback);
+
+        /** Get the render target.*/
+        RenderTargetImplementation getRenderTargetImplementation() const { return _renderTargetImplementation; }
+
+        /** Get the render target fallback.*/
+        RenderTargetImplementation getRenderTargetFallback() const { return _renderTargetFallback; }
+
+
+        /** Set the draw buffer used at the start of each frame draw.
+          * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/
+        void setDrawBuffer(GLenum buffer) { _drawBuffer = buffer; }
+
+        /** Get the draw buffer used at the start of each frame draw. */
+        GLenum getDrawBuffer() const { return _drawBuffer; }
+
+        /** Set the read buffer for any required copy operations to use.
+          * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/
+        void setReadBuffer(GLenum buffer) { _readBuffer = buffer; }
+
+        /** Get the read buffer for any required copy operations to use. */
+        GLenum getReadBuffer() const { return _readBuffer; }
+
+        enum BufferComponent
+        {
+            DEPTH_BUFFER,
+            STENCIL_BUFFER,
+            PACKED_DEPTH_STENCIL_BUFFER,
+            COLOR_BUFFER,
+            COLOR_BUFFER0,
+            COLOR_BUFFER1 = COLOR_BUFFER0+1,
+            COLOR_BUFFER2 = COLOR_BUFFER0+2,
+            COLOR_BUFFER3 = COLOR_BUFFER0+3,
+            COLOR_BUFFER4 = COLOR_BUFFER0+4,
+            COLOR_BUFFER5 = COLOR_BUFFER0+5,
+            COLOR_BUFFER6 = COLOR_BUFFER0+6,
+            COLOR_BUFFER7 = COLOR_BUFFER0+7,
+            COLOR_BUFFER8 = COLOR_BUFFER0+8,
+            COLOR_BUFFER9 = COLOR_BUFFER0+9,
+            COLOR_BUFFER10 = COLOR_BUFFER0+10,
+            COLOR_BUFFER11 = COLOR_BUFFER0+11,
+            COLOR_BUFFER12 = COLOR_BUFFER0+12,
+            COLOR_BUFFER13 = COLOR_BUFFER0+13,
+            COLOR_BUFFER14 = COLOR_BUFFER0+14,
+            COLOR_BUFFER15 = COLOR_BUFFER0+15
+        };
+
+        /** Attach a buffer with specified OpenGL internal format.*/
+        void attach(BufferComponent buffer, GLenum internalFormat);
+
+        /** Attach a Texture to specified buffer component.
+          * The level parameter controls the mip map level of the texture that is attached.
+          * The face parameter controls the face of texture cube map or z level of 3d texture.
+          * The mipMapGeneration flag controls whether mipmap generation should be done for texture.*/
+        void attach(BufferComponent buffer, osg::Texture* texture, unsigned int level = 0, unsigned int face=0, bool mipMapGeneration=false,
+            unsigned int multisampleSamples = 0,
+            unsigned int multisampleColorSamples = 0);
+
+        /** Attach a Image to specified buffer component.*/
+        void attach(BufferComponent buffer, osg::Image* image,
+            unsigned int multisampleSamples = 0,
+            unsigned int multisampleColorSamples = 0);
+
+        /** Detach specified buffer component.*/
+        void detach(BufferComponent buffer);
+
+        struct Attachment
+        {
+            Attachment():
+                _internalFormat(GL_NONE),
+                _level(0),
+                _face(0),
+                _mipMapGeneration(false),
+                _multisampleSamples(0),
+                _multisampleColorSamples(0) {}
+
+            int width() const
+            {
+                if (_texture.valid()) return _texture->getTextureWidth();
+                if (_image.valid()) return _image->s();
+                return 0;
+            };
+
+            int height() const
+            {
+                if (_texture.valid()) return _texture->getTextureHeight();
+                if (_image.valid()) return _image->t();
+                return 0;
+            };
+
+            int depth() const
+            {
+                if (_texture.valid()) return _texture->getTextureDepth();
+                if (_image.valid()) return _image->r();
+                return 0;
+            };
+
+            GLenum              _internalFormat;
+            ref_ptr<Image>      _image;
+            ref_ptr<Texture>    _texture;
+            unsigned int        _level;
+            unsigned int        _face;
+            bool                _mipMapGeneration;
+            unsigned int        _multisampleSamples;
+            unsigned int        _multisampleColorSamples;
+        };
+
+        typedef std::map< BufferComponent, Attachment> BufferAttachmentMap;
+
+        /** Get the BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/
+        BufferAttachmentMap& getBufferAttachmentMap() { return _bufferAttachmentMap; }
+
+        /** Get the const BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/
+        const BufferAttachmentMap& getBufferAttachmentMap() const { return _bufferAttachmentMap; }
+
+
+        /** Create a operation thread for this camera.*/
+        void createCameraThread();
+
+        /** Assign a operation thread to the camera.*/
+        void setCameraThread(OperationThread* gt);
+
+        /** Get the operation thread assigned to this camera.*/
+        OperationThread* getCameraThread() { return _cameraThread.get(); }
+
+        /** Get the const operation thread assigned to this camera.*/
+        const OperationThread* getCameraThread() const { return _cameraThread.get(); }
+
+
+
+        /** Set the GraphicsContext that provides the mechansim for managing the OpenGL graphics context associated with this camera.*/
+        void setGraphicsContext(GraphicsContext* context);
+
+        /** Get the GraphicsContext.*/
+        GraphicsContext* getGraphicsContext() { return _graphicsContext.get(); }
+
+        /** Get the const GraphicsContext.*/
+        const GraphicsContext* getGraphicsContext() const { return _graphicsContext.get(); }
+
+
+        /** Set the Rendering object that is used to implement rendering of the subgraph.*/
+        void setRenderer(osg::GraphicsOperation* rc) { _renderer = rc; }
+
+        /** Get the Rendering object that is used to implement rendering of the subgraph.*/
+        osg::GraphicsOperation* getRenderer() { return _renderer.get(); }
+
+        /** Get the const Rendering object that is used to implement rendering of the subgraph.*/
+        const osg::GraphicsOperation* getRenderer() const { return _renderer.get(); }
+
+
+        /** Set the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/
+        void setRenderingCache(osg::Object* rc) { _renderingCache = rc; }
+
+        /** Get the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/
+        osg::Object* getRenderingCache() { return _renderingCache.get(); }
+
+        /** Get the const Rendering cache that is used for cached objects associated with rendering of subgraphs.*/
+        const osg::Object* getRenderingCache() const { return _renderingCache.get(); }
+
+
+        /** Draw callback for custom operations.*/
+        struct OSG_EXPORT DrawCallback : virtual public Object
+        {
+            DrawCallback() {}
+
+            DrawCallback(const DrawCallback&,const CopyOp&) {}
+
+            META_Object(osg, DrawCallback);
+
+            /** Functor method called by rendering thread. Users will typically override this method to carry tasks such as screen capture.*/
+            virtual void operator () (osg::RenderInfo& renderInfo) const;
+
+            /** Functor method, provided for backwards compatibility, called by operator() (osg::RenderInfo& renderInfo) method.*/
+            virtual void operator () (const osg::Camera& /*camera*/) const {}
+        };
+
+        /** Set the initial draw callback for custom operations to be done before the drawing of the camera's subgraph and pre render stages.*/
+        void setInitialDrawCallback(DrawCallback* cb) { _initialDrawCallback = cb; }
+
+        /** Get the initial draw callback.*/
+        DrawCallback* getInitialDrawCallback() { return _initialDrawCallback.get(); }
+
+        /** Get the const initial draw callback.*/
+        const DrawCallback* getInitialDrawCallback() const { return _initialDrawCallback.get(); }
+
+
+        /** Set the pre draw callback for custom operations to be done before the drawing of the camera's subgraph but after any pre render stages have been completed.*/
+        void setPreDrawCallback(DrawCallback* cb) { _preDrawCallback = cb; }
+
+        /** Get the pre draw callback.*/
+        DrawCallback* getPreDrawCallback() { return _preDrawCallback.get(); }
+
+        /** Get the const pre draw callback.*/
+        const DrawCallback* getPreDrawCallback() const { return _preDrawCallback.get(); }
+
+
+        /** Set the post draw callback for custom operations to be done after the drawing of the camera's subgraph but before the any post render stages have been completed.*/
+        void setPostDrawCallback(DrawCallback* cb) { _postDrawCallback = cb; }
+
+        /** Get the post draw callback.*/
+        DrawCallback* getPostDrawCallback() { return _postDrawCallback.get(); }
+
+        /** Get the const post draw callback.*/
+        const DrawCallback* getPostDrawCallback() const { return _postDrawCallback.get(); }
+
+
+        /** Set the final draw callback for custom operations to be done after the drawing of the camera's subgraph and all of the post render stages has been completed.*/
+        void setFinalDrawCallback(DrawCallback* cb) { _finalDrawCallback = cb; }
+
+        /** Get the final draw callback.*/
+        DrawCallback* getFinalDrawCallback() { return _finalDrawCallback.get(); }
+
+        /** Get the const final draw callback.*/
+        const DrawCallback* getFinalDrawCallback() const { return _finalDrawCallback.get(); }
+
+
+        OpenThreads::Mutex* getDataChangeMutex() const { return &_dataChangeMutex; }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** If State is non-zero, this function releases any associated OpenGL objects for
+           * the specified graphics context. Otherwise, releases OpenGL objexts
+           * for all graphics contexts. */
+        virtual void releaseGLObjects(osg::State* = 0) const;
+
+    public:
+
+        /** Transform method that must be defined to provide generic interface for scene graph traversals.*/
+        virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor*) const;
+
+        /** Transform method that must be defined to provide generic interface for scene graph traversals.*/
+        virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor*) const;
+
+        /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/
+        virtual void inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask);
+
+    protected :
+
+        virtual ~Camera();
+
+        mutable OpenThreads::Mutex          _dataChangeMutex;
+
+
+        View*                               _view;
+
+        osg::ref_ptr<osg::Stats>            _stats;
+
+        bool                                _allowEventFocus;
+
+        osg::ref_ptr<osg::DisplaySettings>  _displaySettings;
+
+        GLbitfield                          _clearMask;
+        osg::Vec4                           _clearColor;
+        osg::Vec4                           _clearAccum;
+        double                              _clearDepth;
+        int                                 _clearStencil;
+
+        ref_ptr<ColorMask>                  _colorMask;
+        ref_ptr<Viewport>                   _viewport;
+
+        TransformOrder                      _transformOrder;
+        ProjectionResizePolicy              _projectionResizePolicy;
+
+        Matrixd                             _projectionMatrix;
+        Matrixd                             _viewMatrix;
+
+        RenderOrder                         _renderOrder;
+        int                                 _renderOrderNum;
+
+        GLenum                              _drawBuffer;
+        GLenum                              _readBuffer;
+
+        RenderTargetImplementation          _renderTargetImplementation;
+        RenderTargetImplementation          _renderTargetFallback;
+        BufferAttachmentMap                 _bufferAttachmentMap;
+
+        ref_ptr<OperationThread>            _cameraThread;
+
+        ref_ptr<GraphicsContext>            _graphicsContext;
+
+        ref_ptr<GraphicsOperation>          _renderer;
+        ref_ptr<Object>                     _renderingCache;
+
+        ref_ptr<DrawCallback>               _initialDrawCallback;
+        ref_ptr<DrawCallback>               _preDrawCallback;
+        ref_ptr<DrawCallback>               _postDrawCallback;
+        ref_ptr<DrawCallback>               _finalDrawCallback;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Billboard
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Billboard (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Billboard (revision 7648)
@@ -0,0 +1,132 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_BILLBOARD
+#define OSG_BILLBOARD 1
+
+#include <osg/Matrix>
+#include <osg/Geode>
+
+namespace osg {
+
+/** Billboard is a derived form of Geode that orients its osg::Drawable
+  * children to face the eye point. Typical uses include trees and
+  * particle explosions,
+*/
+class OSG_EXPORT Billboard : public Geode
+{
+    public:
+
+        enum Mode {
+            POINT_ROT_EYE,
+            POINT_ROT_WORLD,
+            AXIAL_ROT
+        };
+
+        Billboard();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Billboard(const Billboard&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Node(osg, Billboard);
+
+        /** Set the billboard rotation mode. */
+        void setMode(Mode mode);
+        /** Get the billboard rotation mode. */
+        inline Mode getMode() const { return _mode; }
+
+        /** Set the rotation axis for the billboard's child Drawables.
+          * Only utilized when mode==AXIAL_ROT. */
+        void setAxis(const Vec3& axis);
+        /** Get the rotation axis. */
+        inline const Vec3& getAxis() const { return _axis; }
+
+        /** This normal defines child Drawables' front face direction when unrotated. */
+        void setNormal(const Vec3& normal);
+        /** Get the front face direction normal. */
+        inline const Vec3& getNormal() const { return _normal; }
+
+
+        /** Set the specified child Drawable's position. */
+        inline void setPosition(unsigned int i,const Vec3& pos)      { _positionList[i] = pos; }
+        /** Get the specified child Drawable's position. */
+        inline const Vec3& getPosition(unsigned int i) const         { return _positionList[i]; }
+
+        /** Type definition for pivot point position list. */
+        typedef std::vector<Vec3> PositionList;
+        
+        /** Set the list of pivot point positions. */
+        inline void setPositionList(PositionList& pl)       { _positionList=pl; }
+
+        /** Get the list of pivot point positions. */
+        inline PositionList& getPositionList()              { return _positionList; }
+        
+        /** Get a const list of pivot point positions. */
+        inline const PositionList& getPositionList() const  { return _positionList; }
+
+        /** Add a Drawable with a default position of Vec3(0,0,0).
+          * Call the base-class Geode::addDrawble() to add the given Drawable
+          * gset as a child. If Geode::addDrawable() returns true, add the
+          * default position to the pivot point position list and return true.
+          * Otherwise, return false. */
+        virtual bool addDrawable( Drawable *gset );
+
+        /** Add a Drawable with a specified position.
+          * Call the base-class Geode::addDrawble() to add the given Drawable
+          * gset as a child. If Geode::addDrawable() returns true, add the
+          * given position pos to the pivot point position list and return true.
+          * Otherwise, return false. */
+        virtual bool addDrawable(Drawable *gset,const Vec3& pos);
+
+        /** Remove a Drawable and its associated position.
+          * If gset is a child, remove it, decrement its reference count,
+          * remove its pivot point position. and return true.
+          * Otherwise, return false. */
+        virtual bool removeDrawable( Drawable *gset );
+                
+
+        bool computeMatrix(Matrix& modelview, const Vec3& eye_local, const Vec3& pos_local) const;
+
+        virtual BoundingSphere computeBound() const;
+
+    protected:
+
+        virtual ~Billboard();
+
+        enum AxisAligned
+        {
+            AXIAL_ROT_X_AXIS=AXIAL_ROT+1,
+            AXIAL_ROT_Y_AXIS,
+            AXIAL_ROT_Z_AXIS,
+            POINT_ROT_WORLD_Z_AXIS,
+            CACHE_DIRTY
+        };
+
+
+        Mode                                _mode;
+        Vec3                                _axis;
+        Vec3                                _normal;
+        Matrix                              _rotateNormalToZAxis;
+        PositionList                        _positionList;
+        
+        // used internally as cache of which what _axis is aligned to help
+        // decide which method of rotation to use.
+        int                                 _cachedMode;
+        Vec3                                _side;
+        void updateCache();
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BlendEquation
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BlendEquation (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BlendEquation (revision 7648)
@@ -0,0 +1,152 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_BLENDEQUATION
+#define OSG_BLENDEQUATION 1
+
+#include <osg/StateAttribute>
+
+#ifndef GL_VERSION_1_2
+/* Logic Ops */
+#define GL_MIN                                  0x8007
+#define GL_MAX                                  0x8008
+#define GL_FUNC_ADD                             0x8006
+#define GL_FUNC_SUBTRACT                        0x800A
+#define GL_FUNC_REVERSE_SUBTRACT                0x800B
+#endif
+
+#ifndef GL_LOGIC_OP
+#define GL_LOGIC_OP                             0x0BF1
+#endif
+
+#ifndef GL_ALPHA_MIN_SGIX
+#define GL_ALPHA_MIN_SGIX                       0x8320
+#define GL_ALPHA_MAX_SGIX                       0x8321
+#endif
+
+namespace osg {
+
+/** Encapsulates OpenGL BlendEquation state. */
+class OSG_EXPORT BlendEquation : public StateAttribute
+{
+    public :
+
+        enum Equation {
+            RGBA_MIN                        = GL_MIN,
+            RGBA_MAX                        = GL_MAX,
+            ALPHA_MIN                       = GL_ALPHA_MIN_SGIX,
+            ALPHA_MAX                       = GL_ALPHA_MAX_SGIX,
+            LOGIC_OP                        = GL_LOGIC_OP,
+            FUNC_ADD                        = GL_FUNC_ADD,
+            FUNC_SUBTRACT                   = GL_FUNC_SUBTRACT,
+            FUNC_REVERSE_SUBTRACT           = GL_FUNC_REVERSE_SUBTRACT
+        };
+
+        BlendEquation();
+        
+        BlendEquation(Equation equation);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        BlendEquation(const BlendEquation& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(trans,copyop),
+            _equation(trans._equation){}
+
+        META_StateAttribute(osg, BlendEquation,BLENDEQUATION);
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // Check for equal types, then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macros below.
+            COMPARE_StateAttribute_Types(BlendEquation,sa)
+
+            // Compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_equation)
+
+            return 0; // Passed all the above comparison macros, so must be equal.
+        }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_BLEND);
+            return true;
+        }
+
+
+        inline void setEquation(Equation equation)
+        {
+            _equation = equation;
+        }
+
+        inline Equation getEquation() const { return _equation; }
+        
+        virtual void apply(State& state) const;
+        /** Encapsulates queries of extension availability, obtains extension
+          * function pointers, and provides convenience wrappers for
+          * calling extension functions. */        
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setBlendEquationSupported(bool flag) { _isBlendEquationSupported=flag; }
+                bool isBlendEquationSupported() const { return _isBlendEquationSupported; }
+                bool isSGIXMinMaxSupported() const { return _isSGIXMinMaxSupported; }
+                bool isLogicOpSupported() const { return _isLogicOpSupported; }
+                
+                void glBlendEquation(GLenum mode) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                typedef void (APIENTRY * GLBlendEquationProc) (GLenum mode);
+
+                bool                _isBlendEquationSupported;
+                bool                _isSGIXMinMaxSupported;
+                bool                _isLogicOpSupported;
+                
+                GLBlendEquationProc _glBlendEquation;
+
+        };
+        
+        /** Returns the Extensions object for the given context.
+          * If createIfNotInitalized is true and the Extensions object doesn't
+          * exist, getExtensions() creates it on the given context.
+          * Returns NULL if createIfNotInitalized is false and the Extensions
+          * object doesn't exist. */
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** setExtensions() allows users to override the extensions across graphics contexts.
+          * Typically used when you have different extensions supported across graphics pipes,
+          * but need to ensure that they all use the same low common denominator extensions. */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+    protected :
+
+        virtual ~BlendEquation();
+
+
+        Equation _equation;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShadowVolumeOccluder
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShadowVolumeOccluder (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShadowVolumeOccluder (revision 7648)
@@ -0,0 +1,172 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_SHADOWVOLUMEOCCLUDER
+#define OSG_SHADOWVOLUMEOCCLUDER 1
+
+#include <osg/Polytope>
+#include <osg/ConvexPlanarOccluder>
+#include <osg/Node>
+
+namespace osg {
+
+class CullStack;
+
+/** ShadowVolumeOccluder is a helper class for implementing shadow occlusion culling. */
+class OSG_EXPORT ShadowVolumeOccluder
+{
+
+    public:
+    
+    
+        typedef std::vector<Polytope> HoleList;
+
+        ShadowVolumeOccluder(const ShadowVolumeOccluder& svo):
+            _volume(svo._volume),
+            _nodePath(svo._nodePath),
+            _projectionMatrix(svo._projectionMatrix),
+            _occluderVolume(svo._occluderVolume),
+            _holeList(svo._holeList) {}
+
+        ShadowVolumeOccluder():
+            _volume(0.0f) {}
+
+
+        bool operator < (const ShadowVolumeOccluder& svo) const { return getVolume()>svo.getVolume(); } // not greater volume first. 
+
+        /** compute the shadow volume occluder. */
+        bool computeOccluder(const NodePath& nodePath,const ConvexPlanarOccluder& occluder,CullStack& cullStack,bool createDrawables=false);
+        
+
+        inline void disableResultMasks();
+        
+        inline void pushCurrentMask();
+        inline void popCurrentMask();
+        
+        
+        /** return true if the matrix passed in matches the projection matrix that this ShadowVolumeOccluder is
+          * associated with.*/
+        bool matchProjectionMatrix(const osg::Matrix& matrix) const
+        {
+            if (_projectionMatrix.valid()) return matrix==*_projectionMatrix;
+            else return false;
+        }
+        
+
+        /** Set the NodePath which describes which node in the scene graph
+          * that this occluder is attached to. */
+        inline void setNodePath(NodePath& nodePath) { _nodePath = nodePath; }
+        inline NodePath& getNodePath() { return _nodePath; }
+        inline const NodePath& getNodePath() const { return _nodePath; }
+
+
+        /** get the volume of the occluder minus its holes, in eye coords, the volume is normalized by dividing by 
+          * the volume of the view frustum in eye coords.*/
+        float getVolume() const { return _volume; }
+        
+        /** return the occluder polytope.*/
+        Polytope& getOccluder() { return _occluderVolume; }
+        
+        /** return the const occluder polytope.*/
+        const Polytope& getOccluder() const { return _occluderVolume; }
+        
+        /** return the list of holes.*/
+        HoleList& getHoleList() { return _holeList; }
+        
+        /** return the const list of holes.*/
+        const HoleList& getHoleList() const { return _holeList; }
+        
+
+        /** return true if the specified vertex list is contained entirely
+          * within this shadow occluder volume.*/
+        bool contains(const std::vector<Vec3>& vertices);
+
+        /** return true if the specified bounding sphere is contained entirely
+          * within this shadow occluder volume.*/
+        bool contains(const BoundingSphere& bound);
+        
+        /** return true if the specified bounding box is contained entirely
+          * within this shadow occluder volume.*/
+        bool contains(const BoundingBox& bound);
+
+        inline void transformProvidingInverse(const osg::Matrix& matrix)
+        {
+            _occluderVolume.transformProvidingInverse(matrix);
+            for(HoleList::iterator itr=_holeList.begin();
+                itr!=_holeList.end();
+                ++itr)
+            {
+                itr->transformProvidingInverse(matrix);
+            }
+        }
+        
+
+    protected:
+
+        float                       _volume;
+        NodePath                    _nodePath;
+        ref_ptr<const RefMatrix>    _projectionMatrix;
+        Polytope                    _occluderVolume;
+        HoleList                    _holeList;
+};
+
+
+/** A list of ShadowVolumeOccluder, used by CollectOccluderVisitor and CullVistor's.*/
+typedef std::vector<ShadowVolumeOccluder> ShadowVolumeOccluderList;
+
+
+inline void ShadowVolumeOccluder::disableResultMasks()
+{
+    //std::cout<<"ShadowVolumeOccluder::disableResultMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<"  "<<_occluderVolume.getCurrentMask()<<std::endl;
+    _occluderVolume.setResultMask(0);
+    for(HoleList::iterator itr=_holeList.begin();
+        itr!=_holeList.end();
+        ++itr)
+    {
+        itr->setResultMask(0);
+    }
+}
+
+inline void ShadowVolumeOccluder::pushCurrentMask()
+{
+    //std::cout<<"ShadowVolumeOccluder::pushCurrentMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<"  "<<_occluderVolume.getCurrentMask()<<std::endl;
+    _occluderVolume.pushCurrentMask();
+    if (!_holeList.empty())
+    {
+        for(HoleList::iterator itr=_holeList.begin();
+            itr!=_holeList.end();
+            ++itr)
+        {
+            itr->pushCurrentMask();
+        }
+    }
+}
+
+inline void ShadowVolumeOccluder::popCurrentMask()
+{
+    _occluderVolume.popCurrentMask();
+    if (!_holeList.empty())
+    {
+        for(HoleList::iterator itr=_holeList.begin();
+            itr!=_holeList.end();
+            ++itr)
+        {
+            itr->popCurrentMask();
+        }
+    }
+    //std::cout<<"ShadowVolumeOccluder::popCurrentMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<"  "<<_occluderVolume.getCurrentMask()<<std::endl;
+}
+
+}    // end of namespace
+
+#endif 
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageStream
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageStream (revision 8990)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageStream (revision 8990)
@@ -0,0 +1,102 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_IMAGESTREAM
+#define OSG_IMAGESTREAM 1
+
+#include <osg/Image>
+
+namespace osg {
+
+/**
+  * Image Stream class.
+*/
+class OSG_EXPORT ImageStream : public Image
+{
+    public:
+        ImageStream();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        ImageStream(const ImageStream& image,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        virtual Object* cloneType() const { return new ImageStream(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new ImageStream(*this,copyop); }
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const ImageStream*>(obj)!=0; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "ImageStream"; }
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const Image& rhs) const;
+
+        enum StreamStatus
+        {
+            INVALID,
+            PLAYING,
+            PAUSED,
+            REWINDING
+        };
+        
+        virtual void seek(double /*time*/) {}
+
+        virtual void play() { _status=PLAYING; }
+
+        virtual void pause() { _status=PAUSED; }
+
+        virtual void rewind() { _status=REWINDING; }
+        
+        virtual void quit(bool /*waitForThreadToExit*/ = true) {}
+
+        StreamStatus getStatus() { return _status; }
+        
+
+        enum LoopingMode
+        {
+            NO_LOOPING,
+            LOOPING
+        };
+        
+        void setLoopingMode(LoopingMode mode)
+        {
+            if (_loopingMode == mode) return;
+            
+            _loopingMode = mode;
+            applyLoopingMode();
+        }
+        
+        LoopingMode getLoopingMode() const { return _loopingMode; }
+
+
+        virtual double getLength() const { return 0.0; }
+        
+        virtual void setReferenceTime(double) {}
+        virtual double getReferenceTime() const { return 0.0; }
+                
+        virtual void setTimeMultiplier(double) {}
+        virtual double getTimeMultiplier() const { return 0.0; }
+        
+        virtual void setVolume(float) {}
+        virtual float getVolume() const { return 0.0f; }
+        
+
+    protected:
+        virtual void applyLoopingMode() {}
+
+        virtual ~ImageStream() {}
+
+        StreamStatus    _status;
+        LoopingMode     _loopingMode;
+};
+
+} // namespace
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture (revision 8655)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture (revision 8655)
@@ -0,0 +1,929 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXTURE
+#define OSG_TEXTURE 1
+
+#include <osg/GL>
+#include <osg/Image>
+#include <osg/StateAttribute>
+#include <osg/GraphicsContext>
+#include <osg/ref_ptr>
+#include <osg/Vec4>
+#include <osg/Vec4d>
+#include <osg/buffered_value>
+
+#include <list>
+#include <map>
+
+// If not defined by gl.h use the definition found in:
+// http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_filter_anisotropic.txt
+#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
+    #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
+#endif
+
+#ifndef GL_ARB_texture_compression
+    #define GL_COMPRESSED_ALPHA_ARB                 0x84E9
+    #define GL_COMPRESSED_LUMINANCE_ARB             0x84EA
+    #define GL_COMPRESSED_LUMINANCE_ALPHA_ARB       0x84EB
+    #define GL_COMPRESSED_INTENSITY_ARB             0x84EC
+    #define GL_COMPRESSED_RGB_ARB                   0x84ED
+    #define GL_COMPRESSED_RGBA_ARB                  0x84EE
+    #define GL_TEXTURE_COMPRESSION_HINT_ARB         0x84EF
+    #define GL_TEXTURE_COMPRESSED_ARB               0x86A1
+    #define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB   0x86A2
+    #define GL_COMPRESSED_TEXTURE_FORMATS_ARB       0x86A3
+#endif
+
+#ifndef GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB
+    #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB    0x86A0
+#endif
+
+#ifndef GL_EXT_texture_compression_s3tc
+    #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT         0x83F0
+    #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT        0x83F1
+    #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT        0x83F2
+    #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT        0x83F3
+#endif
+
+#ifndef GL_ARB_INTERNAL_TEXTURE_FORMAT
+    #define GL_RGBA32F_ARB                           0x8814
+    #define GL_RGB32F_ARB                            0x8815
+    #define GL_ALPHA32F_ARB                          0x8816
+    #define GL_INTENSITY32F_ARB                      0x8817
+    #define GL_LUMINANCE32F_ARB                      0x8818
+    #define GL_LUMINANCE_ALPHA32F_ARB                0x8819
+    #define GL_RGBA16F_ARB                           0x881A
+    #define GL_RGB16F_ARB                            0x881B
+    #define GL_ALPHA16F_ARB                          0x881C
+    #define GL_INTENSITY16F_ARB                      0x881D
+    #define GL_LUMINANCE16F_ARB                      0x881E
+    #define GL_LUMINANCE_ALPHA16F_ARB                0x881F
+#endif
+
+#ifndef GL_ARB_PIXEL_DATA
+    #define GL_HALF_FLOAT_ARB                        0x140B
+#endif
+
+#ifndef GL_NV_texture_shader
+    #define GL_HILO_NV                              0x86F4
+    #define GL_DSDT_NV                              0x86F5
+    #define GL_DSDT_MAG_NV                          0x86F6
+    #define GL_DSDT_MAG_VIB_NV                      0x86F7
+    #define GL_HILO16_NV                            0x86F8
+    #define GL_SIGNED_HILO_NV                       0x86F9
+    #define GL_SIGNED_HILO16_NV                     0x86FA
+    #define GL_SIGNED_RGBA_NV                       0x86FB
+    #define GL_SIGNED_RGBA8_NV                      0x86FC
+    #define GL_SIGNED_RGB_NV                        0x86FE
+    #define GL_SIGNED_RGB8_NV                       0x86FF
+    #define GL_SIGNED_LUMINANCE_NV                  0x8701
+    #define GL_SIGNED_LUMINANCE8_NV                 0x8702
+    #define GL_SIGNED_LUMINANCE_ALPHA_NV            0x8703
+    #define GL_SIGNED_LUMINANCE8_ALPHA8_NV          0x8704
+    #define GL_SIGNED_ALPHA_NV                      0x8705
+    #define GL_SIGNED_ALPHA8_NV                     0x8706
+    #define GL_SIGNED_INTENSITY_NV                  0x8707
+    #define GL_SIGNED_INTENSITY8_NV                 0x8708
+    #define GL_DSDT8_NV                             0x8709
+    #define GL_DSDT8_MAG8_NV                        0x870A
+    #define GL_DSDT8_MAG8_INTENSITY8_NV             0x870B
+    #define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV         0x870C
+    #define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV       0x870D
+#endif
+
+#ifndef GL_NV_float_buffer
+    #define GL_FLOAT_R_NV                           0x8880
+    #define GL_FLOAT_RG_NV                          0x8881
+    #define GL_FLOAT_RGB_NV                         0x8882
+    #define GL_FLOAT_RGBA_NV                        0x8883
+    #define GL_FLOAT_R16_NV                         0x8884
+    #define GL_FLOAT_R32_NV                         0x8885
+    #define GL_FLOAT_RG16_NV                        0x8886
+    #define GL_FLOAT_RG32_NV                        0x8887
+    #define GL_FLOAT_RGB16_NV                       0x8888
+    #define GL_FLOAT_RGB32_NV                       0x8889
+    #define GL_FLOAT_RGBA16_NV                      0x888A
+    #define GL_FLOAT_RGBA32_NV                      0x888B
+#endif
+
+#ifndef GL_NV_half_float
+    #define GL_HALF_FLOAT_NV                        0x140B
+#endif
+
+#ifndef GL_ATI_texture_float
+    #define GL_RGBA_FLOAT32_ATI                     0x8814
+    #define GL_RGB_FLOAT32_ATI                      0x8815
+    #define GL_ALPHA_FLOAT32_ATI                    0x8816
+    #define GL_INTENSITY_FLOAT32_ATI                0x8817
+    #define GL_LUMINANCE_FLOAT32_ATI                0x8818
+    #define GL_LUMINANCE_ALPHA_FLOAT32_ATI          0x8819
+    #define GL_RGBA_FLOAT16_ATI                     0x881A
+    #define GL_RGB_FLOAT16_ATI                      0x881B
+    #define GL_ALPHA_FLOAT16_ATI                    0x881C
+    #define GL_INTENSITY_FLOAT16_ATI                0x881D
+    #define GL_LUMINANCE_FLOAT16_ATI                0x881E
+    #define GL_LUMINANCE_ALPHA_FLOAT16_ATI          0x881F
+#endif
+
+#ifndef GL_MIRRORED_REPEAT_IBM
+    #define GL_MIRRORED_REPEAT_IBM            0x8370
+#endif
+
+#ifndef GL_CLAMP_TO_EDGE
+    #define GL_CLAMP_TO_EDGE                  0x812F
+#endif
+
+#ifndef GL_CLAMP_TO_BORDER_ARB
+    #define GL_CLAMP_TO_BORDER_ARB            0x812D
+#endif
+
+#ifndef GL_GENERATE_MIPMAP_SGIS
+    #define GL_GENERATE_MIPMAP_SGIS           0x8191
+    #define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192
+#endif
+
+#ifndef GL_TEXTURE_3D
+    #define GL_TEXTURE_3D                     0x806F
+#endif
+
+#ifndef GL_TEXTURE_2D_ARRAY_EXT
+    #define GL_TEXTURE_2D_ARRAY_EXT           0x8C1A
+    #define GL_TEXTURE_2D_ARRAY_EXT                        0x8C1A
+    #define GL_PROXY_TEXTURE_2D_ARRAY_EXT                  0x8C1B
+    #define GL_TEXTURE_BINDING_2D_ARRAY_EXT                0x8C1D
+    #define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT                0x88FF
+    #define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT            0x884E
+    #define GL_SAMPLER_2D_ARRAY_EXT                        0x8DC1
+    #define GL_SAMPLER_2D_ARRAY_SHADOW_EXT                 0x8DC4
+    #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT    0x8CD4
+#endif
+
+#ifndef GL_TEXTURE_BINDING_3D
+    #define GL_TEXTURE_BINDING_3D             0x806A
+#endif
+
+#ifndef GL_DEPTH_TEXTURE_MODE_ARB
+    #define GL_DEPTH_TEXTURE_MODE_ARB         0x884B
+#endif
+
+#ifndef GL_TEXTURE_COMPARE_MODE_ARB
+    #define GL_TEXTURE_COMPARE_MODE_ARB       0x884C
+#endif
+#ifndef GL_TEXTURE_COMPARE_FUNC_ARB
+    #define GL_TEXTURE_COMPARE_FUNC_ARB       0x884D
+#endif
+#ifndef GL_COMPARE_R_TO_TEXTURE_ARB
+    #define GL_COMPARE_R_TO_TEXTURE_ARB       0x884E
+#endif
+
+#ifndef TEXTURE_COMPARE_FAIL_VALUE_ARB
+    #define TEXTURE_COMPARE_FAIL_VALUE_ARB    0x80BF
+#endif
+
+#if !defined( GL_MAX_TEXTURE_UNITS )
+    #define GL_MAX_TEXTURE_UNITS              0x84E2
+#endif
+
+#ifndef  GL_TEXTURE_DEPTH
+    #define GL_TEXTURE_DEPTH                  0x8071
+#endif
+
+// Integer teture extension as in http://www.opengl.org/registry/specs/EXT/texture_integer.txt
+#ifndef GL_EXT_texture_integer
+    #define GL_RGBA32UI_EXT                                    0x8D70
+    #define GL_RGB32UI_EXT                                     0x8D71
+    #define GL_ALPHA32UI_EXT                                   0x8D72
+    #define GL_INTENSITY32UI_EXT                               0x8D73
+    #define GL_LUMINANCE32UI_EXT                               0x8D74
+    #define GL_LUMINANCE_ALPHA32UI_EXT                         0x8D75
+
+    #define GL_RGBA16UI_EXT                                    0x8D76
+    #define GL_RGB16UI_EXT                                     0x8D77
+    #define GL_ALPHA16UI_EXT                                   0x8D78
+    #define GL_INTENSITY16UI_EXT                               0x8D79
+    #define GL_LUMINANCE16UI_EXT                               0x8D7A
+    #define GL_LUMINANCE_ALPHA16UI_EXT                         0x8D7B
+
+    #define GL_RGBA8UI_EXT                                     0x8D7C
+    #define GL_RGB8UI_EXT                                      0x8D7D
+    #define GL_ALPHA8UI_EXT                                    0x8D7E
+    #define GL_INTENSITY8UI_EXT                                0x8D7F
+    #define GL_LUMINANCE8UI_EXT                                0x8D80
+    #define GL_LUMINANCE_ALPHA8UI_EXT                          0x8D81
+
+    #define GL_RGBA32I_EXT                                     0x8D82
+    #define GL_RGB32I_EXT                                      0x8D83
+    #define GL_ALPHA32I_EXT                                    0x8D84
+    #define GL_INTENSITY32I_EXT                                0x8D85
+    #define GL_LUMINANCE32I_EXT                                0x8D86
+    #define GL_LUMINANCE_ALPHA32I_EXT                          0x8D87
+
+    #define GL_RGBA16I_EXT                                     0x8D88
+    #define GL_RGB16I_EXT                                      0x8D89
+    #define GL_ALPHA16I_EXT                                    0x8D8A
+    #define GL_INTENSITY16I_EXT                                0x8D8B
+    #define GL_LUMINANCE16I_EXT                                0x8D8C
+    #define GL_LUMINANCE_ALPHA16I_EXT                          0x8D8D
+
+    #define GL_RGBA8I_EXT                                      0x8D8E
+    #define GL_RGB8I_EXT                                       0x8D8F
+    #define GL_ALPHA8I_EXT                                     0x8D90
+    #define GL_INTENSITY8I_EXT                                 0x8D91
+    #define GL_LUMINANCE8I_EXT                                 0x8D92
+    #define GL_LUMINANCE_ALPHA8I_EXT                           0x8D93
+
+    #define GL_RED_INTEGER_EXT                                 0x8D94
+    #define GL_GREEN_INTEGER_EXT                               0x8D95
+    #define GL_BLUE_INTEGER_EXT                                0x8D96
+    #define GL_ALPHA_INTEGER_EXT                               0x8D97
+    #define GL_RGB_INTEGER_EXT                                 0x8D98
+    #define GL_RGBA_INTEGER_EXT                                0x8D99
+    #define GL_BGR_INTEGER_EXT                                 0x8D9A
+    #define GL_BGRA_INTEGER_EXT                                0x8D9B
+    #define GL_LUMINANCE_INTEGER_EXT                           0x8D9C
+    #define GL_LUMINANCE_ALPHA_INTEGER_EXT                     0x8D9D
+
+    #define GL_RGBA_INTEGER_MODE_EXT                           0x8D9E
+#endif
+
+namespace osg {
+
+
+/** Texture pure virtual base class that encapsulates OpenGl texture
+  * functionality common to the various types of OSG textures.
+*/
+class OSG_EXPORT Texture : public osg::StateAttribute
+{
+
+    public :
+    
+        static unsigned int s_numberTextureReusedLastInLastFrame;
+        static unsigned int s_numberNewTextureInLastFrame;
+        static unsigned int s_numberDeletedTextureInLastFrame;
+
+        Texture();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Texture(const Texture& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        virtual osg::Object* cloneType() const = 0;
+        virtual osg::Object* clone(const CopyOp& copyop) const = 0;
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const Texture *>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Texture"; }
+
+        /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/
+        virtual Texture* asTexture() { return this; }
+        
+        /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/
+        virtual const Texture* asTexture() const { return this; }
+
+        virtual Type getType() const { return TEXTURE; }
+
+        virtual bool isTextureAttribute() const { return true; }
+
+        virtual GLenum getTextureTarget() const = 0;
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesTextureMode(getTextureTarget());
+            return true;
+        }
+
+        virtual int getTextureWidth() const { return 0; }
+        virtual int getTextureHeight() const { return 0; }
+        virtual int getTextureDepth() const { return 0; }
+
+        enum WrapParameter {
+            WRAP_S,
+            WRAP_T,
+            WRAP_R
+        };
+
+        enum WrapMode {
+            CLAMP  = GL_CLAMP,
+            CLAMP_TO_EDGE = GL_CLAMP_TO_EDGE,
+            CLAMP_TO_BORDER = GL_CLAMP_TO_BORDER_ARB,
+            REPEAT = GL_REPEAT,
+            MIRROR = GL_MIRRORED_REPEAT_IBM
+        };
+
+        /** Sets the texture wrap mode. */
+        void setWrap(WrapParameter which, WrapMode wrap);
+        /** Gets the texture wrap mode. */
+        WrapMode getWrap(WrapParameter which) const;
+
+
+        /** Sets the border color. Only used when wrap mode is CLAMP_TO_BORDER.
+         * The border color will be casted to the appropriate type to match the
+         * internal pixel format of the texture. */
+        void setBorderColor(const Vec4d& color) { _borderColor = color; dirtyTextureParameters(); }
+
+        /** Gets the border color. */
+        const Vec4d& getBorderColor() const { return _borderColor; }
+
+        /** Sets the border width. */
+        void setBorderWidth(GLint width) { _borderWidth = width; dirtyTextureParameters(); }
+        
+        GLint getBorderWidth() const { return _borderWidth; }
+
+        enum FilterParameter {
+            MIN_FILTER,
+            MAG_FILTER
+        };
+
+        enum FilterMode {
+            LINEAR                    = GL_LINEAR,
+            LINEAR_MIPMAP_LINEAR      = GL_LINEAR_MIPMAP_LINEAR,
+            LINEAR_MIPMAP_NEAREST     = GL_LINEAR_MIPMAP_NEAREST,
+            NEAREST                   = GL_NEAREST,
+            NEAREST_MIPMAP_LINEAR     = GL_NEAREST_MIPMAP_LINEAR,
+            NEAREST_MIPMAP_NEAREST    = GL_NEAREST_MIPMAP_NEAREST
+        };
+
+
+        /** Sets the texture filter mode. */
+        void setFilter(FilterParameter which, FilterMode filter);
+
+        /** Gets the texture filter mode. */
+        FilterMode getFilter(FilterParameter which) const;
+
+        /** Sets the maximum anisotropy value, default value is 1.0 for no
+          * anisotropic filtering. If hardware does not support anisotropic
+          * filtering, use normal filtering (equivalent to a max anisotropy
+          * value of 1.0. Valid range is 1.0f upwards.  The maximum value
+          * depends on the graphics system. */
+        void setMaxAnisotropy(float anis);
+        
+        /** Gets the maximum anisotropy value. */
+        inline float getMaxAnisotropy() const { return _maxAnisotropy; }
+
+        /** Sets the hardware mipmap generation hint. If enabled, it will
+          * only be used if supported in the graphics system. */
+        inline void setUseHardwareMipMapGeneration(bool useHardwareMipMapGeneration) { _useHardwareMipMapGeneration = useHardwareMipMapGeneration; }
+
+        /** Gets the hardware mipmap generation hint. */
+        inline bool getUseHardwareMipMapGeneration() const { return _useHardwareMipMapGeneration; }
+
+        /** Sets whether or not the apply() function will unreference the image
+          * data. If enabled, and the image data is only referenced by this
+          * Texture, apply() will delete the image data. */
+        inline void setUnRefImageDataAfterApply(bool flag) { _unrefImageDataAfterApply = flag; }
+        
+        /** Gets whether or not apply() unreferences image data. */
+        inline bool getUnRefImageDataAfterApply() const { return _unrefImageDataAfterApply; }
+
+        /** Sets whether to use client storage for the texture, if supported
+          * by the graphics system. Note: If enabled, and the graphics system
+          * supports it, the osg::Image(s) associated with this texture cannot
+          * be deleted, so the UnRefImageDataAfterApply flag would be ignored. */
+        inline void setClientStorageHint(bool flag) { _clientStorageHint = flag; }
+
+        /** Gets whether to use client storage for the texture. */
+        inline bool getClientStorageHint() const { return _clientStorageHint; }
+
+        /** Sets whether to force the texture to resize images that have dimensions 
+          * that are not a power of two. If enabled, NPOT images will be resized,
+          * whether or not NPOT textures are supported by the hardware. If disabled,
+          * NPOT images will not be resized if supported by hardware. */
+        inline void setResizeNonPowerOfTwoHint(bool flag) { _resizeNonPowerOfTwoHint = flag; }
+
+        /** Gets whether texture will force non power to two images to be resized. */
+        inline bool getResizeNonPowerOfTwoHint() const { return _resizeNonPowerOfTwoHint; }
+
+        enum InternalFormatMode {
+            USE_IMAGE_DATA_FORMAT,
+            USE_USER_DEFINED_FORMAT,
+            USE_ARB_COMPRESSION,
+            USE_S3TC_DXT1_COMPRESSION,
+            USE_S3TC_DXT3_COMPRESSION,
+            USE_S3TC_DXT5_COMPRESSION
+        };
+
+        /** Sets the internal texture format mode. Note: If the texture format is
+          * USE_IMAGE_DATA_FORMAT, USE_ARB_COMPRESSION, or USE_S3TC_COMPRESSION,
+          * the internal format mode is set automatically and will overwrite the
+          * previous _internalFormat. */
+        inline void setInternalFormatMode(InternalFormatMode mode) { _internalFormatMode = mode; }
+
+        /** Gets the internal texture format mode. */
+        inline InternalFormatMode getInternalFormatMode() const { return _internalFormatMode; }
+
+        /** Sets the internal texture format. Implicitly sets the
+          * internalFormatMode to USE_USER_DEFINED_FORMAT.
+          * The corresponding internal format type will be computed. */
+        inline void setInternalFormat(GLint internalFormat)
+        {
+            _internalFormatMode = USE_USER_DEFINED_FORMAT;
+            _internalFormat = internalFormat;
+            computeInternalFormatType();
+        }
+
+
+        /** Gets the internal texture format. */
+        inline GLint getInternalFormat() const { if (_internalFormat==0) computeInternalFormat(); return _internalFormat; }
+        
+        /** Return true if the internal format is one of the compressed formats.*/
+        bool isCompressedInternalFormat() const;
+
+        /** Sets the external source image format, used as a fallback when no osg::Image is attached to provide the source image format. */
+        inline void setSourceFormat(GLenum sourceFormat) { _sourceFormat = sourceFormat; }
+
+        /** Gets the external source image format. */
+        inline GLenum getSourceFormat() const { return _sourceFormat; }
+
+        /** Sets the external source data type, used as a fallback when no osg::Image is attached to provide the source image format.*/
+        inline void setSourceType(GLenum sourceType) { _sourceType = sourceType; }
+
+        /** Gets the external source data type.*/
+        inline GLenum getSourceType() const { return _sourceType; }
+
+        /** Texture type determined by the internal texture format */
+        enum InternalFormatType{
+
+            //! default OpenGL format (clamped values to [0,1) or [0,255])
+            NORMALIZED = 0x0,
+
+            //! float values, Shader Model 3.0 (see ARB_texture_float)
+            FLOAT = 0x1,
+
+            //! Signed integer values (see EXT_texture_integer)
+            SIGNED_INTEGER = 0x2,
+
+            //! Unsigned integer value (see EXT_texture_integer)
+            UNSIGNED_INTEGER = 0x4
+        };
+        
+        /** Get the internal texture format type. */
+        inline InternalFormatType getInternalFormatType() const { return _internalFormatType; }
+        
+        class TextureObject;
+
+        /** Returns a pointer to the texture object for the current context. */
+        inline TextureObject* getTextureObject(unsigned int contextID) const
+        {
+            return _textureObjectBuffer[contextID].get();
+        }
+
+        /** Forces a recompile on next apply() of associated OpenGL texture
+          * objects. */
+        void dirtyTextureObject();
+
+        /** Returns true if the texture objects for all the required graphics
+          * contexts are loaded. */
+        bool areAllTextureObjectsLoaded() const;
+
+
+        /** Gets the dirty flag for the current contextID. */
+        inline unsigned int& getTextureParameterDirty(unsigned int contextID) const
+        {
+            return _texParametersDirtyList[contextID];
+        }
+
+
+        /** Force a reset on next apply() of associated OpenGL texture
+          * parameters. */
+        void dirtyTextureParameters();
+
+        /** Force a manual allocation of the mipmap levels on the next apply() call.
+          * User is responsible for filling the mipmap levels with valid data.
+          * The OpenGL's glGenerateMipmapEXT function is used to generate the mipmap levels.
+          * If glGenerateMipmapEXT is not supported or texture's internal format is not supported
+          * by the glGenerateMipmapEXT, then empty mipmap levels will
+          * be allocated manually. The mipmap levels are also allocated if a non-mipmapped
+          * min filter is used. */
+        void allocateMipmapLevels();
+
+
+        /** Sets GL_TEXTURE_COMPARE_MODE_ARB to GL_COMPARE_R_TO_TEXTURE_ARB
+          * See http://oss.sgi.com/projects/ogl-sample/registry/ARB/shadow.txt. */
+        void setShadowComparison(bool flag) { _use_shadow_comparison = flag; }
+
+        enum ShadowCompareFunc {
+            LEQUAL = GL_LEQUAL,
+            GEQUAL = GL_GEQUAL
+        };
+
+        /** Sets shadow texture comparison function. */
+        void setShadowCompareFunc(ShadowCompareFunc func) { _shadow_compare_func = func; }
+        ShadowCompareFunc getShadowCompareFunc() const { return _shadow_compare_func; }
+
+        enum ShadowTextureMode {
+            LUMINANCE = GL_LUMINANCE,
+            INTENSITY = GL_INTENSITY,
+            ALPHA = GL_ALPHA
+        };
+
+        /** Sets shadow texture mode after comparison. */
+        void setShadowTextureMode(ShadowTextureMode mode) { _shadow_texture_mode = mode; }
+        ShadowTextureMode getShadowTextureMode() const { return _shadow_texture_mode; }
+
+        /** Sets the TEXTURE_COMPARE_FAIL_VALUE_ARB texture parameter. See
+          * http://oss.sgi.com/projects/ogl-sample/registry/ARB/shadow_ambient.txt. */
+        void setShadowAmbient(float shadow_ambient) { _shadow_ambient = shadow_ambient; }
+        float getShadowAmbient() const { return _shadow_ambient; }
+        
+
+        /** Sets the texture image for the specified face. */
+        virtual void setImage(unsigned int face, Image* image) = 0;
+
+        /** Gets the texture image for the specified face. */
+        virtual Image* getImage(unsigned int face) = 0;
+
+        /** Gets the const texture image for specified face. */
+        virtual const Image* getImage(unsigned int face) const = 0;
+
+        /** Gets the number of images that can be assigned to this Texture. */
+        virtual unsigned int getNumImages() const = 0;
+
+
+        /** Set the PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/
+        void setReadPBuffer(GraphicsContext* context) { _readPBuffer = context; }
+
+        /** Get the PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/
+        GraphicsContext* getReadPBuffer() { return _readPBuffer.get(); }
+
+        /** Get the const PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/
+        const GraphicsContext* getReadPBuffer() const { return _readPBuffer.get(); }
+
+        /** Texture is a pure virtual base class, apply must be overridden. */
+        virtual void apply(State& state) const = 0;
+
+        /** Calls apply(state) to compile the texture. */
+        virtual void compileGLObjects(State& state) const;
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** If State is non-zero, this function releases OpenGL objects for
+          * the specified graphics context. Otherwise, releases OpenGL objects
+          * for all graphics contexts. */
+        virtual void releaseGLObjects(State* state=0) const;
+
+        /** Encapsulates queries of extension availability, obtains extension
+          * function pointers, and provides convenience wrappers for
+          * calling extension functions. */        
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setMultiTexturingSupported(bool flag) { _isMultiTexturingSupported=flag; }
+                bool isMultiTexturingSupported() const { return _isMultiTexturingSupported; }
+
+                void setTextureFilterAnisotropicSupported(bool flag) { _isTextureFilterAnisotropicSupported=flag; }
+                bool isTextureFilterAnisotropicSupported() const { return _isTextureFilterAnisotropicSupported; }
+                
+                void setTextureCompressionARBSupported(bool flag) { _isTextureCompressionARBSupported=flag; }
+                bool isTextureCompressionARBSupported() const { return _isTextureCompressionARBSupported; }
+
+                void setTextureCompressionS3TCSupported(bool flag) { _isTextureCompressionS3TCSupported=flag; }
+                bool isTextureCompressionS3TCSupported() const { return _isTextureCompressionS3TCSupported; }
+
+                void setTextureMirroredRepeatSupported(bool flag) { _isTextureMirroredRepeatSupported=flag; }
+                bool isTextureMirroredRepeatSupported() const { return _isTextureMirroredRepeatSupported; }
+
+                void setTextureEdgeClampSupported(bool flag) { _isTextureEdgeClampSupported=flag; }
+                bool isTextureEdgeClampSupported() const { return _isTextureEdgeClampSupported; }
+
+                void setTextureBorderClampSupported(bool flag) { _isTextureBorderClampSupported=flag; }
+                bool isTextureBorderClampSupported() const { return _isTextureBorderClampSupported; }
+
+                void setGenerateMipMapSupported(bool flag) { _isGenerateMipMapSupported=flag; }
+                bool isGenerateMipMapSupported() const { return _isGenerateMipMapSupported; }
+
+                void setShadowSupported(bool flag) { _isShadowSupported = flag; }
+                bool isShadowSupported() const { return _isShadowSupported; }
+
+                void setShadowAmbientSupported(bool flag) { _isShadowAmbientSupported = flag; }
+                bool isShadowAmbientSupported() const { return _isShadowAmbientSupported; }
+
+                void setMaxTextureSize(GLint maxsize) { _maxTextureSize=maxsize; }
+                GLint maxTextureSize() const { return _maxTextureSize; }
+
+                void setNumTextureUnits(GLint nunits ) { _numTextureUnits=nunits; }
+                GLint numTextureUnits() const { return _numTextureUnits; }
+
+                bool isCompressedTexImage2DSupported() const { return _glCompressedTexImage2D!=0; }
+                bool isCompressedTexSubImage2DSupported() const { return _glCompressedTexSubImage2D!=0; }
+                
+                void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data) const;
+                void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei type, const GLvoid *data) const;
+                void glGetCompressedTexImage(GLenum target, GLint level, GLvoid *data) const;
+
+                bool isClientStorageSupported() const { return _isClientStorageSupported; }
+
+                bool isNonPowerOfTwoTextureSupported(GLenum filter) const
+                {
+                    return (filter==GL_LINEAR || filter==GL_NEAREST) ? 
+                            _isNonPowerOfTwoTextureNonMipMappedSupported :
+                            _isNonPowerOfTwoTextureMipMappedSupported;
+                }
+
+                void setTextureIntegerSupported(bool flag) { _isTextureIntegerEXTSupported=flag; }
+                bool isTextureIntegerSupported() const { return _isTextureIntegerEXTSupported; }
+
+                void glTexParameterIiv(GLenum target, GLenum pname, const GLint* data) const;
+                void glTexParameterIuiv(GLenum target, GLenum pname, const GLuint* data) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool    _isMultiTexturingSupported;
+                bool    _isTextureFilterAnisotropicSupported;
+                bool    _isTextureCompressionARBSupported;
+                bool    _isTextureCompressionS3TCSupported;
+                bool    _isTextureMirroredRepeatSupported;
+                bool    _isTextureEdgeClampSupported;
+                bool    _isTextureBorderClampSupported;
+                bool    _isGenerateMipMapSupported;
+                bool    _isShadowSupported;
+                bool    _isShadowAmbientSupported;
+                bool    _isClientStorageSupported;
+                bool    _isNonPowerOfTwoTextureMipMappedSupported;
+                bool    _isNonPowerOfTwoTextureNonMipMappedSupported;
+                bool    _isTextureIntegerEXTSupported;
+
+                GLint   _maxTextureSize;
+                GLint   _numTextureUnits;
+
+                typedef void (APIENTRY * CompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * CompressedTexSubImage2DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * GetCompressedTexImageArbProc) (GLenum target, GLint level, GLvoid *data);
+                typedef void (APIENTRY * TexParameterIivProc)(GLenum target, GLenum pname, const GLint* data);
+                typedef void (APIENTRY * TexParameterIuivProc)(GLenum target, GLenum pname, const GLuint* data);
+
+                CompressedTexImage2DArbProc     _glCompressedTexImage2D;
+                CompressedTexSubImage2DArbProc  _glCompressedTexSubImage2D;
+                GetCompressedTexImageArbProc    _glGetCompressedTexImage;
+                TexParameterIivProc             _glTexParameterIiv;
+                TexParameterIuivProc            _glTexParameterIuiv;
+
+        };
+        
+        /** Gets the extension for the specified context. Creates the
+          * Extensions object for that context if it doesn't exist.
+          * Returns NULL if the Extensions object for the context doesn't
+          * exist and the createIfNotInitalized flag is false. */
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** Overrides Extensions objects across graphics contexts. Typically
+          * used to ensure the same lowest common denominator of extensions
+          * on systems with different graphics pipes. */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+        /** Determine whether the given internalFormat is a compressed
+          * image format. */
+        static bool isCompressedInternalFormat(GLint internalFormat);
+        
+        /** Determine the size of a compressed image, given the internalFormat,
+          * the width, the height, and the depth of the image. The block size
+          * and the size are output parameters. */
+        static void getCompressedSize(GLenum internalFormat, GLint width, GLint height, GLint depth, GLint& blockSize, GLint& size);
+
+
+        /** Helper method. Creates the texture, but doesn't set or use a
+          * texture binding. Note: Don't call this method directly unless
+          * you're implementing a subload callback. */
+        void applyTexImage2D_load(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height,GLsizei numMipmapLevels) const;
+        
+        /** Helper method. Subloads images into the texture, but doesn't set
+          * or use a texture binding. Note: Don't call this method directly
+          * unless you're implementing a subload callback. */
+        void applyTexImage2D_subload(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height, GLint inInternalFormat, GLsizei numMipmapLevels) const;
+
+        /** Returned by mipmapBeforeTexImage() to indicate what
+          * mipmapAfterTexImage() should do */
+        enum GenerateMipmapMode
+        {
+            GENERATE_MIPMAP_NONE,
+            GENERATE_MIPMAP,
+            GENERATE_MIPMAP_TEX_PARAMETER
+        };
+
+    protected :
+
+        virtual ~Texture();
+
+        virtual void computeInternalFormat() const = 0;
+        
+        void computeInternalFormatWithImage(const osg::Image& image) const;
+
+        void computeRequiredTextureDimensions(State& state, const osg::Image& image,GLsizei& width, GLsizei& height,GLsizei& numMipmapLevels) const;
+        
+        void computeInternalFormatType() const;
+
+        /** Helper method. Sets texture parameters. */
+        void applyTexParameters(GLenum target, State& state) const;
+
+        /** Returns true if _useHardwareMipMapGeneration is true and either
+          * glGenerateMipmapEXT() or GL_GENERATE_MIPMAP_SGIS are supported. */
+        bool isHardwareMipmapGenerationEnabled(const State& state) const;
+
+        /** Helper methods to be called before and after calling
+          * gl[Compressed][Copy]Tex[Sub]Image2D to handle generating mipmaps. */
+        GenerateMipmapMode mipmapBeforeTexImage(const State& state, bool hardwareMipmapOn) const;
+        void mipmapAfterTexImage(State& state, GenerateMipmapMode beforeResult) const;
+
+        /** Helper method to generate mipmap levels by calling of glGenerateMipmapEXT.
+          * If it is not supported, then call the virtual allocateMipmap() method */
+        void generateMipmap(State& state) const;
+
+        /** Allocate mipmap levels of the texture by subsequent calling of glTexImage* function. */
+        virtual void allocateMipmap(State& state) const = 0;
+        
+        /** Returns -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        int compareTexture(const Texture& rhs) const;
+
+        /** Returns -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        int compareTextureObjects(const Texture& rhs) const;
+
+        typedef buffered_value<unsigned int> TexParameterDirtyList;
+        mutable TexParameterDirtyList _texParametersDirtyList;
+        mutable TexParameterDirtyList _texMipmapGenerationDirtyList;
+        
+        WrapMode _wrap_s;
+        WrapMode _wrap_t;
+        WrapMode _wrap_r;
+
+        FilterMode      _min_filter;
+        FilterMode      _mag_filter;
+        float           _maxAnisotropy;
+        bool            _useHardwareMipMapGeneration;
+        bool            _unrefImageDataAfterApply;
+        bool            _clientStorageHint;
+        bool            _resizeNonPowerOfTwoHint;
+
+        Vec4d           _borderColor;
+        GLint           _borderWidth;
+
+        InternalFormatMode          _internalFormatMode;
+        mutable InternalFormatType  _internalFormatType;
+        mutable GLint       _internalFormat;
+        mutable GLenum      _sourceFormat;
+        mutable GLenum      _sourceType;
+      
+        bool                _use_shadow_comparison;
+        ShadowCompareFunc   _shadow_compare_func;
+        ShadowTextureMode   _shadow_texture_mode;
+        float               _shadow_ambient;
+
+    public:
+    
+        class TextureObject : public osg::Referenced
+        {
+        public:
+        
+            inline TextureObject(GLuint    id,GLenum target):
+                _id(id),
+                _target(target),
+                _numMipmapLevels(0),
+                _internalFormat(0),
+                _width(0),
+                _height(0),
+                _depth(0),
+                _border(0),
+                _allocated(false),
+                _timeStamp(0) {}
+                
+            inline TextureObject(GLuint    id,
+                          GLenum    target,
+                          GLint     numMipmapLevels,
+                          GLenum    internalFormat,
+                          GLsizei   width,
+                          GLsizei   height,
+                          GLsizei   depth,
+                          GLint     border):
+                _id(id),
+                _target(target),
+                _numMipmapLevels(numMipmapLevels),
+                _internalFormat(internalFormat),
+                _width(width),
+                _height(height),
+                _depth(depth),
+                _border(border),
+                _allocated(false),
+                _timeStamp(0) {}
+                          
+            inline bool match(GLenum    target,
+                       GLint     numMipmapLevels,
+                       GLenum    internalFormat,
+                       GLsizei   width,
+                       GLsizei   height,
+                       GLsizei   depth,
+                       GLint     border)
+            {
+                return isReusable() &&
+                       (_target == target) &&
+                       (_numMipmapLevels == numMipmapLevels) &&
+                       (_internalFormat == internalFormat) &&
+                       (_width == width) &&
+                       (_height == height) &&
+                       (_depth == depth) &&
+                       (_border == border);
+            }
+            
+            
+            inline void bind()
+            {
+                glBindTexture( _target, _id);
+            }
+
+
+            inline void setAllocated(bool allocated=true) { _allocated = allocated; }
+            
+            inline void setAllocated(GLint     numMipmapLevels,
+                              GLenum    internalFormat,
+                              GLsizei   width,
+                              GLsizei   height,
+                              GLsizei   depth,
+                              GLint     border)
+            {
+                _allocated=true;
+                _numMipmapLevels = numMipmapLevels;
+                _internalFormat = internalFormat;
+                _width = width;
+                _height = height;
+                _depth = depth;
+                _border = border;
+            }
+        
+            inline bool isAllocated() const { return _allocated; }
+
+            inline bool isReusable() const { return _allocated && _width!=0; }
+
+            GLuint      _id;
+            GLenum      _target;
+            GLint       _numMipmapLevels;
+            GLenum      _internalFormat;
+            GLsizei     _width;
+            GLsizei     _height;
+            GLsizei     _depth;
+            GLint       _border;
+
+            bool        _allocated;
+            double      _timeStamp;
+        };
+        
+        typedef std::list< ref_ptr<TextureObject> > TextureObjectList;
+        typedef osg::buffered_object<TextureObjectList> TextureObjectListMap; 
+
+        /** Takes the active texture objects from the Texture and places them
+          * in the specified TextureObjectListMap. */
+        void takeTextureObjects(TextureObjectListMap& toblm);
+        
+        
+        static TextureObject* generateTextureObject(unsigned int contextID,GLenum target);
+
+        static TextureObject* generateTextureObject(unsigned int contextID,
+                                                     GLenum    target,
+                                                     GLint     numMipmapLevels,
+                                                     GLenum    internalFormat,
+                                                     GLsizei   width,
+                                                     GLsizei   height,
+                                                     GLsizei   depth,
+                                                     GLint     border);
+
+
+        /** Set the minimum number of texture objects to retain in the deleted display list cache. */
+        static void setMinimumNumberOfTextureObjectsToRetainInCache(unsigned int minimum);
+
+        /** Get the minimum number of display lists to retain in the deleted display list cache. */
+        static unsigned int getMinimumNumberOfTextureObjectsToRetainInCache();
+
+        static void flushAllDeletedTextureObjects(unsigned int contextID);
+
+        static void discardAllDeletedTextureObjects(unsigned int contextID);
+        
+        static void flushDeletedTextureObjects(unsigned int contextID,double currentTime, double& availableTime);
+
+
+    protected:
+
+        typedef buffered_object< ref_ptr<TextureObject> >  TextureObjectBuffer;
+        mutable TextureObjectBuffer         _textureObjectBuffer;
+        mutable ref_ptr<GraphicsContext>    _readPBuffer;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BufferObject
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BufferObject (revision 9302)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BufferObject (revision 9302)
@@ -0,0 +1,441 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_BUFFEROBJECT
+#define OSG_BUFFEROBJECT 1
+
+#include <osg/GL>
+#include <osg/Object>
+#include <osg/buffered_value>
+
+#ifndef GL_ARB_vertex_buffer_object
+
+    #define GL_ARB_vertex_buffer_object
+
+    // for compatibility with gl.h headers that don't support VBO,
+    #if defined(_WIN64)
+        typedef __int64 GLintptrARB;
+        typedef __int64 GLsizeiptrARB;
+    #elif defined(__ia64__) || defined(__x86_64__)
+        typedef long int GLintptrARB;
+        typedef long int GLsizeiptrARB;
+    #else
+        typedef int GLintptrARB;
+        typedef int GLsizeiptrARB;
+    #endif
+
+    #define GL_ARRAY_BUFFER_ARB               0x8892
+    #define GL_ELEMENT_ARRAY_BUFFER_ARB       0x8893
+    #define GL_ARRAY_BUFFER_BINDING_ARB       0x8894
+    #define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
+    #define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
+    #define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
+    #define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
+    #define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
+    #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
+    #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
+    #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
+    #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
+    #define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
+    #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
+    #define GL_STREAM_DRAW_ARB                0x88E0
+    #define GL_STREAM_READ_ARB                0x88E1
+    #define GL_STREAM_COPY_ARB                0x88E2
+    #define GL_STATIC_DRAW_ARB                0x88E4
+    #define GL_STATIC_READ_ARB                0x88E5
+    #define GL_STATIC_COPY_ARB                0x88E6
+    #define GL_DYNAMIC_DRAW_ARB               0x88E8
+    #define GL_DYNAMIC_READ_ARB               0x88E9
+    #define GL_DYNAMIC_COPY_ARB               0x88EA
+    #define GL_READ_ONLY_ARB                  0x88B8
+    #define GL_WRITE_ONLY_ARB                 0x88B9
+    #define GL_READ_WRITE_ARB                 0x88BA
+    #define GL_BUFFER_SIZE_ARB                0x8764
+    #define GL_BUFFER_USAGE_ARB               0x8765
+    #define GL_BUFFER_ACCESS_ARB              0x88BB
+    #define GL_BUFFER_MAPPED_ARB              0x88BC
+    #define GL_BUFFER_MAP_POINTER_ARB         0x88BD
+
+#endif
+
+#ifndef GL_VERSION_1_5
+    #define GL_STREAM_DRAW                    0x88E0
+    #define GL_STREAM_READ                    0x88E1
+    #define GL_STREAM_COPY                    0x88E2
+    #define GL_STATIC_DRAW                    0x88E4
+    #define GL_STATIC_READ                    0x88E5
+    #define GL_STATIC_COPY                    0x88E6
+    #define GL_DYNAMIC_DRAW                   0x88E8
+    #define GL_DYNAMIC_READ                   0x88E9
+    #define GL_DYNAMIC_COPY                   0x88EA
+#endif
+
+#ifndef GL_VERSION_2_1
+    #define GL_PIXEL_PACK_BUFFER              0x88EB
+    #define GL_PIXEL_UNPACK_BUFFER            0x88EC
+    #define GL_PIXEL_PACK_BUFFER_BINDING      0x88ED
+    #define GL_PIXEL_UNPACK_BUFFER_BINDING    0x88EF
+#endif
+
+
+#ifndef GL_ARB_pixel_buffer_object
+    #define GL_PIXEL_PACK_BUFFER_ARB            0x88EB
+    #define GL_PIXEL_UNPACK_BUFFER_ARB          0x88EC
+    #define GL_PIXEL_PACK_BUFFER_BINDING_ARB    0x88ED
+    #define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB  0x88EF
+#endif
+
+namespace osg 
+{
+
+class State;
+
+class OSG_EXPORT BufferObject : public Object
+{
+    public:
+
+        BufferObject();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        BufferObject(const BufferObject& bo,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const BufferObject*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "BufferObject"; }
+
+        /** Set what type of usage the buffer object will have. Options are: 
+          *          GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, 
+          *          GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, 
+          *          GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, or GL_DYNAMIC_COPY.
+          */
+        void setUsage(GLenum usage) { _usage = usage; }
+        
+        /** Get the type of usage the buffer object has been set up for.*/
+        GLenum getUsage() const { return _usage; }
+
+        struct BufferEntry
+        {
+            BufferEntry(): dataSize(0),offset(0) {}
+            BufferEntry(const BufferEntry& be): modifiedCount(be.modifiedCount),dataSize(be.dataSize),offset(be.offset) {}
+        
+            BufferEntry& operator = (const BufferEntry& be) { modifiedCount=be.modifiedCount; dataSize=be.dataSize; offset=be.offset; return *this; }
+
+            mutable buffered_value<unsigned int>    modifiedCount;
+            mutable unsigned int                    dataSize;
+            mutable unsigned int                    offset;
+        };
+
+        inline bool isBufferObjectSupported(unsigned int contextID) const { return getExtensions(contextID,true)->isBufferObjectSupported(); }
+        inline bool isPBOSupported(unsigned int contextID) const { return getExtensions(contextID,true)->isPBOSupported(); }
+
+        inline GLuint& buffer(unsigned int contextID) const { return _bufferObjectList[contextID]; }
+        
+        inline void bindBuffer(unsigned int contextID) const
+        { 
+            Extensions* extensions = getExtensions(contextID,true);
+            extensions->glBindBuffer(_target,_bufferObjectList[contextID]);
+        }
+
+        virtual void unbindBuffer(unsigned int contextID) const
+        { 
+            Extensions* extensions = getExtensions(contextID,true);
+            extensions->glBindBuffer(_target,0);
+        }
+
+        inline void dirty() { _compiledList.setAllElementsTo(0); }
+
+        bool isDirty(unsigned int contextID) const { return _compiledList[contextID]==0; }
+
+        virtual void compileBuffer(State& state) const = 0;
+        
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** If State is non-zero, this function releases OpenGL objects for
+          * the specified graphics context. Otherwise, releases OpenGL objects
+          * for all graphics contexts. */
+        void releaseGLObjects(State* state=0) const;
+
+
+        /** Use deleteVertexBufferObject instead of glDeleteBuffers to allow
+          * OpenGL buffer objects to be cached until they can be deleted
+          * by the OpenGL context in which they were created, specified
+          * by contextID.*/
+        static void deleteBufferObject(unsigned int contextID,GLuint globj);
+
+        /** flush all the cached display list which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void flushDeletedBufferObjects(unsigned int contextID,double /*currentTime*/, double& availableTime);
+
+        /** dicard all the cached display list which need to be deleted
+          * in the OpenGL context related to contextID.
+          * Note, unlike flush no OpenGL calls are made, instead the handles are all removed.
+          * this call is useful for when an OpenGL context has been destroyed. */
+        static void discardDeletedBufferObjects(unsigned int contextID);
+
+        /** Extensions class which encapsulates the querying of extensions and
+        * associated function pointers, and provide convenience wrappers to
+        * check for the extensions or use the associated functions.*/
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+        public:
+            Extensions(unsigned int contextID);
+
+            Extensions(const Extensions& rhs);
+
+            void lowestCommonDenominator(const Extensions& rhs);
+
+            void setupGLExtensions(unsigned int contextID);
+
+            bool isBufferObjectSupported() const { return _glGenBuffers!=0; }
+            bool isPBOSupported() const { return _isPBOSupported; }
+
+            void glGenBuffers (GLsizei n, GLuint *buffers) const;
+            void glBindBuffer (GLenum target, GLuint buffer) const;
+            void glBufferData (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage) const;
+            void glBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data) const;
+            void glDeleteBuffers (GLsizei n, const GLuint *buffers) const;
+            GLboolean glIsBuffer (GLuint buffer) const;
+            void glGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data) const;
+            GLvoid* glMapBuffer (GLenum target, GLenum access) const;
+            GLboolean glUnmapBuffer (GLenum target) const;
+            void glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params) const;
+            void glGetBufferPointerv (GLenum target, GLenum pname, GLvoid* *params) const;
+
+        protected:
+
+            typedef void (APIENTRY * GenBuffersProc) (GLsizei n, GLuint *buffers);
+            typedef void (APIENTRY * BindBufferProc) (GLenum target, GLuint buffer);
+            typedef void (APIENTRY * BufferDataProc) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+            typedef void (APIENTRY * BufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+            typedef void (APIENTRY * DeleteBuffersProc) (GLsizei n, const GLuint *buffers);
+            typedef GLboolean (APIENTRY * IsBufferProc) (GLuint buffer);
+            typedef void (APIENTRY * GetBufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+            typedef GLvoid* (APIENTRY * MapBufferProc) (GLenum target, GLenum access);
+            typedef GLboolean (APIENTRY * UnmapBufferProc) (GLenum target);
+            typedef void (APIENTRY * GetBufferParameterivProc) (GLenum target, GLenum pname, GLint *params);
+            typedef void (APIENTRY * GetBufferPointervProc) (GLenum target, GLenum pname, GLvoid* *params);
+
+            GenBuffersProc          _glGenBuffers;
+            BindBufferProc          _glBindBuffer;
+            BufferDataProc          _glBufferData;
+            BufferSubDataProc       _glBufferSubData;
+            DeleteBuffersProc       _glDeleteBuffers;
+            IsBufferProc            _glIsBuffer;
+            GetBufferSubDataProc    _glGetBufferSubData;
+            MapBufferProc           _glMapBuffer;
+            UnmapBufferProc         _glUnmapBuffer;
+            GetBufferParameterivProc _glGetBufferParameteriv;
+            GetBufferPointervProc   _glGetBufferPointerv;
+
+            bool _isPBOSupported;
+        };
+
+        /** Function to call to get the extension of a specified context.
+        * If the Extension object for that context has not yet been created  
+        * and the 'createIfNotInitalized' flag been set to false then returns NULL.
+        * If 'createIfNotInitalized' is true then the Extensions object is 
+        * automatically created.  However, in this case the extension object is
+        * only created with the graphics context associated with ContextID..*/
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** setExtensions allows users to override the extensions across graphics contexts.
+        * typically used when you have different extensions supported across graphics pipes
+        * but need to ensure that they all use the same low common denominator extensions.*/
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+    protected:
+    
+        virtual ~BufferObject();
+        
+        typedef osg::buffered_value<GLuint> GLObjectList;
+        typedef osg::buffered_value<unsigned int> CompiledList;
+
+        mutable GLObjectList    _bufferObjectList;
+        mutable CompiledList    _compiledList;
+
+        GLenum                  _target;
+        GLenum                  _usage;
+        mutable unsigned int    _totalSize;
+};
+
+class Array;
+class OSG_EXPORT VertexBufferObject : public BufferObject
+{
+    public:
+
+        VertexBufferObject();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        VertexBufferObject(const VertexBufferObject& vbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg,VertexBufferObject);
+        
+        typedef std::pair< BufferEntry, Array* > BufferEntryArrayPair;
+        typedef std::vector< BufferEntryArrayPair > BufferEntryArrayPairs;
+
+        unsigned int addArray(osg::Array* array);
+        void removeArray(osg::Array* array);
+
+        void setArray(unsigned int i, Array* array);
+        Array* getArray(unsigned int i) { return _bufferEntryArrayPairs[i].second; }
+        const Array* getArray(unsigned int i) const { return _bufferEntryArrayPairs[i].second; }
+        
+        const GLvoid* getOffset(unsigned int i) const { return (const GLvoid*)(((char *)0)+(_bufferEntryArrayPairs[i].first.offset)); }
+
+        virtual void compileBuffer(State& state) const;
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+    protected:
+    
+        virtual ~VertexBufferObject();
+        
+        BufferEntryArrayPairs _bufferEntryArrayPairs;
+};
+
+class DrawElements;
+class OSG_EXPORT ElementBufferObject : public BufferObject
+{
+    public:
+
+        ElementBufferObject();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        ElementBufferObject(const ElementBufferObject& pbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg,ElementBufferObject);
+        
+        typedef std::pair< BufferEntry, DrawElements* > BufferEntryDrawElementsPair;
+        typedef std::vector< BufferEntryDrawElementsPair > BufferEntryDrawElementsPairs;
+
+        unsigned int addDrawElements(osg::DrawElements* PrimitiveSet);
+        void removeDrawElements(osg::DrawElements* PrimitiveSet);
+
+        void setDrawElements(unsigned int i, DrawElements* PrimitiveSet);
+        DrawElements* getDrawElements(unsigned int i) { return _bufferEntryDrawElementsPairs[i].second; }
+        const DrawElements* getDrawElements(unsigned int i) const { return _bufferEntryDrawElementsPairs[i].second; }
+        
+        const GLvoid* getOffset(unsigned int i) const { return (const GLvoid*)(((char *)0)+(_bufferEntryDrawElementsPairs[i].first.offset)); }
+
+        virtual void compileBuffer(State& state) const;
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+    protected:
+    
+        virtual ~ElementBufferObject();
+        
+        BufferEntryDrawElementsPairs _bufferEntryDrawElementsPairs;
+};
+
+class Image;
+class OSG_EXPORT PixelBufferObject : public BufferObject
+{
+    public:
+
+        PixelBufferObject(osg::Image* image=0);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        PixelBufferObject(const PixelBufferObject& pbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg,PixelBufferObject);
+        
+        typedef std::pair< BufferEntry, Image* > BufferEntryImagePair;
+
+        void setImage(osg::Image* image);
+
+        Image* getImage() { return _bufferEntryImagePair.second; }
+        const Image* getImage() const { return _bufferEntryImagePair.second; }
+        
+        unsigned int offset() const { return _bufferEntryImagePair.first.offset; }
+        
+        virtual void compileBuffer(State& state) const;
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+    protected:
+    
+        virtual ~PixelBufferObject();
+        
+        BufferEntryImagePair _bufferEntryImagePair;
+};
+
+/**
+ * This object represent a general class of pixel buffer objects,
+ * which are capable of allocating buffer object (memory)
+ * on the GPU. The memory can then be used either for CPU-GPU
+ * pixel transfer or directly for GPU-GPU transfer, without CPU intervention.
+ **/
+class OSG_EXPORT PixelDataBufferObject : public BufferObject
+{
+    public:
+        PixelDataBufferObject();
+        PixelDataBufferObject(const PixelDataBufferObject& pbo, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, PixelDataBufferObject);
+
+        //! Set new size of the buffer object. This will reallocate the memory on the next compile
+        inline void setDataSize(unsigned int size) { _bufferData.dataSize = size; dirty(); }
+
+        //! Get data size of the used buffer 
+        inline unsigned int getDataSize() { return _bufferData.dataSize; }
+
+        //! Compile the buffer (reallocate the memory if buffer is dirty)
+        virtual void compileBuffer(State& state) const;
+
+        //! Bind the buffer in read mode, which means that data can be downloaded from the buffer (note: GL_PIXEL_UNPACK_BUFFER_ARB)
+        virtual void bindBufferInReadMode(State& state);
+
+        //! Bind the buffer in write mode, which means following OpenGL instructions will write data into the buffer (note: GL_PIXEL_PACK_BUFFER_ARB)
+        virtual void bindBufferInWriteMode(State& state);
+
+        //! Unbind the buffer 
+        virtual void unbindBuffer(unsigned int contextID) const;
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        enum Mode
+        {
+            //! A normal mode of this data buffer
+            NONE = 0,
+
+            //! Buffer is in read mode (@see bindBufferInReadMode)
+            READ = 1,
+
+            //! Buffer is in write mode (@see bindBufferInWriteMode)
+            WRITE = 2
+        };
+
+        Mode getMode(unsigned int contextID) const { return (Mode)_mode[contextID]; }
+
+    protected:
+
+        virtual ~PixelDataBufferObject();
+
+        BufferEntry _bufferData;
+
+        typedef osg::buffered_value<unsigned int> ModeList;
+        
+        mutable ModeList _mode;
+        
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/fast_back_stack
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/fast_back_stack (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/fast_back_stack (revision 5328)
@@ -0,0 +1,97 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_FAST_BACK_STACK
+#define OSG_FAST_BACK_STACK 1
+
+#include <vector>
+
+namespace osg {
+
+/** Simple stack implementation that keeps the back() cached locally for fast access
+  * rather than at the back of the vector which is the traditional stack implementation.
+  * A conventional std::vector<> stores the rest of the stack. Although fast_back_stack
+  *  contains a stl container it only implements the back push_back(),pop_back()
+  * and back() methods so is not as general purpose as stl stack implementation.
+  * The focus of the fast_back_stack is purely to maximize the speed at which the
+  * back can be accessed.*/
+  
+template<class T>
+class fast_back_stack
+{
+    public:
+    
+        inline fast_back_stack():_value(),_stack(),_size(0) {}
+
+        inline fast_back_stack(const fast_back_stack& fbs):_value(fbs._value),_stack(fbs._stack),_size(fbs._size) {}
+
+        inline fast_back_stack(const T& value):_value(value),_stack(),_size(1) {}
+
+        fast_back_stack& operator = (const fast_back_stack& fbs)
+        {
+            _value = fbs._value;
+            _stack = fbs._stack;
+            _size = fbs._size;
+            return *this;
+        }
+
+        inline void clear() { _stack.clear(); _size = 0; }
+
+        inline bool empty() const { return _size==0; }
+
+        inline unsigned int size() const { return _size; }
+
+        inline T& back() { return _value; }
+
+        inline const T& back() const { return _value; }
+
+        inline void push_back()
+        {
+            if (_size>0)
+            {
+                _stack.push_back(_value);
+            }
+            ++_size;
+        }
+        
+        inline void push_back(const T& value)
+        {
+            if (_size>0)
+            {
+                _stack.push_back(_value);
+            }
+            _value = value;
+            ++_size;
+        }
+        
+        inline void pop_back()
+        {
+            if (_size>0)
+            {
+                if (!_stack.empty())
+                {
+                    _value = _stack.back();
+                    _stack.pop_back();
+                }
+                --_size;
+            } // else error condition.
+        }
+        
+        T              _value;
+        std::vector<T> _stack;
+        unsigned int   _size;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageUtils
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageUtils (revision 10233)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ImageUtils (revision 10233)
@@ -0,0 +1,138 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_IMAGEUTILS
+#define OSG_IMAGEUTILS 1
+
+#include <osg/Export>
+
+#include <osg/Image>
+
+namespace osg {
+
+template <typename T, class O>    
+void _readRow(unsigned int num, GLenum pixelFormat, const T* data,float scale, O& operation)
+{
+    switch(pixelFormat)
+    {
+        case(GL_LUMINANCE):         { for(unsigned int i=0;i<num;++i) { float l = float(*data++)*scale; operation.luminance(l); } }  break;
+        case(GL_ALPHA):             { for(unsigned int i=0;i<num;++i) { float a = float(*data++)*scale; operation.alpha(a); } }  break;
+        case(GL_LUMINANCE_ALPHA):   { for(unsigned int i=0;i<num;++i) { float l = float(*data++)*scale; float a = float(*data++)*scale; operation.luminance_alpha(l,a); } }  break;
+        case(GL_RGB):               { for(unsigned int i=0;i<num;++i) { float r = float(*data++)*scale; float g = float(*data++)*scale; float b = float(*data++)*scale; operation.rgb(r,g,b); } }  break;
+        case(GL_RGBA):              { for(unsigned int i=0;i<num;++i) { float r = float(*data++)*scale; float g = float(*data++)*scale; float b = float(*data++)*scale; float a = float(*data++)*scale; operation.rgba(r,g,b,a); } }  break;
+        case(GL_BGR):               { for(unsigned int i=0;i<num;++i) { float b = float(*data++)*scale; float g = float(*data++)*scale; float r = float(*data++)*scale; operation.rgb(r,g,b); } }  break;
+        case(GL_BGRA):              { for(unsigned int i=0;i<num;++i) { float b = float(*data++)*scale; float g = float(*data++)*scale; float r = float(*data++)*scale; float a = float(*data++)*scale; operation.rgba(r,g,b,a); } }  break;
+    }
+}
+
+template <class O>    
+void readRow(unsigned int num, GLenum pixelFormat, GLenum dataType, const unsigned char* data, O& operation)
+{
+    switch(dataType)
+    {
+        case(GL_BYTE):              _readRow(num,pixelFormat, (const char*)data,            1.0f/128.0f,        operation); break;
+        case(GL_UNSIGNED_BYTE):     _readRow(num,pixelFormat, (const unsigned char*)data,   1.0f/255.0f,        operation); break;
+        case(GL_SHORT):             _readRow(num,pixelFormat, (const short*) data,          1.0f/32768.0f,      operation); break;
+        case(GL_UNSIGNED_SHORT):    _readRow(num,pixelFormat, (const unsigned short*)data,  1.0f/65535.0f,      operation); break;
+        case(GL_INT):               _readRow(num,pixelFormat, (const int*) data,            1.0f/2147483648.0f, operation); break;
+        case(GL_UNSIGNED_INT):      _readRow(num,pixelFormat, (const unsigned int*) data,   1.0f/4294967295.0f, operation); break;
+        case(GL_FLOAT):             _readRow(num,pixelFormat, (const float*) data,          1.0f,               operation); break;
+    }
+}
+
+template <class O>    
+void readImage(const osg::Image* image, O& operation)
+{
+    if (!image) return;
+    
+    for(int r=0;r<image->r();++r)
+    {
+        for(int t=0;t<image->t();++t)
+        {
+            readRow(image->s(), image->getPixelFormat(), image->getDataType(), image->data(0,t,r), operation);
+        }
+    }
+}
+
+// example ModifyOperator
+// struct ModifyOperator
+// {
+//     inline void luminance(float& l) const {} 
+//     inline void alpha(float& a) const {} 
+//     inline void luminance_alpha(float& l,float& a) const {} 
+//     inline void rgb(float& r,float& g,float& b) const {}
+//     inline void rgba(float& r,float& g,float& b,float& a) const {}
+// };
+
+
+template <typename T, class M>    
+void _modifyRow(unsigned int num, GLenum pixelFormat, T* data,float scale, const M& operation)
+{
+    float inv_scale = 1.0f/scale;
+    switch(pixelFormat)
+    {
+        case(GL_LUMINANCE):         { for(unsigned int i=0;i<num;++i) { float l = float(*data)*scale; operation.luminance(l); *data++ = T(l*inv_scale); } }  break;
+        case(GL_ALPHA):             { for(unsigned int i=0;i<num;++i) { float a = float(*data)*scale; operation.alpha(a); *data++ = T(a*inv_scale); } }  break;
+        case(GL_LUMINANCE_ALPHA):   { for(unsigned int i=0;i<num;++i) { float l = float(*data)*scale; float a = float(*(data+1))*scale; operation.luminance_alpha(l,a); *data++ = T(l*inv_scale); *data++ = T(a*inv_scale); } }  break;
+        case(GL_RGB):               { for(unsigned int i=0;i<num;++i) { float r = float(*data)*scale; float g = float(*(data+1))*scale; float b = float(*(data+2))*scale; operation.rgb(r,g,b); *data++ = T(r*inv_scale); *data++ = T(g*inv_scale); *data++ = T(b*inv_scale); } }  break;
+        case(GL_RGBA):              { for(unsigned int i=0;i<num;++i) { float r = float(*data)*scale; float g = float(*(data+1))*scale; float b = float(*(data+2))*scale; float a = float(*(data+3))*scale; operation.rgba(r,g,b,a); *data++ = T(r*inv_scale); *data++ = T(g*inv_scale); *data++ = T(g*inv_scale); *data++ = T(a*inv_scale); } }  break;
+        case(GL_BGR):               { for(unsigned int i=0;i<num;++i) { float b = float(*data)*scale; float g = float(*(data+1))*scale; float r = float(*(data+2))*scale; operation.rgb(r,g,b); *data++ = T(b*inv_scale); *data++ = T(g*inv_scale); *data++ = T(r*inv_scale); } }  break;
+        case(GL_BGRA):              { for(unsigned int i=0;i<num;++i) { float b = float(*data)*scale; float g = float(*(data+1))*scale; float r = float(*(data+2))*scale; float a = float(*(data+3))*scale; operation.rgba(r,g,b,a); *data++ = T(g*inv_scale); *data++ = T(b*inv_scale); *data++ = T(r*inv_scale); *data++ = T(a*inv_scale); } }  break;
+    }
+}
+
+template <class M>    
+void modifyRow(unsigned int num, GLenum pixelFormat, GLenum dataType, unsigned char* data, const M& operation)
+{
+    switch(dataType)
+    {
+        case(GL_BYTE):              _modifyRow(num,pixelFormat, (char*)data,            1.0f/128.0f,        operation); break;
+        case(GL_UNSIGNED_BYTE):     _modifyRow(num,pixelFormat, (unsigned char*)data,   1.0f/255.0f,        operation); break;
+        case(GL_SHORT):             _modifyRow(num,pixelFormat, (short*) data,          1.0f/32768.0f,      operation); break;
+        case(GL_UNSIGNED_SHORT):    _modifyRow(num,pixelFormat, (unsigned short*)data,  1.0f/65535.0f,      operation); break;
+        case(GL_INT):               _modifyRow(num,pixelFormat, (int*) data,            1.0f/2147483648.0f, operation); break;
+        case(GL_UNSIGNED_INT):      _modifyRow(num,pixelFormat, (unsigned int*) data,   1.0f/4294967295.0f, operation); break;
+        case(GL_FLOAT):             _modifyRow(num,pixelFormat, (float*) data,          1.0f,               operation); break;
+    }
+}
+
+template <class M>    
+void modifyImage(osg::Image* image, const M& operation)
+{
+    if (!image) return;
+    
+    for(int r=0;r<image->r();++r)
+    {
+        for(int t=0;t<image->t();++t)
+        {
+            modifyRow(image->s(), image->getPixelFormat(), image->getDataType(), image->data(0,t,r), operation);
+        }
+    }
+}
+
+/** Compute the min max colour values in the image.*/
+extern OSG_EXPORT bool computeMinMax(const osg::Image* image, osg::Vec4& min, osg::Vec4& max);
+
+/** Compute the min max colour values in the image.*/
+extern OSG_EXPORT bool offsetAndScaleImage(osg::Image* image, const osg::Vec4& offset, const osg::Vec4& scale);
+
+/** Compute source image to destination image.*/
+extern OSG_EXPORT bool copyImage(const osg::Image* srcImage, int src_s, int src_t, int src_r, int width, int height, int depth,
+                                       osg::Image* destImage, int dest_s, int dest_t, int dest_r, bool doRescale = false);
+
+/** Compute the min max colour values in the image.*/
+extern OSG_EXPORT bool clearImageToColor(osg::Image* image, const osg::Vec4& colour);
+}
+
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeVisitor (revision 9464)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeVisitor (revision 9464)
@@ -0,0 +1,367 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_NODEVISITOR
+#define OSG_NODEVISITOR 1
+
+#include <osg/Node>
+#include <osg/Matrix>
+#include <osg/FrameStamp>
+
+namespace osg {
+
+class Billboard;
+class ClearNode;
+class ClipNode;
+class CoordinateSystemNode;
+class Geode;
+class Group;
+class LightSource;
+class LOD;
+class MatrixTransform;
+class OccluderNode;
+class OcclusionQueryNode;
+class PagedLOD;
+class PositionAttitudeTransform;
+class Projection;
+class ProxyNode;
+class Sequence;
+class Switch;
+class TexGenNode;
+class Transform;
+class Camera;
+class CameraView;
+
+#define META_NodeVisitor(library,name) \
+        virtual const char* libraryName() const { return #library; }\
+        virtual const char* className() const { return #name; }
+
+/** Visitor for type safe operations on osg::Nodes.
+    Based on GOF's Visitor pattern. The NodeVisitor 
+    is useful for developing type safe operations to nodes
+    in the scene graph (as per Visitor pattern), and adds to this
+    support for optional scene graph traversal to allow
+    operations to be applied to whole scenes at once. The Visitor
+    pattern uses a technique of double dispatch as a mechanism to
+    call the appropriate apply(..) method of the NodeVisitor.  To
+    use this feature one must use the Node::accept(NodeVisitor) which
+    is extended in each Node subclass, rather than the NodeVisitor
+    apply directly.  So use root->accept(myVisitor); instead of
+    myVisitor.apply(*root).  The later method will bypass the double
+    dispatch and the appropriate NodeVisitor::apply(..) method will
+    not be called. */ 
+class OSG_EXPORT NodeVisitor : public virtual Referenced
+{
+    public:
+
+        enum TraversalMode
+        {
+            TRAVERSE_NONE,
+            TRAVERSE_PARENTS,
+            TRAVERSE_ALL_CHILDREN,
+            TRAVERSE_ACTIVE_CHILDREN
+        };
+        
+        enum VisitorType
+        {
+            NODE_VISITOR = 0,
+            UPDATE_VISITOR,
+            EVENT_VISITOR,
+            COLLECT_OCCLUDER_VISITOR,
+            CULL_VISITOR
+        };
+
+        NodeVisitor(TraversalMode tm=TRAVERSE_NONE);
+        
+        NodeVisitor(VisitorType type,TraversalMode tm=TRAVERSE_NONE);
+        
+        virtual ~NodeVisitor();
+        
+        /** return the library name/namespapce of the visitor's. Should be defined by derived classes.*/
+        virtual const char* libraryName() const { return "osg"; }
+
+        /** return the name of the visitor's class type. Should be defined by derived classes.*/
+        virtual const char* className() const { return "NodeVisitor"; }
+
+        /** Method to call to reset visitor. Useful if your visitor accumulates
+            state during a traversal, and you plan to reuse the visitor. 
+            To flush that state for the next traversal: call reset() prior
+            to each traversal.*/
+        virtual void reset() {}
+
+
+        /** Set the VisitorType, used to distinguish different visitors during
+          * traversal of the scene, typically used in the Node::traverse() method
+          * to select which behaviour to use for different types of traversal/visitors.*/
+        inline void setVisitorType(VisitorType type) { _visitorType = type; }
+        
+        /** Get the VisitorType.*/
+        inline VisitorType getVisitorType() const { return _visitorType; }
+
+        /** Set the traversal number. Typically used to denote the frame count.*/
+        inline void setTraversalNumber(int fn) { _traversalNumber = fn; }
+        
+        /** Get the traversal number. Typically used to denote the frame count.*/
+        inline int getTraversalNumber() const { return _traversalNumber; }
+
+        /** Set the FrameStamp that this traversal is associated with.*/
+        inline void setFrameStamp(FrameStamp* fs) { _frameStamp = fs; }
+        
+        /** Get the FrameStamp that this traversal is associated with.*/
+        inline const FrameStamp* getFrameStamp() const { return _frameStamp.get(); }
+
+
+        /** Set the TraversalMask of this NodeVisitor.
+          * The TraversalMask is used by the NodeVisitor::validNodeMask() method
+          * to determine whether to operate on a node and its subgraph.
+          * validNodeMask() is called automatically in the Node::accept() method before
+          * any call to NodeVisitor::apply(), apply() is only ever called if validNodeMask
+          * returns true. Note, if NodeVisitor::_traversalMask is 0 then all operations
+          * will be switched off for all nodes.  Whereas setting both _traversalMask and
+          * _nodeMaskOverride to 0xffffffff will allow a visitor to work on all nodes
+          * regardless of their own Node::_nodeMask state.*/
+        inline void setTraversalMask(Node::NodeMask mask) { _traversalMask = mask; }
+
+        /** Get the TraversalMask.*/
+        inline Node::NodeMask getTraversalMask() const { return _traversalMask; }
+
+        /** Set the NodeMaskOverride mask.
+          * Used in validNodeMask() to determine whether to operate on a node or its 
+          * subgraph, by OR'ing NodeVisitor::_nodeMaskOverride with the Node's own Node::_nodeMask.
+          * Typically used to force on nodes which may have
+          * been switched off by their own Node::_nodeMask.*/
+        inline void setNodeMaskOverride(Node::NodeMask mask) { _nodeMaskOverride = mask; }
+
+        /** Get the NodeMaskOverride mask.*/
+        inline Node::NodeMask getNodeMaskOverride() const { return _nodeMaskOverride; }
+        
+        /** Method to called by Node and its subclass' Node::accept() method, if the result is true
+          * it is used to cull operations of nodes and their subgraphs.
+          * Return true if the result of a bit wise and of the NodeVisitor::_traversalMask
+          * with the bit or between NodeVistor::_nodeMaskOverride and the Node::_nodeMask.
+          * default values for _traversalMask is 0xffffffff, _nodeMaskOverride is 0x0,
+          * and osg::Node::_nodeMask is 0xffffffff. */
+        inline bool validNodeMask(const osg::Node& node) const
+        {
+            return (getTraversalMask() & (getNodeMaskOverride() | node.getNodeMask()))!=0;
+        }
+
+        /** Set the traversal mode for Node::traverse() to use when 
+            deciding which children of a node to traverse. If a
+            NodeVisitor has been attached via setTraverseVisitor()
+            and the new mode is not TRAVERSE_VISITOR then the attached
+            visitor is detached. Default mode is TRAVERSE_NONE.*/
+        inline void setTraversalMode(TraversalMode mode) { _traversalMode = mode; }
+        
+        /** Get the traversal mode.*/
+        inline TraversalMode getTraversalMode() const { return _traversalMode; }
+
+        /**
+         * Set user data, data must be subclassed from Referenced to allow
+         * automatic memory handling.  If your own data isn't directly 
+         * subclassed from Referenced then create an adapter object
+         * which points to your own objects and handles the memory addressing.
+         */
+        inline void setUserData(Referenced* obj) { _userData = obj; }
+        
+        /** Get user data.*/
+        inline Referenced* getUserData() { return _userData.get(); }
+        
+        /** Get const user data.*/
+        inline const Referenced* getUserData() const { return _userData.get(); }
+
+
+        /** Method for handling traversal of a nodes.
+            If you intend to use the visitor for actively traversing 
+            the scene graph then make sure the accept() methods call
+            this method unless they handle traversal directly.*/
+        inline void traverse(Node& node)
+        {
+            if (_traversalMode==TRAVERSE_PARENTS) node.ascend(*this);
+            else if (_traversalMode!=TRAVERSE_NONE) node.traverse(*this);
+        }
+        
+        /** Method called by osg::Node::accept() method before
+          * a call to the NodeVisitor::apply(..).  The back of the list will,
+          * therefore, be the current node being visited inside the apply(..),
+          * and the rest of the list will be the parental sequence of nodes 
+          * from the top most node applied down the graph to the current node.
+          * Note, the user does not typically call pushNodeOnPath() as it
+          * will be called automatically by the Node::accept() method.*/
+        inline void pushOntoNodePath(Node* node) { if (_traversalMode!=TRAVERSE_PARENTS) _nodePath.push_back(node); else _nodePath.insert(_nodePath.begin(),node); }
+        
+        /** Method called by osg::Node::accept() method after
+          * a call to NodeVisitor::apply(..).
+          * Note, the user does not typically call popFromNodePath() as it
+          * will be called automatically by the Node::accept() method.*/
+        inline void popFromNodePath()            { if (_traversalMode!=TRAVERSE_PARENTS) _nodePath.pop_back(); else _nodePath.erase(_nodePath.begin()); }
+        
+        /** Get the non const NodePath from the top most node applied down
+          * to the current Node being visited.*/
+        NodePath& getNodePath() { return _nodePath; }
+
+        /** Get the const NodePath from the top most node applied down
+          * to the current Node being visited.*/
+        const NodePath& getNodePath() const { return _nodePath; }
+        
+        /** Get the eye point in local coordinates.
+          * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.*/
+        virtual osg::Vec3 getEyePoint() const { return Vec3(0.0f,0.0f,0.0f); }
+
+        /** Get the view point in local coordinates.
+          * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.*/
+        virtual osg::Vec3 getViewPoint() const { return getEyePoint(); }
+
+        /** Get the distance from a point to the eye point, distance value in local coordinate system.
+          * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.
+          * If the getDistanceFromEyePoint(pos) is not implemented then a default value of 0.0 is returned.*/
+        virtual float getDistanceToEyePoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; }
+
+        /** Get the distance of a point from the eye point, distance value in the eye coordinate system.
+          * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.
+          * If the getDistanceFromEyePoint(pos) is not implemented than a default value of 0.0 is returned.*/
+        virtual float getDistanceFromEyePoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; }
+
+        /** Get the distance from a point to the view point, distance value in local coordinate system.
+          * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.
+          * If the getDistanceToViewPoint(pos) is not implemented then a default value of 0.0 is returned.*/
+        virtual float getDistanceToViewPoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; }
+        
+
+        virtual void apply(Node& node);
+        
+        virtual void apply(Geode& node);
+        virtual void apply(Billboard& node);
+        
+        virtual void apply(Group& node);
+
+        virtual void apply(ProxyNode& node);
+
+        virtual void apply(Projection& node);
+
+        virtual void apply(CoordinateSystemNode& node);
+
+        virtual void apply(ClipNode& node);
+        virtual void apply(TexGenNode& node);
+        virtual void apply(LightSource& node);
+
+        virtual void apply(Transform& node);
+        virtual void apply(Camera& node);
+        virtual void apply(CameraView& node);
+        virtual void apply(MatrixTransform& node);
+        virtual void apply(PositionAttitudeTransform& node);
+
+        virtual void apply(Switch& node);
+        virtual void apply(Sequence& node);
+        virtual void apply(LOD& node);
+        virtual void apply(PagedLOD& node);
+        virtual void apply(ClearNode& node);
+        virtual void apply(OccluderNode& node);
+        virtual void apply(OcclusionQueryNode& node);
+
+
+        /** Callback for managing database paging, such as generated by PagedLOD nodes.*/
+        class DatabaseRequestHandler : public osg::Referenced
+        {
+        public:
+        
+            DatabaseRequestHandler():
+                Referenced(true) {}
+        
+            virtual void requestNodeFile(const std::string& fileName,osg::Group* group, float priority, const FrameStamp* framestamp, osg::ref_ptr<osg::Referenced>& databaseRequest) = 0;
+            
+        protected:
+            virtual ~DatabaseRequestHandler() {}
+        };
+        
+        /** Set the handler for database requests.*/
+        void setDatabaseRequestHandler(DatabaseRequestHandler* handler) { _databaseRequestHandler = handler; }
+        
+        /** Get the handler for database requests.*/
+        DatabaseRequestHandler* getDatabaseRequestHandler() { return _databaseRequestHandler.get(); }
+
+        /** Get the const handler for database requests.*/
+        const DatabaseRequestHandler* getDatabaseRequestHandler() const { return _databaseRequestHandler.get(); }
+
+
+        /** Callback for managing database paging, such as generated by PagedLOD nodes.*/
+        class ImageRequestHandler : public osg::Referenced
+        {
+        public:
+        
+            ImageRequestHandler():
+                Referenced(true) {}
+
+            virtual double getPreLoadTime() const = 0;
+            
+            virtual osg::Image* readImageFile(const std::string& fileName) = 0;
+        
+            virtual void requestImageFile(const std::string& fileName,osg::Object* attachmentPoint, int attachmentIndex, double timeToMergeBy, const FrameStamp* framestamp) = 0;
+            
+        protected:
+            virtual ~ImageRequestHandler() {}
+        };
+        
+        /** Set the handler for image requests.*/
+        void setImageRequestHandler(ImageRequestHandler* handler) { _imageRequestHandler = handler; }
+        
+        /** Get the handler for image requests.*/
+        ImageRequestHandler* getImageRequestHandler() { return _imageRequestHandler.get(); }
+
+        /** Get the const handler for image requests.*/
+        const ImageRequestHandler* getImageRequestHandler() const { return _imageRequestHandler.get(); }
+
+
+
+    protected:
+
+        VisitorType                     _visitorType;
+        int                             _traversalNumber;
+        
+        ref_ptr<FrameStamp>             _frameStamp;
+        
+        TraversalMode                   _traversalMode;
+        Node::NodeMask                  _traversalMask;
+        Node::NodeMask                  _nodeMaskOverride;
+        
+        NodePath                        _nodePath;
+
+        ref_ptr<Referenced>             _userData;
+
+        ref_ptr<DatabaseRequestHandler> _databaseRequestHandler;
+        ref_ptr<ImageRequestHandler>    _imageRequestHandler;
+
+};
+
+
+/** Convenience functor for assisting visiting of arrays of osg::Node's.*/ 
+class NodeAcceptOp
+{
+    public:
+
+        NodeAcceptOp(NodeVisitor& nv):_nv(nv) {}
+        NodeAcceptOp(const NodeAcceptOp& naop):_nv(naop._nv) {}
+
+        void operator () (Node* node) { node->accept(_nv); }
+        void operator () (ref_ptr<Node> node) { node->accept(_nv); }
+
+    protected:
+
+        NodeAcceptOp& operator = (const NodeAcceptOp&) { return *this; }
+
+        NodeVisitor& _nv;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Object
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Object (revision 8911)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Object (revision 8911)
@@ -0,0 +1,174 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_OBJECT
+#define OSG_OBJECT 1
+
+#include <osg/Referenced>
+#include <osg/CopyOp>
+#include <osg/ref_ptr>
+
+#include <string>
+
+namespace osg {
+
+// forward declare
+class State;
+
+#define _ADDQUOTES(def) #def
+#define ADDQUOTES(def) _ADDQUOTES(def)
+
+/** META_Object macro define the standard clone, isSameKindAs and className methods.
+  * Use when subclassing from Object to make it more convenient to define 
+  * the standard pure virtual clone, isSameKindAs and className methods 
+  * which are required for all Object subclasses.*/
+#define META_Object(library,name) \
+        virtual osg::Object* cloneType() const { return new name (); } \
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const name *>(obj)!=NULL; } \
+        virtual const char* libraryName() const { return #library; }\
+        virtual const char* className() const { return #name; }
+
+template<typename T>
+T* clone(const T* t, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY)
+{
+    return dynamic_cast<T*>(t->clone(copyop)); 
+}
+
+
+template<typename T>
+T* clone(const T* t, const std::string& name, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY)
+{
+    T* newObject = dynamic_cast<T*>(t->clone(copyop)); 
+    newObject->setName(name);
+    return newObject;
+}
+
+/** Base class/standard interface for objects which require IO support, 
+    cloning and reference counting.
+    Based on GOF Composite, Prototype and Template Method patterns.
+*/
+class OSG_EXPORT Object : public Referenced
+{
+    public:
+
+
+        /** Construct an object. Note Object is a pure virtual base class
+            and therefore cannot be constructed on its own, only derived
+            classes which override the clone and className methods are
+            concrete classes and can be constructed.*/
+        inline Object():Referenced(),_dataVariance(UNSPECIFIED) {}
+
+        inline explicit Object(bool threadSafeRefUnref):Referenced(threadSafeRefUnref),_dataVariance(UNSPECIFIED) {}
+
+        /** Copy constructor, optional CopyOp object can be used to control
+          * shallow vs deep copying of dynamic data.*/
+        Object(const Object&,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        /** Clone the type of an object, with Object* return type.
+            Must be defined by derived classes.*/
+        virtual Object* cloneType() const = 0;
+
+        /** Clone an object, with Object* return type.
+            Must be defined by derived classes.*/
+        virtual Object* clone(const CopyOp&) const = 0;
+
+        virtual bool isSameKindAs(const Object*) const { return true; }
+
+        /** return the name of the object's library. Must be defined
+            by derived classes. The OpenSceneGraph convention is that the
+            namespace of a library is the same as the library name.*/
+        virtual const char* libraryName() const = 0;
+
+        /** return the name of the object's class type. Must be defined
+            by derived classes.*/
+        virtual const char* className() const = 0;
+        
+
+        /** Set the name of object using C++ style string.*/
+        inline void setName( const std::string& name ) { _name = name; }
+
+        /** Set the name of object using a C style string.*/
+        inline void setName( const char* name ) { _name = name; }
+
+        /** Get the name of object.*/
+        inline const std::string& getName() const { return _name; }
+
+
+        enum DataVariance
+        {
+            DYNAMIC,
+            STATIC,
+            UNSPECIFIED
+        };
+        
+        /** Set the data variance of this object.
+           * Can be set to either STATIC for values that do not change over the lifetime of the object,
+           * or DYNAMIC for values that vary over the lifetime of the object. The DataVariance value
+           * can be used by routines such as optimization codes that wish to share static data.
+           * UNSPECIFIED is used to specify that the DataVariance hasn't been set yet. */
+        inline void setDataVariance(DataVariance dv) { _dataVariance = dv; }
+
+        /** Get the data variance of this object.*/
+        inline DataVariance getDataVariance() const { return _dataVariance; }
+        
+        /** Compute the DataVariance based on an assessment of callback etc.*/
+        virtual void computeDataVariance() {}
+
+
+        /**
+         * Set user data, data must be subclassed from Referenced to allow
+         * automatic memory handling.  If your own data isn't directly 
+         * subclassed from Referenced then create an adapter object
+         * which points to your own object and handles the memory addressing.
+         */
+        inline void setUserData(Referenced* obj) { _userData = obj; }
+        
+        /** Get user data.*/
+        inline Referenced* getUserData() { return _userData.get(); }
+        
+        /** Get const user data.*/
+        inline const Referenced* getUserData() const { return _userData.get(); }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {}
+
+        /** If State is non-zero, this function releases any associated OpenGL objects for
+           * the specified graphics context. Otherwise, releases OpenGL objects
+           * for all graphics contexts. */
+        virtual void releaseGLObjects(osg::State* = 0) const {}
+
+    protected:
+
+        /** Object destructor. Note, is protected so that Objects cannot
+            be deleted other than by being dereferenced and the reference
+            count being zero (see osg::Referenced), preventing the deletion
+            of nodes which are still in use. This also means that
+            Nodes cannot be created on stack i.e Node node will not compile,
+            forcing all nodes to be created on the heap i.e Node* node
+            = new Node().*/
+        virtual ~Object() {}
+        
+        std::string _name;
+        DataVariance _dataVariance;
+        ref_ptr<Referenced> _userData;
+
+    private:
+
+        /** disallow any copy operator.*/
+        Object& operator = (const Object&) { return *this; }
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Light
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Light (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Light (revision 7648)
@@ -0,0 +1,184 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_LIGHT
+#define OSG_LIGHT 1
+
+#include <osg/StateAttribute>
+#include <osg/Vec3>
+#include <osg/Vec4>
+
+namespace osg {
+
+/** Light state class which encapsulates OpenGL glLight() functionality. */
+class OSG_EXPORT Light : public StateAttribute
+{
+    public :
+
+        Light();
+
+        Light(unsigned int lightnum);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Light(const Light& light,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(light,copyop),
+            _lightnum(light._lightnum),
+            _ambient(light._ambient),
+            _diffuse(light._diffuse),
+            _specular(light._specular),
+            _position(light._position),
+            _direction(light._direction),
+            _constant_attenuation(light._constant_attenuation),
+            _linear_attenuation(light._linear_attenuation),
+            _quadratic_attenuation(light._quadratic_attenuation),
+            _spot_exponent(light._spot_exponent),
+            _spot_cutoff(light._spot_cutoff) {}
+        
+        virtual osg::Object* cloneType() const { return new Light(_lightnum); }
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new Light(*this,copyop); }
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const Light *>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Light"; }
+        virtual Type getType() const { return LIGHT; }
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(Light,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_lightnum)
+            COMPARE_StateAttribute_Parameter(_ambient)
+            COMPARE_StateAttribute_Parameter(_diffuse)
+            COMPARE_StateAttribute_Parameter(_specular)
+            COMPARE_StateAttribute_Parameter(_position)
+            COMPARE_StateAttribute_Parameter(_direction)
+            COMPARE_StateAttribute_Parameter(_constant_attenuation)
+            COMPARE_StateAttribute_Parameter(_linear_attenuation)
+            COMPARE_StateAttribute_Parameter(_quadratic_attenuation)
+            COMPARE_StateAttribute_Parameter(_spot_exponent)
+            COMPARE_StateAttribute_Parameter(_spot_cutoff)
+
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+        virtual unsigned int getMember() const { return _lightnum; }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_LIGHT0+_lightnum);
+            return true;
+        }
+        
+        
+
+        /** Set which OpenGL light to operate on. */
+        void setLightNum(int num);
+        
+        /** Get which OpenGL light this osg::Light operates on. */
+        int getLightNum() const { return _lightnum; }
+
+        /** Set the ambient component of the light. */
+        inline void setAmbient( const Vec4& ambient ) { _ambient = ambient; }
+
+        /** Get the ambient component of the light. */
+        inline const Vec4& getAmbient() const { return _ambient; }
+
+        /** Set the diffuse component of the light. */
+        inline void setDiffuse( const Vec4& diffuse ) { _diffuse = diffuse; }
+
+        /** Get the diffuse component of the light. */
+        inline const Vec4& getDiffuse() const { return _diffuse; }
+
+        /** Set the specular component of the light. */
+        inline void setSpecular( const Vec4& specular ) { _specular = specular; }
+
+        /** Get the specular component of the light. */
+        inline const Vec4& getSpecular() const { return _specular; }
+
+        /** Set the position of the light. */    
+        inline void setPosition( const Vec4& position ) { _position = position; }
+
+        /** Get the position of the light. */    
+        inline const Vec4& getPosition() const { return _position; }
+
+        /** Set the direction of the light. */    
+        inline void setDirection( const Vec3& direction ) { _direction = direction; }
+
+        /** Get the direction of the light. */    
+        inline const Vec3& getDirection() const { return _direction; }
+
+        /** Set the constant attenuation of the light. */
+        inline void setConstantAttenuation( float constant_attenuation )     { _constant_attenuation = constant_attenuation; }
+
+        /** Get the constant attenuation of the light. */
+        inline float getConstantAttenuation() const { return _constant_attenuation; }
+
+        /** Set the linear attenuation of the light. */
+        inline void setLinearAttenuation ( float linear_attenuation )        { _linear_attenuation = linear_attenuation; }
+
+        /** Get the linear attenuation of the light. */
+        inline float getLinearAttenuation () const { return _linear_attenuation; }
+
+        /** Set the quadratic attenuation of the light. */
+        inline void setQuadraticAttenuation ( float quadratic_attenuation )  { _quadratic_attenuation = quadratic_attenuation; }
+
+        /** Get the quadratic attenuation of the light. */
+        inline float getQuadraticAttenuation()  const { return _quadratic_attenuation; }
+
+        /** Set the spot exponent of the light. */
+        inline void setSpotExponent( float spot_exponent )                   { _spot_exponent = spot_exponent; }
+
+        /** Get the spot exponent of the light. */
+        inline float getSpotExponent() const { return _spot_exponent; }
+
+        /** Set the spot cutoff of the light. */
+        inline void setSpotCutoff( float spot_cutoff )                       { _spot_cutoff = spot_cutoff; }
+
+        /** Get the spot cutoff of the light. */
+        inline float getSpotCutoff() const                                   { return _spot_cutoff; }
+
+        /** Capture the lighting settings of the current OpenGL state
+          * and store them in this object.
+        */
+        void captureLightState();
+
+        /** Apply the light's state to the OpenGL state machine. */
+        virtual void apply(State& state) const;
+
+    protected :
+    
+        virtual ~Light();
+
+        /** Initialize the light's settings with some decent defaults. */
+        void init();
+
+        int _lightnum;                           // OpenGL light number
+
+        Vec4 _ambient;                           // r, g, b, w
+        Vec4 _diffuse;                           // r, g, b, w
+        Vec4 _specular;                          // r, g, b, w
+        Vec4 _position;                          // x, y, z, w
+        Vec3 _direction;                         // x, y, z
+        float _constant_attenuation;             // constant
+        float _linear_attenuation;               // linear
+        float _quadratic_attenuation;            // quadratic
+        float _spot_exponent;                    // exponent
+        float _spot_cutoff;                      // spread
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrontFace
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrontFace (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrontFace (revision 7648)
@@ -0,0 +1,70 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_FRONTFACE
+#define OSG_FRONTFACE 1
+
+#include <osg/StateAttribute>
+#include <osg/GL>
+
+namespace osg {
+
+/** Class to specify the orientation of front-facing polygons.
+*/     
+class OSG_EXPORT FrontFace : public StateAttribute
+{
+    public :
+    
+        enum Mode {
+            CLOCKWISE = GL_CW,
+            COUNTER_CLOCKWISE = GL_CCW
+        };
+        
+        FrontFace(Mode face=COUNTER_CLOCKWISE);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        FrontFace(const FrontFace& ff,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(ff,copyop),
+            _mode(ff._mode) {}
+
+        META_StateAttribute(osg, FrontFace, FRONTFACE);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(FrontFace,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_mode)
+
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+    
+        inline void setMode(Mode mode) { _mode = mode; }
+        inline Mode getMode() const    { return _mode; }
+    
+        virtual void apply(State& state) const;
+        
+    protected:
+    
+        virtual ~FrontFace();
+        
+        Mode _mode;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameBufferObject
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameBufferObject (revision 9239)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameBufferObject (revision 9239)
@@ -0,0 +1,484 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+// initial FBO support written by Marco Jez, June 2005.
+
+#ifndef OSG_FRAMEBUFFEROBJECT
+#define OSG_FRAMEBUFFEROBJECT 1
+
+#include <osg/GL>
+#include <osg/Texture>
+#include <osg/buffered_value>
+#include <osg/Camera>
+
+#ifndef GL_EXT_framebuffer_object
+#define GL_EXT_framebuffer_object 1
+#define GL_FRAMEBUFFER_EXT                     0x8D40
+#define GL_RENDERBUFFER_EXT                    0x8D41
+// #define GL_STENCIL_INDEX_EXT                   0x8D45  // removed in rev. #114 of the spec
+#define GL_STENCIL_INDEX1_EXT                  0x8D46
+#define GL_STENCIL_INDEX4_EXT                  0x8D47
+#define GL_STENCIL_INDEX8_EXT                  0x8D48
+#define GL_STENCIL_INDEX16_EXT                 0x8D49
+#define GL_RENDERBUFFER_WIDTH_EXT              0x8D42
+#define GL_RENDERBUFFER_HEIGHT_EXT             0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT    0x8D44
+#define GL_RENDERBUFFER_RED_SIZE_EXT           0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE_EXT         0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE_EXT          0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE_EXT         0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE_EXT         0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE_EXT       0x8D55
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT            0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT            0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT          0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT  0x8CD3
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT     0x8CD4
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT          0x8CD4
+#define GL_COLOR_ATTACHMENT0_EXT                0x8CE0
+#define GL_COLOR_ATTACHMENT1_EXT                0x8CE1
+#define GL_COLOR_ATTACHMENT2_EXT                0x8CE2
+#define GL_COLOR_ATTACHMENT3_EXT                0x8CE3
+#define GL_COLOR_ATTACHMENT4_EXT                0x8CE4
+#define GL_COLOR_ATTACHMENT5_EXT                0x8CE5
+#define GL_COLOR_ATTACHMENT6_EXT                0x8CE6
+#define GL_COLOR_ATTACHMENT7_EXT                0x8CE7
+#define GL_COLOR_ATTACHMENT8_EXT                0x8CE8
+#define GL_COLOR_ATTACHMENT9_EXT                0x8CE9
+#define GL_COLOR_ATTACHMENT10_EXT               0x8CEA
+#define GL_COLOR_ATTACHMENT11_EXT               0x8CEB
+#define GL_COLOR_ATTACHMENT12_EXT               0x8CEC
+#define GL_COLOR_ATTACHMENT13_EXT               0x8CED
+#define GL_COLOR_ATTACHMENT14_EXT               0x8CEE
+#define GL_COLOR_ATTACHMENT15_EXT               0x8CEF
+#define GL_DEPTH_ATTACHMENT_EXT                 0x8D00
+#define GL_STENCIL_ATTACHMENT_EXT               0x8D20
+#define GL_FRAMEBUFFER_COMPLETE_EXT                          0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT             0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT     0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT   0x8CD8
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT             0x8CD9
+#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT                0x8CDA
+#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT            0x8CDB
+#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT            0x8CDC
+#define GL_FRAMEBUFFER_UNSUPPORTED_EXT                       0x8CDD
+#define GL_FRAMEBUFFER_BINDING_EXT             0x8CA6
+#define GL_RENDERBUFFER_BINDING_EXT            0x8CA7
+#define GL_MAX_COLOR_ATTACHMENTS_EXT           0x8CDF
+#define GL_MAX_RENDERBUFFER_SIZE_EXT           0x84E8
+#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT   0x0506
+#endif
+
+#ifndef GL_EXT_framebuffer_blit
+#define GL_EXT_framebuffer_blit 1
+#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6
+#define GL_READ_FRAMEBUFFER_EXT 0x8CA8
+#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9
+#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA
+#endif
+
+#ifndef GL_EXT_framebuffer_multisample
+#define GL_EXT_framebuffer_multisample 1
+#define GL_RENDERBUFFER_SAMPLES_EXT                 0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT   0x8D56
+#define GL_MAX_SAMPLES_EXT                          0x8D57
+#endif
+
+#ifndef GL_MAX_SAMPLES_EXT
+// Workaround for Centos 5 and other distros that define
+// GL_EXT_framebuffer_multisample but not GL_MAX_SAMPLES_EXT
+#define GL_MAX_SAMPLES_EXT 0x8D57
+#endif
+
+#ifndef GL_NV_framebuffer_multisample_coverage
+#define GL_NV_framebuffer_multisample_coverage 1
+#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV     0x8CAB
+#define GL_RENDERBUFFER_COLOR_SAMPLES_NV        0x8E10
+#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV    0x8E11
+#define GL_MULTISAMPLE_COVERAGE_MODES_NV        0x8E12
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_DEPTH_COMPONENT24              0x81A6
+#define GL_DEPTH_COMPONENT32              0x81A7
+#endif
+
+#ifndef GL_EXT_packed_depth_stencil
+#define GL_EXT_packed_depth_stencil 1
+#define GL_DEPTH_STENCIL_EXT 0x84F9
+#define GL_UNSIGNED_INT_24_8_EXT 0x84FA
+#define GL_DEPTH24_STENCIL8_EXT 0x88F0
+#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1
+#endif
+
+namespace osg
+{
+
+/**************************************************************************
+ * FBOExtensions
+ **************************************************************************/
+
+    class OSG_EXPORT FBOExtensions : public osg::Referenced
+    {
+    public:
+        typedef void APIENTRY TglBindRenderbufferEXT(GLenum, GLuint);
+        typedef void APIENTRY TglDeleteRenderbuffersEXT(GLsizei n, const GLuint *renderbuffers);
+        typedef void APIENTRY TglGenRenderbuffersEXT(GLsizei, GLuint *);
+        typedef void APIENTRY TglRenderbufferStorageEXT(GLenum, GLenum, GLsizei, GLsizei);
+        typedef void APIENTRY TglRenderbufferStorageMultisampleEXT(GLenum, GLsizei, GLenum, GLsizei, GLsizei);
+        typedef void APIENTRY TglRenderbufferStorageMultisampleCoverageNV(GLenum, GLsizei, GLsizei, GLenum, GLsizei, GLsizei);
+        typedef void APIENTRY TglBindFramebufferEXT(GLenum, GLuint);
+        typedef void APIENTRY TglDeleteFramebuffersEXT(GLsizei n, const GLuint *framebuffers);
+        typedef void APIENTRY TglGenFramebuffersEXT(GLsizei, GLuint *);
+        typedef GLenum APIENTRY TglCheckFramebufferStatusEXT(GLenum);
+        typedef void APIENTRY TglFramebufferTexture1DEXT(GLenum, GLenum, GLenum, GLuint, GLint);
+        typedef void APIENTRY TglFramebufferTexture2DEXT(GLenum, GLenum, GLenum, GLuint, GLint);
+        typedef void APIENTRY TglFramebufferTexture3DEXT(GLenum, GLenum, GLenum, GLuint, GLint, GLint);
+        typedef void APIENTRY TglFramebufferTextureLayerEXT(GLenum, GLenum, GLuint, GLint, GLint);
+        typedef void APIENTRY TglFramebufferRenderbufferEXT(GLenum, GLenum, GLenum, GLuint);
+        typedef void APIENTRY TglGenerateMipmapEXT(GLenum);
+        typedef void APIENTRY TglBlitFramebufferEXT(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum);
+
+        TglBindRenderbufferEXT* glBindRenderbufferEXT;
+        TglGenRenderbuffersEXT* glGenRenderbuffersEXT;
+        TglDeleteRenderbuffersEXT* glDeleteRenderbuffersEXT; 
+        TglRenderbufferStorageEXT* glRenderbufferStorageEXT;
+        TglRenderbufferStorageMultisampleEXT* glRenderbufferStorageMultisampleEXT;
+        TglRenderbufferStorageMultisampleCoverageNV* glRenderbufferStorageMultisampleCoverageNV;
+        TglBindFramebufferEXT* glBindFramebufferEXT;
+        TglDeleteFramebuffersEXT* glDeleteFramebuffersEXT;
+        TglGenFramebuffersEXT* glGenFramebuffersEXT;
+        TglCheckFramebufferStatusEXT* glCheckFramebufferStatusEXT;
+        TglFramebufferTexture1DEXT* glFramebufferTexture1DEXT;
+        TglFramebufferTexture2DEXT* glFramebufferTexture2DEXT;
+        TglFramebufferTexture3DEXT* glFramebufferTexture3DEXT;
+        TglFramebufferTextureLayerEXT* glFramebufferTextureLayerEXT;
+        TglFramebufferRenderbufferEXT* glFramebufferRenderbufferEXT;
+        TglGenerateMipmapEXT* glGenerateMipmapEXT;
+        TglBlitFramebufferEXT* glBlitFramebufferEXT;
+
+        static FBOExtensions* instance(unsigned contextID, bool createIfNotInitalized);
+
+        bool isSupported() const { return _supported; }
+        bool isMultisampleSupported() const { return glRenderbufferStorageMultisampleEXT != 0; }
+        bool isMultisampleCoverageSupported() const { return glRenderbufferStorageMultisampleCoverageNV != 0; }
+        bool isPackedDepthStencilSupported() const { return _packed_depth_stencil_supported; }
+
+    protected:
+        FBOExtensions(unsigned int contextID);
+
+        bool _supported;
+        bool _packed_depth_stencil_supported;
+    };
+
+/**************************************************************************
+ * RenderBuffer
+ **************************************************************************/
+
+    class OSG_EXPORT RenderBuffer: public Object
+    {
+    public:
+        RenderBuffer();
+        RenderBuffer(int width, int height, GLenum internalFormat, int samples=0, int colorSamples=0);
+        RenderBuffer(const RenderBuffer& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, RenderBuffer);
+
+        inline int getWidth() const;
+        inline int getHeight() const;
+        inline void setWidth(int w);
+        inline void setHeight(int h);
+        inline void setSize(int w, int h);
+        inline GLenum getInternalFormat() const;
+        inline void setInternalFormat(GLenum format);
+        inline int getSamples() const;
+        inline int getColorSamples() const;
+        inline void setSamples(int samples);
+        inline void setColorSamples(int colorSamples);
+
+        GLuint getObjectID(unsigned int contextID, const FBOExtensions *ext) const;
+        inline int compare(const RenderBuffer &rb) const;
+
+        /** Mark internal RenderBuffer for deletion.
+          * Deletion requests are queued until they can be executed
+          * in the proper GL context. */
+        static void deleteRenderBuffer(unsigned int contextID, GLuint rb);
+
+        /** flush all the cached RenderBuffers which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void flushDeletedRenderBuffers(unsigned int contextID,double currentTime, double& availableTime);
+
+        /** discard all the cached RenderBuffers which need to be deleted in the OpenGL context related to contextID.
+          * Note, unlike flush no OpenGL calls are made, instead the handles are all removed.
+          * this call is useful for when an OpenGL context has been destroyed. */
+        static void discardDeletedRenderBuffers(unsigned int contextID);
+
+        static int getMaxSamples(unsigned int contextID, const FBOExtensions *ext);
+
+    protected:
+        virtual ~RenderBuffer();
+        RenderBuffer &operator=(const RenderBuffer &) { return *this; }
+
+        inline void dirtyAll() const;
+
+    private:
+        mutable buffered_value<GLuint> _objectID;
+        mutable buffered_value<int> _dirty;
+
+        GLenum _internalFormat;
+        int _width;
+        int _height;
+        // "samples" in the framebuffer_multisample extension is equivalent to
+        // "coverageSamples" in the framebuffer_multisample_coverage extension.
+        int _samples;
+        int _colorSamples;
+    };
+
+    // INLINE METHODS
+
+    inline int RenderBuffer::getWidth() const
+    {
+        return _width;
+    }
+
+    inline int RenderBuffer::getHeight() const
+    {
+        return _height;
+    }
+
+    inline void RenderBuffer::setWidth(int w)
+    {
+        _width = w;
+        dirtyAll();
+    }
+
+    inline void RenderBuffer::setHeight(int h)
+    {
+        _height = h;
+        dirtyAll();
+    }
+
+    inline void RenderBuffer::setSize(int w, int h)
+    {
+        _width = w;
+        _height = h;
+        dirtyAll();
+    }
+
+    inline GLenum RenderBuffer::getInternalFormat() const
+    {
+        return _internalFormat;
+    }
+
+    inline void RenderBuffer::setInternalFormat(GLenum format)
+    {
+        _internalFormat = format;
+        dirtyAll();
+    }
+
+    inline int RenderBuffer::getSamples() const
+    {
+        return _samples;
+    }
+
+    inline int RenderBuffer::getColorSamples() const
+    {
+        return _colorSamples;
+    }
+
+    inline void RenderBuffer::setSamples(int samples)
+    {
+        _samples = samples;
+        dirtyAll();
+    }
+
+    inline void RenderBuffer::setColorSamples(int colorSamples)
+    {
+        _colorSamples = colorSamples;
+        dirtyAll();
+    }
+
+    inline void RenderBuffer::dirtyAll() const
+    {
+        _dirty.setAllElementsTo(1);
+    }
+
+    inline int RenderBuffer::compare(const RenderBuffer &rb) const
+    {
+        if (&rb == this) return 0;
+        if (_internalFormat < rb._internalFormat) return -1;
+        if (_internalFormat > rb._internalFormat) return 1;
+        if (_width < rb._width) return -1;
+        if (_width > rb._width) return 1;
+        if (_height < rb._height) return -1;
+        if (_height > rb._height) return 1;
+        return 0;
+    }
+
+/**************************************************************************
+ * FrameBufferAttachement
+ **************************************************************************/
+    class Texture1D;
+    class Texture2D;
+    class Texture3D;
+    class Texture2DArray;
+    class TextureCubeMap;
+    class TextureRectangle;
+
+    class OSG_EXPORT FrameBufferAttachment
+    {
+    public:
+        FrameBufferAttachment();
+        FrameBufferAttachment(const FrameBufferAttachment& copy);
+
+        explicit FrameBufferAttachment(RenderBuffer* target);
+        explicit FrameBufferAttachment(Texture1D* target, int level = 0);
+        explicit FrameBufferAttachment(Texture2D* target, int level = 0);
+        explicit FrameBufferAttachment(Texture3D* target, int zoffset, int level = 0);
+        explicit FrameBufferAttachment(Texture2DArray* target, int layer, int level = 0);
+        explicit FrameBufferAttachment(TextureCubeMap* target, int face, int level = 0);
+        explicit FrameBufferAttachment(TextureRectangle* target);
+        explicit FrameBufferAttachment(Camera::Attachment& attachment);
+        
+        ~FrameBufferAttachment();
+
+        FrameBufferAttachment&operator = (const FrameBufferAttachment& copy);        
+
+        bool isMultisample() const;
+        void createRequiredTexturesAndApplyGenerateMipMap(State& state, const FBOExtensions* ext) const;
+        void attach(State &state, GLenum target, GLenum attachment_point, const FBOExtensions* ext) const;
+        int compare(const FrameBufferAttachment &fa) const;
+
+        RenderBuffer* getRenderBuffer();
+        const RenderBuffer* getRenderBuffer() const;
+
+        Texture* getTexture();
+        const Texture* getTexture() const;
+
+        int getCubeMapFace() const;
+        int getTextureLevel() const;
+        int getTexture3DZOffset() const;
+        int getTextureArrayLayer() const;
+
+    private:
+        // use the Pimpl idiom to avoid dependency from
+        // all Texture* headers
+        struct Pimpl;
+        Pimpl* _ximpl;
+    };
+
+/**************************************************************************
+ * FrameBufferObject
+ **************************************************************************/
+    class OSG_EXPORT FrameBufferObject: public StateAttribute
+    {
+    public:
+        typedef std::map<Camera::BufferComponent, FrameBufferAttachment> AttachmentMap;
+        typedef std::vector<GLenum> MultipleRenderingTargets;
+        
+        typedef Camera::BufferComponent BufferComponent;
+
+        FrameBufferObject();
+        FrameBufferObject(const FrameBufferObject& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osg, FrameBufferObject, (StateAttribute::Type)0x101010/*FrameBufferObject*/);
+
+        inline const AttachmentMap& getAttachmentMap() const;
+        
+
+        void setAttachment(BufferComponent attachment_point, const FrameBufferAttachment &attachment);
+        inline const FrameBufferAttachment& getAttachment(BufferComponent attachment_point) const;
+        inline bool hasAttachment(BufferComponent attachment_point) const;
+        
+        inline bool hasMultipleRenderingTargets() const { return !_drawBuffers.empty(); }
+        inline const MultipleRenderingTargets& getMultipleRenderingTargets() const { return _drawBuffers; }
+
+        bool isMultisample() const;
+
+        int compare(const StateAttribute &sa) const;
+        
+        void apply(State &state) const;
+
+        enum BindTarget
+        {
+            READ_FRAMEBUFFER = GL_READ_FRAMEBUFFER_EXT,
+            DRAW_FRAMEBUFFER = GL_DRAW_FRAMEBUFFER_EXT,
+            READ_DRAW_FRAMEBUFFER = GL_FRAMEBUFFER_EXT
+        };
+
+        /** Bind the FBO as either the read or draw target, or both. */
+        void apply(State &state, BindTarget target) const;
+
+        /** Mark internal FBO for deletion.
+          * Deletion requests are queued until they can be executed
+          * in the proper GL context. */
+        static void deleteFrameBufferObject(unsigned int contextID, GLuint program);
+
+        /** flush all the cached FBOs which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void flushDeletedFrameBufferObjects(unsigned int contextID,double currentTime, double& availableTime);
+
+        /** discard all the cached FBOs which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void discardDeletedFrameBufferObjects(unsigned int contextID);
+
+    protected:
+        virtual ~FrameBufferObject();
+        FrameBufferObject& operator = (const FrameBufferObject&) { return *this; }
+
+        void updateDrawBuffers();
+        
+        inline void dirtyAll();
+
+        GLenum convertBufferComponentToGLenum(BufferComponent attachment_point) const;
+
+    private:        
+        AttachmentMap               _attachments;
+
+        // Buffers passed to glDrawBuffers when using multiple render targets.
+        MultipleRenderingTargets    _drawBuffers;
+
+        mutable buffered_value<int>         _dirtyAttachmentList;
+        mutable buffered_value<int>         _unsupported;
+        mutable buffered_value<GLuint>      _fboID;
+        
+    };
+
+    // INLINE METHODS
+
+    inline const FrameBufferObject::AttachmentMap &FrameBufferObject::getAttachmentMap() const
+    {
+        return _attachments;
+    }
+
+    inline bool FrameBufferObject::hasAttachment(FrameBufferObject::BufferComponent attachment_point) const
+    {
+        return _attachments.find(attachment_point) != _attachments.end();
+    }
+
+    inline const FrameBufferAttachment &FrameBufferObject::getAttachment(FrameBufferObject::BufferComponent attachment_point) const
+    {
+        return _attachments.find(attachment_point)->second;
+    }
+
+    inline void FrameBufferObject::dirtyAll()
+    {
+        _dirtyAttachmentList.setAllElementsTo(1);
+    }
+
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/observer_ptr
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/observer_ptr (revision 7944)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/observer_ptr (revision 7944)
@@ -0,0 +1,94 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_OBSERVER_PTR
+#define OSG_OBSERVER_PTR
+
+#include <osg/Notify>
+
+namespace osg {
+
+class Observer
+{
+public:
+    virtual ~Observer() {}
+    virtual void objectDeleted(void*) {}
+};
+
+/** Smart pointer for observed objects, that automatically set pointers to them to null when they deleted.*/
+template<class T>
+class observer_ptr : public Observer
+{
+
+    public:
+        typedef T element_type;
+
+        observer_ptr() :_ptr(0L)                            {}
+        observer_ptr(T* t):_ptr(t)                          { if (_ptr) _ptr->addObserver(this); }
+        observer_ptr(const observer_ptr& rp):Observer(), _ptr(rp._ptr)  { if (_ptr) _ptr->addObserver(this); }
+        ~observer_ptr()                                     { if (_ptr) _ptr->removeObserver(this); _ptr=0; }
+
+        inline observer_ptr& operator = (const observer_ptr& rp)
+        {
+            if (_ptr==rp._ptr) return *this;
+            if (_ptr) _ptr->removeObserver(this);
+            
+            _ptr = rp._ptr;
+            if (_ptr) _ptr->addObserver(this);
+            return *this;
+        }
+
+        inline observer_ptr& operator = (T* ptr)
+        {
+            if (_ptr==ptr) return *this;
+            if (_ptr) _ptr->removeObserver(this);
+            
+            _ptr = ptr;
+            if (_ptr) _ptr->addObserver(this);
+
+            return *this;
+        }
+        
+        virtual void objectDeleted(void*)
+        {
+            _ptr = 0;
+        }
+
+        // comparison operators for observer_ptr.
+        inline bool operator == (const observer_ptr& rp) const { return (_ptr==rp._ptr); }
+        inline bool operator != (const observer_ptr& rp) const { return (_ptr!=rp._ptr); }
+        inline bool operator < (const observer_ptr& rp) const { return (_ptr<rp._ptr); }
+        inline bool operator > (const observer_ptr& rp) const { return (_ptr>rp._ptr); }
+
+        // comparison operator for const T*.
+        inline bool operator == (const T* ptr) const { return (_ptr==ptr); }
+        inline bool operator != (const T* ptr) const { return (_ptr!=ptr); }
+        inline bool operator < (const T* ptr) const { return (_ptr<ptr); }
+        inline bool operator > (const T* ptr) const { return (_ptr>ptr); }
+
+        inline T& operator*() const { return *_ptr; }
+        inline T* operator->() const   { return _ptr; }
+        inline T* get() const { return _ptr; }
+
+        inline bool operator!() const   { return _ptr==0L; }
+
+        inline bool valid() const       { return _ptr!=0L; }
+        
+
+    private:
+        T* _ptr;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BoundingSphere
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BoundingSphere (revision 10233)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/BoundingSphere (revision 10233)
@@ -0,0 +1,306 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_BOUNDINGSPHERE
+#define OSG_BOUNDINGSPHERE 1
+
+#include <osg/Config>
+#include <osg/Export>
+#include <osg/Vec3f>
+#include <osg/Vec3d>
+
+namespace osg {
+
+template<typename VT>
+class BoundingBoxImpl;
+
+/** General purpose bounding sphere class for enclosing nodes/objects/vertices.
+  * Bounds internal osg::Nodes in the scene, assists in view frustum culling,
+  * etc. Similar in function to BoundingBox, it's quicker for evaluating
+  * culling but generally will not cull as aggressively because it encloses a
+  * greater volume.
+*/
+template<typename VT>
+class BoundingSphereImpl
+{
+    public:
+        typedef VT vec_type;
+        typedef typename VT::value_type value_type;        
+
+        vec_type    _center;
+        value_type  _radius;
+
+        /** Construct a default bounding sphere with radius to -1.0f, representing an invalid/unset bounding sphere.*/ 
+        BoundingSphereImpl() : _center(0.0,0.0,0.0),_radius(-1.0) {}
+    
+        /** Creates a bounding sphere initialized to the given extents. */
+        BoundingSphereImpl(const vec_type& center, value_type radius) : _center(center),_radius(radius) {}
+
+        /** Creates a bounding sphere initialized to the given extents. */
+        BoundingSphereImpl(const BoundingSphereImpl& bs) : _center(bs._center),_radius(bs._radius) {}
+
+        /** Creates a bounding sphere initialized to the given extents. */
+        BoundingSphereImpl(const BoundingBoxImpl<VT>& bb) : _center(0.0,0.0,0.0),_radius(-1.0) { expandBy(bb); }
+
+        /** Clear the bounding sphere. Reset to default values. */
+        inline void init()
+        {
+            _center.set(0.0,0.0,0.0);
+            _radius = -1.0;
+        }
+
+        /** Returns true of the bounding sphere extents are valid, false
+          * otherwise. */
+        inline bool valid() const { return _radius>=0.0; }
+
+        /** Set the bounding sphere to the given center/radius using floats. */ 
+        inline void set(const vec_type& center,value_type radius)
+        {
+            _center = center;
+            _radius = radius;
+        }
+
+        /** Returns the center of the bounding sphere. */
+        inline vec_type& center() { return _center; }
+        
+        /** Returns the const center of the bounding sphere. */
+        inline const vec_type& center() const { return _center; }
+
+        /** Returns the radius of the bounding sphere. */
+        inline value_type& radius() { return _radius; }
+        /** Returns the const radius of the bounding sphere. */
+        inline value_type radius() const { return _radius; }
+        
+        /** Returns the squared length of the radius. Note, For performance
+          * reasons, the calling method is responsible for checking to make
+          * sure the sphere is valid. */
+        inline value_type radius2() const { return _radius*_radius; }
+
+        /** Expands the sphere to encompass the given point. Repositions the
+          * sphere center to minimize the radius increase. If the sphere is
+          * uninitialized, set its center to v and radius to zero. */
+        template<typename vector_type>
+        void expandBy(const vector_type& v);
+
+        /** Expands the sphere to encompass the given point. Does not
+          * reposition the sphere center. If the sphere is
+          * uninitialized, set its center to v and radius to zero. */
+        template<typename vector_type>
+        void expandRadiusBy(const vector_type& v);
+
+        /** Expands the sphere to encompass the given sphere. Repositions the
+          * sphere center to minimize the radius increase. If the sphere is
+          * uninitialized, set its center and radius to match sh. */
+        void expandBy(const BoundingSphereImpl& sh);
+
+        /** Expands the sphere to encompass the given sphere. Does not
+          * repositions the sphere center. If the sphere is
+          * uninitialized, set its center and radius to match sh. */
+        void expandRadiusBy(const BoundingSphereImpl& sh);
+
+        /** Expands the sphere to encompass the given box. Repositions the
+          * sphere center to minimize the radius increase. */
+        void expandBy(const BoundingBoxImpl<VT>& bb);
+
+        /** Expands the sphere to encompass the given box. Does not
+          * repositions the sphere center. */
+        void expandRadiusBy(const BoundingBoxImpl<VT>& bb);
+
+        /** Returns true if v is within the sphere. */
+        inline bool contains(const vec_type& v) const
+        {
+            return valid() && ((v-_center).length2()<=radius2());
+        }
+
+
+        /** Returns true if there is a non-empty intersection with the given
+          * bounding sphere. */
+        inline bool intersects( const BoundingSphereImpl& bs ) const
+        {
+            return valid() && bs.valid() &&
+                   ((_center - bs._center).length2() <= (_radius + bs._radius)*(_radius + bs._radius));
+        }
+        
+};
+
+
+template<typename VT>
+ template<typename vector_type>
+void BoundingSphereImpl<VT>::expandBy(const vector_type& v)
+{
+    if (valid())
+    {
+        vec_type dv = v-_center;
+        value_type r = dv.length();
+        if (r>_radius)
+        {
+            value_type dr = (r-_radius)*0.5;
+            _center += dv*(dr/r);
+            _radius += dr;
+        } // else do nothing as vertex is within sphere.
+    }
+    else
+    {
+        _center = v;
+        _radius = 0.0;
+    }
+}
+
+template<typename VT>
+ template<typename vector_type>
+void BoundingSphereImpl<VT>::expandRadiusBy(const vector_type& v)
+{
+    if (valid())
+    {
+        value_type r = (v-_center).length();
+        if (r>_radius) _radius = r;
+        // else do nothing as vertex is within sphere.
+    }
+    else
+    {
+        _center = v;
+        _radius = 0.0;
+    }
+}
+
+template<typename VT>
+void BoundingSphereImpl<VT>::expandBy(const BoundingSphereImpl& sh)
+{
+    // ignore operation if incomming BoundingSphere is invalid.
+    if (!sh.valid()) return;
+
+    // This sphere is not set so use the inbound sphere
+    if (!valid())
+    {
+        _center = sh._center;
+        _radius = sh._radius;
+
+        return;
+    }
+    
+    
+    // Calculate d == The distance between the sphere centers   
+    double d = ( _center - sh.center() ).length();
+
+    // New sphere is already inside this one
+    if ( d + sh.radius() <= _radius )  
+    {
+        return;
+    }
+
+    //  New sphere completely contains this one 
+    if ( d + _radius <= sh.radius() )  
+    {
+        _center = sh._center;
+        _radius = sh._radius;
+        return;
+    }
+
+    
+    // Build a new sphere that completely contains the other two:
+    //
+    // The center point lies halfway along the line between the furthest
+    // points on the edges of the two spheres.
+    //
+    // Computing those two points is ugly - so we'll use similar triangles
+    double new_radius = (_radius + d + sh.radius() ) * 0.5;
+    double ratio = ( new_radius - _radius ) / d ;
+
+    _center[0] += ( sh.center()[0] - _center[0] ) * ratio;
+    _center[1] += ( sh.center()[1] - _center[1] ) * ratio;
+    _center[2] += ( sh.center()[2] - _center[2] ) * ratio;
+
+    _radius = new_radius;
+
+}
+
+template<typename VT>
+void BoundingSphereImpl<VT>::expandRadiusBy(const BoundingSphereImpl& sh)
+{
+    if (sh.valid())
+    {
+        if (valid())
+        {
+            value_type r = (sh._center-_center).length()+sh._radius;
+            if (r>_radius) _radius = r;
+            // else do nothing as vertex is within sphere.
+        }
+        else
+        {
+            _center = sh._center;
+            _radius = sh._radius;
+        }
+    }
+}
+
+template<typename VT>        
+void BoundingSphereImpl<VT>::expandBy(const BoundingBoxImpl<VT>& bb)
+{
+    if (bb.valid())
+    {
+        if (valid())
+        {
+            BoundingBoxImpl<vec_type> newbb(bb);
+
+            for(unsigned int c=0;c<8;++c)
+            {
+                vec_type v = bb.corner(c)-_center; // get the direction vector from corner
+                v.normalize(); // normalise it.
+                v *= -_radius; // move the vector in the opposite direction distance radius.
+                v += _center; // move to absolute position.
+                newbb.expandBy(v); // add it into the new bounding box.
+            }
+            
+            _center = newbb.center();
+            _radius = newbb.radius();
+            
+        }
+        else
+        {
+            _center = bb.center();
+            _radius = bb.radius();
+        }
+    }
+}
+
+template<typename VT>
+void BoundingSphereImpl<VT>::expandRadiusBy(const BoundingBoxImpl<VT>& bb)
+{
+    if (bb.valid())
+    {
+        if (valid())
+        {
+            for(unsigned int c=0;c<8;++c)
+            {
+                expandRadiusBy(bb.corner(c));
+            }
+        }
+        else
+        {
+            _center = bb.center();
+            _radius = bb.radius();
+        }
+    }
+}
+
+typedef BoundingSphereImpl<Vec3f> BoundingSpheref;
+typedef BoundingSphereImpl<Vec3d> BoundingSphered;
+
+#ifdef OSG_USE_FLOAT_BOUNDINGSPHERE
+        typedef BoundingSpheref BoundingSphere;
+#else
+        typedef BoundingSphered BoundingSphere;        
+#endif
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Uniform
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Uniform (revision 9243)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Uniform (revision 9243)
@@ -0,0 +1,502 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ * Copyright (C) 2003-2005 3Dlabs Inc. Ltd.
+ * Copyright (C) 2008 Zebra Imaging
+ *
+ * This application is open source and may be redistributed and/or modified   
+ * freely and without restriction, both in commericial and non commericial
+ * applications, as long as this copyright notice is maintained.
+ * 
+ * This application is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+*/
+
+/* file:   include/osg/Uniform
+ * author: Mike Weiblen 2008-01-02
+*/
+
+#ifndef OSG_UNIFORM
+#define OSG_UNIFORM 1
+
+#include <osg/ref_ptr>
+#include <osg/Array>
+#include <osg/Vec2>
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/Matrix>
+#include <osg/GL2Extensions>
+
+#include <string>
+#include <vector>
+
+namespace osg {
+
+// forward declare
+class GL2Extensions;
+class NodeVisitor;
+
+///////////////////////////////////////////////////////////////////////////
+// C++ classes to represent the GLSL-specific types.
+
+class OSG_EXPORT Matrix2
+{
+    public:
+        Matrix2() { makeIdentity(); }
+        Matrix2( const Matrix2& mat ) { set(mat.ptr()); }
+        Matrix2( float a00, float a01,
+                 float a10, float a11 )
+        {
+            set( a00, a01, a10, a11 );
+        }
+        ~Matrix2() {}
+        float& operator()(int row, int col) { return _mat[row][col]; }
+        float operator()(int row, int col) const { return _mat[row][col]; }
+
+        Matrix2& operator = (const Matrix2& rhs)
+        {
+            if( &rhs == this ) return *this;
+            set(rhs.ptr());
+            return *this;
+        }
+
+        void set(const Matrix2& rhs) { set(rhs.ptr()); }
+
+        void set(float const * const ptr)
+        {
+            float* local_ptr = (float*)_mat;
+            for(int i=0;i<4;++i) local_ptr[i]=ptr[i];
+        }
+
+        void set(float a00, float a01,
+                 float a10, float a11)
+         {
+             _mat[0][0]=a00; _mat[0][1]=a01;
+             _mat[1][0]=a10; _mat[1][1]=a11;
+         }
+
+        float* ptr() { return (float*)_mat; }
+        const float* ptr() const { return (const float*)_mat; }
+
+        float& operator [] (int i) {return ptr()[i];}
+        float operator [] (int i) const {return ptr()[i];}
+
+        void makeIdentity() { set( 1, 0, 0, 1 ); }
+
+    protected:
+        float _mat[2][2];
+};
+
+
+class OSG_EXPORT Matrix3
+{
+    public:
+        Matrix3() { makeIdentity(); }
+        Matrix3( const Matrix3& mat ) { set(mat.ptr()); }
+        Matrix3( float a00, float a01, float a02,
+                 float a10, float a11, float a12,
+                 float a20, float a21, float a22 )
+        {
+            set( a00, a01, a02, a10, a11, a12, a20, a21, a22 );
+        }
+        ~Matrix3() {}
+        float& operator()(int row, int col) { return _mat[row][col]; }
+        float operator()(int row, int col) const { return _mat[row][col]; }
+
+        Matrix3& operator = (const Matrix3& rhs)
+        {
+            if( &rhs == this ) return *this;
+            set(rhs.ptr());
+            return *this;
+        }
+
+        void set(const Matrix3& rhs) { set(rhs.ptr()); }
+
+        void set(float const * const ptr)
+        {
+            float* local_ptr = (float*)_mat;
+            for(int i=0;i<9;++i) local_ptr[i]=ptr[i];
+        }
+
+        void set(float a00, float a01, float a02,
+                 float a10, float a11, float a12,
+                 float a20, float a21, float a22 )
+         {
+             _mat[0][0]=a00; _mat[0][1]=a01; _mat[0][2]=a02;
+             _mat[1][0]=a10; _mat[1][1]=a11; _mat[1][2]=a12;
+             _mat[2][0]=a20; _mat[2][1]=a21; _mat[2][2]=a22;
+         }
+
+        float* ptr() { return (float*)_mat; }
+        const float* ptr() const { return (const float*)_mat; }
+
+        float& operator [] (int i) {return ptr()[i];}
+        float operator [] (int i) const {return ptr()[i];}
+
+        void makeIdentity() { set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); }
+
+    protected:
+        float _mat[3][3];
+};
+
+// TODO add new GL 2.1 non-square matrix types
+// class OSG_EXPORT Matrix2x3
+// class OSG_EXPORT Matrix3x2
+// class OSG_EXPORT Matrix2x4
+// class OSG_EXPORT Matrix4x2
+// class OSG_EXPORT Matrix3x4
+// class OSG_EXPORT Matrix4x3
+
+
+///////////////////////////////////////////////////////////////////////////
+
+/** Uniform encapsulates glUniform values */
+class OSG_EXPORT Uniform : public Object
+{
+    public:
+        enum Type {
+            FLOAT = GL_FLOAT,
+            FLOAT_VEC2 = GL_FLOAT_VEC2,
+            FLOAT_VEC3 = GL_FLOAT_VEC3,
+            FLOAT_VEC4 = GL_FLOAT_VEC4,
+            INT = GL_INT,
+            INT_VEC2 = GL_INT_VEC2,
+            INT_VEC3 = GL_INT_VEC3,
+            INT_VEC4 = GL_INT_VEC4,
+            BOOL = GL_BOOL,
+            BOOL_VEC2 = GL_BOOL_VEC2,
+            BOOL_VEC3 = GL_BOOL_VEC3,
+            BOOL_VEC4 = GL_BOOL_VEC4,
+            FLOAT_MAT2 = GL_FLOAT_MAT2,
+            FLOAT_MAT3 = GL_FLOAT_MAT3,
+            FLOAT_MAT4 = GL_FLOAT_MAT4,
+            SAMPLER_1D = GL_SAMPLER_1D,
+            SAMPLER_2D = GL_SAMPLER_2D,
+            SAMPLER_3D = GL_SAMPLER_3D,
+            SAMPLER_CUBE = GL_SAMPLER_CUBE,
+            SAMPLER_1D_SHADOW = GL_SAMPLER_1D_SHADOW,
+            SAMPLER_2D_SHADOW = GL_SAMPLER_2D_SHADOW,
+            
+            SAMPLER_1D_ARRAY  = GL_SAMPLER_1D_ARRAY_EXT,
+            SAMPLER_2D_ARRAY  = GL_SAMPLER_2D_ARRAY_EXT,
+            SAMPLER_1D_ARRAY_SHADOW = GL_SAMPLER_1D_ARRAY_SHADOW_EXT,
+            SAMPLER_2D_ARRAY_SHADOW = GL_SAMPLER_2D_ARRAY_SHADOW_EXT,
+
+// TODO the following must be integrated fully here and Uniform.cpp
+            FLOAT_MAT2x3 = GL_FLOAT_MAT2x3,
+            FLOAT_MAT2x4 = GL_FLOAT_MAT2x4,
+            FLOAT_MAT3x2 = GL_FLOAT_MAT3x2,
+            FLOAT_MAT3x4 = GL_FLOAT_MAT3x4,
+            FLOAT_MAT4x2 = GL_FLOAT_MAT4x2,
+            FLOAT_MAT4x3 = GL_FLOAT_MAT4x3,
+            SAMPLER_BUFFER = GL_SAMPLER_BUFFER_EXT,
+            SAMPLER_CUBE_SHADOW = GL_SAMPLER_CUBE_SHADOW_EXT,
+            UNSIGNED_INT = GL_UNSIGNED_INT,
+            UNSIGNED_INT_VEC2 = GL_UNSIGNED_INT_VEC2_EXT,
+            UNSIGNED_INT_VEC3 = GL_UNSIGNED_INT_VEC3_EXT,
+            UNSIGNED_INT_VEC4 = GL_UNSIGNED_INT_VEC4_EXT,
+            INT_SAMPLER_1D       = GL_INT_SAMPLER_1D_EXT,
+            INT_SAMPLER_2D       = GL_INT_SAMPLER_2D_EXT,
+            INT_SAMPLER_3D       = GL_INT_SAMPLER_3D_EXT,
+            INT_SAMPLER_CUBE     = GL_INT_SAMPLER_CUBE_EXT,
+            INT_SAMPLER_2D_RECT  = GL_INT_SAMPLER_2D_RECT_EXT,
+            INT_SAMPLER_1D_ARRAY = GL_INT_SAMPLER_1D_ARRAY_EXT,
+            INT_SAMPLER_2D_ARRAY = GL_INT_SAMPLER_2D_ARRAY_EXT,
+            INT_SAMPLER_BUFFER   = GL_INT_SAMPLER_BUFFER_EXT,
+            UNSIGNED_INT_SAMPLER_1D       = GL_UNSIGNED_INT_SAMPLER_1D_EXT,
+            UNSIGNED_INT_SAMPLER_2D       = GL_UNSIGNED_INT_SAMPLER_2D_EXT,
+            UNSIGNED_INT_SAMPLER_3D       = GL_UNSIGNED_INT_SAMPLER_3D_EXT,
+            UNSIGNED_INT_SAMPLER_CUBE     = GL_UNSIGNED_INT_SAMPLER_CUBE_EXT,
+            UNSIGNED_INT_SAMPLER_2D_RECT  = GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT,
+            UNSIGNED_INT_SAMPLER_1D_ARRAY = GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT,
+            UNSIGNED_INT_SAMPLER_2D_ARRAY = GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT,
+            UNSIGNED_INT_SAMPLER_BUFFER   = GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT,
+
+            UNDEFINED = 0x0
+        };
+
+    public:
+
+        Uniform();
+        Uniform( Type type, const std::string& name, int numElements=1 );
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Uniform(const Uniform& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, Uniform);
+
+
+        /** Set the type of glUniform, ensuring it is only set once.*/
+        bool setType( Type t );
+
+        /** Get the type of glUniform as enum. */
+        Type getType() const { return _type; }
+
+        /** Set the name of the glUniform, ensuring it is only set once.*/
+        void setName( const std::string& name );
+
+        /** Set the length of a uniform, ensuring it is only set once (1==scalar)*/
+        void setNumElements( unsigned int numElements );
+
+        /** Get the number of GLSL elements of the osg::Uniform (1==scalar) */
+        unsigned int getNumElements() const { return _numElements; }
+
+        /** Get the number of elements required for the internal data array.
+          * Returns 0 if the osg::Uniform is not properly configured.  */
+        unsigned int getInternalArrayNumElements() const;
+
+        /** Return the name of a Type enum as string. */
+        static const char* getTypename( Type t );
+
+        /** Return the the number of components for a GLSL type. */
+        static int getTypeNumComponents( Type t );
+
+        /** Return the Type enum of a Uniform typename string */
+        static Uniform::Type getTypeId( const std::string& tname );
+
+        /** Return the GL API type corresponding to a GLSL type */
+        static Type getGlApiType( Type t );
+
+        /** Return the internal data array type corresponding to a GLSL type */
+        static GLenum getInternalArrayType( Type t );
+
+        /** convenient scalar (non-array) constructors w/ assignment */
+        explicit Uniform( const char* name, float f );
+        explicit Uniform( const char* name, int i );
+        explicit Uniform( const char* name, unsigned int i );
+        explicit Uniform( const char* name, bool b );
+        Uniform( const char* name, const osg::Vec2& v2 );
+        Uniform( const char* name, const osg::Vec3& v3 );
+        Uniform( const char* name, const osg::Vec4& v4 );
+        Uniform( const char* name, const osg::Matrix2& m2 );
+        Uniform( const char* name, const osg::Matrix3& m3 );
+        Uniform( const char* name, const osg::Matrixf& m4 );
+        Uniform( const char* name, const osg::Matrixd& m4 );
+        Uniform( const char* name, int i0, int i1 );
+        Uniform( const char* name, int i0, int i1, int i2 );
+        Uniform( const char* name, int i0, int i1, int i2, int i3 );
+        Uniform( const char* name, unsigned int i0, unsigned int i1 );
+        Uniform( const char* name, unsigned int i0, unsigned int i1, unsigned int i2 );
+        Uniform( const char* name, unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3 );
+        Uniform( const char* name, bool b0, bool b1 );
+        Uniform( const char* name, bool b0, bool b1, bool b2 );
+        Uniform( const char* name, bool b0, bool b1, bool b2, bool b3 );
+        // TODO must add new types
+
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const Uniform& rhs) const;
+        virtual int compareData(const Uniform& rhs) const;
+
+        bool operator <  (const Uniform& rhs) const { return compare(rhs)<0; }
+        bool operator == (const Uniform& rhs) const { return compare(rhs)==0; }
+        bool operator != (const Uniform& rhs) const { return compare(rhs)!=0; }
+
+        void copyData( const Uniform& rhs );
+
+
+        /** A vector of osg::StateSet pointers which is used to store the parent(s) of this Uniform, the parents could be osg::Node or osg::Drawable.*/
+        typedef std::vector<StateSet*> ParentList;
+
+        /** Get the parent list of this Uniform. */
+        inline const ParentList& getParents() const { return _parents; }
+
+        /** Get the a copy of parent list of node. A copy is returned to 
+          * prevent modification of the parent list.*/
+        inline ParentList getParents() { return _parents; }
+
+        inline StateSet* getParent(unsigned int i)  { return _parents[i]; }
+        /**
+         * Get a single const parent of this Uniform.
+         * @param i index of the parent to get.
+         * @return the parent i.
+         */
+        inline const StateSet* getParent(unsigned int i) const  { return _parents[i]; }
+
+        /**
+         * Get the number of parents of this Uniform.
+         * @return the number of parents of this Uniform.
+         */
+        inline unsigned int getNumParents() const { return _parents.size(); }
+
+
+        /** convenient scalar (non-array) value assignment */
+        bool set( float f );
+        bool set( int i );
+        bool set( unsigned int i );
+        bool set( bool b );
+        bool set( const osg::Vec2& v2 );
+        bool set( const osg::Vec3& v3 );
+        bool set( const osg::Vec4& v4 );
+        bool set( const osg::Matrix2& m2 );
+        bool set( const osg::Matrix3& m3 );
+        bool set( const osg::Matrixf& m4 );
+        bool set( const osg::Matrixd& m4 );
+        bool set( int i0, int i1 );
+        bool set( int i0, int i1, int i2 );
+        bool set( int i0, int i1, int i2, int i3 );
+        bool set( unsigned int i0, unsigned int i1 );
+        bool set( unsigned int i0, unsigned int i1, unsigned int i2 );
+        bool set( unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3 );
+        bool set( bool b0, bool b1 );
+        bool set( bool b0, bool b1, bool b2 );
+        bool set( bool b0, bool b1, bool b2, bool b3 );
+
+        /** convenient scalar (non-array) value query */
+        bool get( float& f ) const;
+        bool get( int& i ) const;
+        bool get( unsigned int& i ) const;
+        bool get( bool& b ) const;
+        bool get( osg::Vec2& v2 ) const;
+        bool get( osg::Vec3& v3 ) const;
+        bool get( osg::Vec4& v4 ) const;
+        bool get( osg::Matrix2& m2 ) const;
+        bool get( osg::Matrix3& m3 ) const;
+        bool get( osg::Matrixf& m4 ) const;
+        bool get( osg::Matrixd& m4 ) const;
+        bool get( int& i0, int& i1 ) const;
+        bool get( int& i0, int& i1, int& i2 ) const;
+        bool get( int& i0, int& i1, int& i2, int& i3 ) const;
+        bool get( unsigned int& i0, unsigned int& i1 ) const;
+        bool get( unsigned int& i0, unsigned int& i1, unsigned int& i2 ) const;
+        bool get( unsigned int& i0, unsigned int& i1, unsigned int& i2, unsigned int& i3 ) const;
+        bool get( bool& b0, bool& b1 ) const;
+        bool get( bool& b0, bool& b1, bool& b2 ) const;
+        bool get( bool& b0, bool& b1, bool& b2, bool& b3 ) const;
+
+        /** value assignment for array uniforms */
+        bool setElement( unsigned int index, float f );
+        bool setElement( unsigned int index, int i );
+        bool setElement( unsigned int index, unsigned int i );
+        bool setElement( unsigned int index, bool b );
+        bool setElement( unsigned int index, const osg::Vec2& v2 );
+        bool setElement( unsigned int index, const osg::Vec3& v3 );
+        bool setElement( unsigned int index, const osg::Vec4& v4 );
+        bool setElement( unsigned int index, const osg::Matrix2& m2 );
+        bool setElement( unsigned int index, const osg::Matrix3& m3 );
+        bool setElement( unsigned int index, const osg::Matrixf& m4 );
+        bool setElement( unsigned int index, const osg::Matrixd& m4 );
+        bool setElement( unsigned int index, int i0, int i1 );
+        bool setElement( unsigned int index, int i0, int i1, int i2 );
+        bool setElement( unsigned int index, int i0, int i1, int i2, int i3 );
+        bool setElement( unsigned int index, unsigned int i0, unsigned int i1 );
+        bool setElement( unsigned int index, unsigned int i0, unsigned int i1, unsigned int i2 );
+        bool setElement( unsigned int index, unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3 );
+        bool setElement( unsigned int index, bool b0, bool b1 );
+        bool setElement( unsigned int index, bool b0, bool b1, bool b2 );
+        bool setElement( unsigned int index, bool b0, bool b1, bool b2, bool b3 );
+
+        /** value query for array uniforms */
+        bool getElement( unsigned int index, float& f ) const;
+        bool getElement( unsigned int index, int& i ) const;
+        bool getElement( unsigned int index, unsigned int& i ) const;
+        bool getElement( unsigned int index, bool& b ) const;
+        bool getElement( unsigned int index, osg::Vec2& v2 ) const;
+        bool getElement( unsigned int index, osg::Vec3& v3 ) const;
+        bool getElement( unsigned int index, osg::Vec4& v4 ) const;
+        bool getElement( unsigned int index, osg::Matrix2& m2 ) const;
+        bool getElement( unsigned int index, osg::Matrix3& m3 ) const;
+        bool getElement( unsigned int index, osg::Matrixf& m4 ) const;
+        bool getElement( unsigned int index, osg::Matrixd& m4 ) const;
+        bool getElement( unsigned int index, int& i0, int& i1 ) const;
+        bool getElement( unsigned int index, int& i0, int& i1, int& i2 ) const;
+        bool getElement( unsigned int index, int& i0, int& i1, int& i2, int& i3 ) const;
+        bool getElement( unsigned int index, unsigned int& i0, unsigned int& i1 ) const;
+        bool getElement( unsigned int index, unsigned int& i0, unsigned int& i1, unsigned int& i2 ) const;
+        bool getElement( unsigned int index, unsigned int& i0, unsigned int& i1, unsigned int& i2, unsigned int& i3 ) const;
+        bool getElement( unsigned int index, bool& b0, bool& b1 ) const;
+        bool getElement( unsigned int index, bool& b0, bool& b1, bool& b2 ) const;
+        bool getElement( unsigned int index, bool& b0, bool& b1, bool& b2, bool& b3 ) const;
+
+
+        struct Callback : public virtual osg::Object
+        {
+            Callback() {}
+
+            Callback(const Callback&,const CopyOp&) {}
+
+            META_Object(osg,Callback);
+
+            /** do customized update code.*/
+            virtual void operator () (Uniform*, NodeVisitor*) {}
+        };
+
+        /** Set the UpdateCallback which allows users to attach customize the updating of an object during the update traversal.*/
+        void setUpdateCallback(Callback* uc);
+
+        /** Get the non const UpdateCallback.*/
+        Callback* getUpdateCallback() { return _updateCallback.get(); }
+
+        /** Get the const UpdateCallback.*/
+        const Callback* getUpdateCallback() const { return _updateCallback.get(); }
+
+
+        /** Set the EventCallback which allows users to attach customize the updating of an object during the Event traversal.*/
+        void setEventCallback(Callback* ec);
+
+        /** Get the non const EventCallback.*/
+        Callback* getEventCallback() { return _eventCallback.get(); }
+
+        /** Get the const EventCallback.*/
+        const Callback* getEventCallback() const { return _eventCallback.get(); }
+
+        /** Increment the modified count on the Uniform so Programs watching it know it update themselves.
+          * NOTE: automatically called during osg::Uniform::set*();
+          * you must call if modifying the internal data array directly. */
+        inline void dirty() { ++_modifiedCount; }
+
+        /** Set the internal data array for a osg::Uniform */
+        bool setArray( FloatArray* array );
+        bool setArray( IntArray* array );
+        bool setArray( UIntArray* array );
+
+        /** Get the internal data array for a float osg::Uniform. */
+        FloatArray* getFloatArray() { return _floatArray.get(); }
+        const FloatArray* getFloatArray() const { return _floatArray.get(); }
+
+        /** Get the internal data array for an int osg::Uniform. */
+        IntArray* getIntArray() { return _intArray.get(); }
+        const IntArray* getIntArray() const { return _intArray.get(); }
+
+        /** Get the internal data array for an unsigned int osg::Uniform. */
+        UIntArray* getUIntArray() { return _uintArray.get(); }
+        const UIntArray* getUIntArray() const { return _uintArray.get(); }
+
+        inline void setModifiedCount(unsigned int mc) { _modifiedCount = mc; }
+        inline unsigned int getModifiedCount() const { return _modifiedCount; }
+
+
+        void apply(const GL2Extensions* ext, GLint location) const;
+
+
+    protected:
+    
+        virtual ~Uniform();
+        Uniform& operator=(const Uniform&) { return *this; }
+
+        bool isCompatibleType( Type t ) const;
+        bool isScalar() const { return _numElements==1; }
+        void allocateDataArray();
+
+        void addParent(osg::StateSet* object);
+        void removeParent(osg::StateSet* object);
+
+        ParentList _parents;
+        friend class osg::StateSet;
+
+        Type                _type;
+        unsigned int        _numElements;
+
+        // The internal data for osg::Uniforms are stored as an array of
+        // getInternalArrayType() of length getInternalArrayNumElements().
+        ref_ptr<FloatArray> _floatArray;
+        ref_ptr<IntArray>   _intArray;
+        ref_ptr<UIntArray>  _uintArray;
+
+        ref_ptr<Callback>   _updateCallback;
+        ref_ptr<Callback>   _eventCallback;
+        
+        unsigned int        _modifiedCount;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture3D
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture3D (revision 9383)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture3D (revision 9383)
@@ -0,0 +1,241 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXTURE3D
+#define OSG_TEXTURE3D 1
+
+#include <osg/Texture>
+
+#ifndef GL_MAX_3D_TEXTURE_SIZE
+#define GL_MAX_3D_TEXTURE_SIZE 0x8073
+#endif
+
+namespace osg {
+
+/** Encapsulates OpenGl 2D texture functionality. Doesn't support cube maps,
+  * so ignore \a face parameters.
+*/
+class OSG_EXPORT Texture3D : public Texture
+{
+
+    public :
+        
+        Texture3D();
+
+        Texture3D(Image* image);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Texture3D(const Texture3D& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+        
+        META_StateAttribute(osg, Texture3D,TEXTURE);
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& rhs) const;
+
+        virtual GLenum getTextureTarget() const { return GL_TEXTURE_3D; }
+
+        /** Sets the texture image. */
+        void setImage(Image* image);
+
+        /** Gets the texture image. */
+        Image* getImage() { return _image.get(); }
+
+        /** Gets the const texture image. */
+        inline const Image* getImage() const { return _image.get(); }
+
+        inline unsigned int& getModifiedCount(unsigned int contextID) const
+        {
+            // get the modified count for the current contextID.
+            return _modifiedCount[contextID];
+        }
+
+        /** Sets the texture image, ignoring face. */
+        virtual void setImage(unsigned int, Image* image) { setImage(image); }
+
+        /** Gets the texture image, ignoring face. */
+        virtual Image* getImage(unsigned int) { return _image.get(); }
+
+        /** Gets the const texture image, ignoring face. */
+        virtual const Image* getImage(unsigned int) const { return _image.get(); }
+
+        /** Gets the number of images that can be assigned to the Texture. */
+        virtual unsigned int getNumImages() const { return 1; }
+
+
+        /** Sets the texture width, height, and depth. If width, height, or
+          * depth are zero, calculate the respective value from the source
+          * image size. */
+        inline void setTextureSize(int width, int height, int depth) const
+        {
+            _textureWidth = width;
+            _textureHeight = height;
+            _textureDepth = depth;
+        }
+
+        /** Gets the texture subload width. */
+        inline void getTextureSize(int& width, int& height, int& depth) const
+        {
+            width = _textureWidth;
+            height = _textureHeight;
+            depth = _textureDepth;
+        }
+
+        void setTextureWidth(int width) { _textureWidth=width; }
+        void setTextureHeight(int height) { _textureHeight=height; }
+        void setTextureDepth(int depth) { _textureDepth=depth; }
+
+        virtual int getTextureWidth() const { return _textureWidth; }
+        virtual int getTextureHeight() const { return _textureHeight; }
+        virtual int getTextureDepth() const { return _textureDepth; }
+
+
+        class OSG_EXPORT SubloadCallback : public Referenced
+        {
+            public:
+                virtual void load(const Texture3D& texture,State& state) const = 0;
+                virtual void subload(const Texture3D& texture,State& state) const = 0;
+        };
+        
+        void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; }
+        
+        SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
+
+        const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
+
+
+        /** Helper function. Sets the number of mipmap levels created for this
+          * texture. Should only be called within an osg::Texture::apply(), or
+          * during a custom OpenGL texture load. */
+        void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; }
+
+        /** Gets the number of mipmap levels created. */
+        unsigned int getNumMipmapLevels() const { return _numMipmapLevels; }
+        
+
+        /** Copies a two-dimensional texture subimage, as per
+          * glCopyTexSubImage3D. Updates a portion of an existing OpenGL
+          * texture object from the current OpenGL background framebuffer
+          * contents at position \a x, \a y with width \a width and height
+          * \a height. Loads framebuffer data into the texture using offsets
+          * \a xoffset, \a yoffset, and \a zoffset. \a width and \a height
+          * must be powers of two. */
+        void copyTexSubImage3D(State& state, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height);
+
+
+        /** Bind the texture object. If the texture object hasn't already been
+          * compiled, create the texture mipmap levels. */
+        virtual void apply(State& state) const;
+        
+
+        /** Encapsulates queries of extension availability, obtains extension
+          * function pointers, and provides convenience wrappers for
+          * calling extension functions. */        
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                    
+                void setupGLExtensions(unsigned int contextID);
+
+                void setTexture3DSupported(bool flag) { _isTexture3DSupported=flag; }
+                bool isTexture3DSupported() const { return _isTexture3DSupported; }
+                
+                void setTexture3DFast(bool flag) { _isTexture3DFast=flag; }
+                bool isTexture3DFast() const { return _isTexture3DFast; }
+
+                void setMaxTexture3DSize(GLint maxsize) { _maxTexture3DSize=maxsize; }
+                GLint maxTexture3DSize() const { return _maxTexture3DSize; }
+
+                void glTexImage3D( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels) const;
+                void glTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels) const;
+                void glCopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) const;
+                
+                bool isCompressedTexImage3DSupported() const { return _glCompressedTexImage3D!=0; }
+                void glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data) const;
+
+                bool isCompressedTexSubImage3DSupported() const { return _glCompressedTexSubImage3D!=0; }
+                void glCompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data ) const;
+
+                void gluBuild3DMipmaps( GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *data) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool    _isTexture3DSupported;
+                bool    _isTexture3DFast;
+                GLint   _maxTexture3DSize;
+
+                typedef void (APIENTRY * GLTexImage3DProc)      ( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+                typedef void (APIENTRY * GLTexSubImage3DProc)   ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+                typedef void (APIENTRY * CompressedTexImage3DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * CompressedTexSubImage3DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * GLCopyTexSubImageProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height );
+                typedef void (APIENTRY * GLUBuild3DMipMapsProc) ( GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *data);
+
+                GLTexImage3DProc _glTexImage3D;
+                GLTexSubImage3DProc _glTexSubImage3D;
+                CompressedTexImage3DArbProc _glCompressedTexImage3D;
+                CompressedTexSubImage3DArbProc   _glCompressedTexSubImage3D;
+                GLCopyTexSubImageProc _glCopyTexSubImage3D;
+                GLUBuild3DMipMapsProc _gluBuild3DMipmaps;
+
+        };
+        
+        /** Encapsulates queries of extension availability, obtains extension
+          * function pointers, and provides convenience wrappers for
+          * calling extension functions. */        
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** Overrides Extensions objects across graphics contexts. Typically
+          * used to ensure the same lowest common denominator of extensions
+          * on systems with different graphics pipes. */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+    protected :
+
+        virtual ~Texture3D();
+
+        void computeRequiredTextureDimensions(State& state, const osg::Image& image,GLsizei& width, GLsizei& height,GLsizei& depth, GLsizei& numMipmapLevels) const;
+
+        virtual void computeInternalFormat() const;
+        void allocateMipmap(State& state) const;
+
+        void applyTexImage3D(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight, GLsizei& indepth, GLsizei& numMipmapLevels) const;
+
+        /** It's not ideal that _image is mutable, but it's required since
+          * Image::ensureDimensionsArePowerOfTwo() can only be called in a
+          * valid OpenGL context, and therefore within Texture::apply, which
+          * is const. */
+        mutable ref_ptr<Image> _image;
+
+        /** Subloaded images can have different texture and image sizes. */
+        mutable GLsizei _textureWidth, _textureHeight, _textureDepth;
+        
+        /** Number of mip map levels the the texture has been created with, */
+        mutable GLsizei _numMipmapLevels;
+
+        ref_ptr<SubloadCallback> _subloadCallback;
+
+        typedef buffered_value<unsigned int> ImageModifiedCount;
+        mutable ImageModifiedCount _modifiedCount;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLU
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLU (revision 9883)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLU (revision 9883)
@@ -0,0 +1,32 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_GLU
+#define OSG_GLU 1
+
+#include <osg/GL>
+
+#if defined(__APPLE__) || \
+    (defined (_AIX) && !defined (_AIX51))
+    #include <OpenGL/glu.h>
+#else
+    #include <GL/glu.h>
+#endif
+
+#if defined(GLU_TESS_CALLBACK_TRIPLEDOT)
+    typedef void (APIENTRY *GLU_TESS_CALLBACK)(...);
+#else
+    typedef void (APIENTRY *GLU_TESS_CALLBACK)();
+#endif
+
+#endif  // __osgGLU_h
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4ub
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4ub (revision 10233)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4ub (revision 10233)
@@ -0,0 +1,160 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VEC4UB
+#define OSG_VEC4UB 1
+
+#include <osg/Vec3>
+
+namespace osg {
+
+/** General purpose float quad.
+  * Uses include representation of color coordinates.
+  * No support yet added for float * Vec4ub - is it necessary?
+  * Need to define a non-member non-friend operator*  etc.
+  * Vec4ub * float is okay
+*/
+class Vec4ub
+{
+    public:
+
+        /** Type of Vec class.*/
+        typedef unsigned char value_type;
+
+        /** Number of vector components. */
+        enum { num_components = 4 };
+        
+        /** Vec member variable. */
+        value_type _v[4];
+
+        Vec4ub() { _v[0]=0; _v[1]=0; _v[2]=0; _v[3]=0; }
+
+        Vec4ub(value_type x, value_type y, value_type z, value_type w)
+        {
+            _v[0]=x;
+            _v[1]=y;
+            _v[2]=z;
+            _v[3]=w;
+        }
+
+        inline bool operator == (const Vec4ub& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; }
+
+        inline bool operator != (const Vec4ub& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; }
+
+        inline bool operator <  (const Vec4ub& v) const
+        {
+            if (_v[0]<v._v[0]) return true;
+            else if (_v[0]>v._v[0]) return false;
+            else if (_v[1]<v._v[1]) return true;
+            else if (_v[1]>v._v[1]) return false;
+            else if (_v[2]<v._v[2]) return true;
+            else if (_v[2]>v._v[2]) return false;
+            else return (_v[3]<v._v[3]);
+        }
+
+        inline value_type* ptr() { return _v; }
+        inline const value_type* ptr() const { return _v; }
+
+        inline void set(value_type r, value_type g, value_type b, value_type a)
+        {
+            _v[0]=r; _v[1]=g; _v[2]=b; _v[3]=a;
+        }
+
+        inline value_type& operator [] (unsigned int i) { return _v[i]; }
+        inline value_type operator [] (unsigned int i) const { return _v[i]; }
+
+        inline value_type& r() { return _v[0]; }
+        inline value_type& g() { return _v[1]; }
+        inline value_type& b() { return _v[2]; }
+        inline value_type& a() { return _v[3]; }
+
+        inline value_type r() const { return _v[0]; }
+        inline value_type g() const { return _v[1]; }
+        inline value_type b() const { return _v[2]; }
+        inline value_type a() const { return _v[3]; }
+
+        /** Multiply by scalar. */
+        inline Vec4ub operator * (float rhs) const
+        {
+            Vec4ub col(*this);
+            col *= rhs;
+            return col;
+        }
+
+        /** Unary multiply by scalar. */
+        inline Vec4ub& operator *= (float rhs)
+        {
+            _v[0]=(value_type)((float)_v[0]*rhs);
+            _v[1]=(value_type)((float)_v[1]*rhs);
+            _v[2]=(value_type)((float)_v[2]*rhs);
+            _v[3]=(value_type)((float)_v[3]*rhs);
+            return *this;
+        }
+
+        /** Divide by scalar. */
+        inline Vec4ub operator / (float rhs) const
+        {
+            Vec4ub col(*this);
+            col /= rhs;
+            return col;
+        }
+
+        /** Unary divide by scalar. */
+        inline Vec4ub& operator /= (float rhs)
+        {
+            float div = 1.0f/rhs;
+            *this *= div;
+            return *this;
+        }
+
+        /** Binary vector add. */
+        inline Vec4ub operator + (const Vec4ub& rhs) const
+        {
+            return Vec4ub(_v[0]+rhs._v[0], _v[1]+rhs._v[1],
+                        _v[2]+rhs._v[2], _v[3]+rhs._v[3]);
+        }
+
+        /** Unary vector add. Slightly more efficient because no temporary
+          * intermediate object.
+        */
+        inline Vec4ub& operator += (const Vec4ub& rhs)
+        {
+            _v[0] += rhs._v[0];
+            _v[1] += rhs._v[1];
+            _v[2] += rhs._v[2];
+            _v[3] += rhs._v[3];
+            return *this;
+        }
+
+        /** Binary vector subtract. */
+        inline Vec4ub operator - (const Vec4ub& rhs) const
+        {
+            return Vec4ub(_v[0]-rhs._v[0], _v[1]-rhs._v[1],
+                        _v[2]-rhs._v[2], _v[3]-rhs._v[3] );
+        }
+
+        /** Unary vector subtract. */
+        inline Vec4ub& operator -= (const Vec4ub& rhs)
+        {
+            _v[0]-=rhs._v[0];
+            _v[1]-=rhs._v[1];
+            _v[2]-=rhs._v[2];
+            _v[3]-=rhs._v[3];
+            return *this;
+        }
+
+};    // end of class Vec4ub
+
+}    // end of namespace osg
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ApplicationUsage
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ApplicationUsage (revision 8306)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ApplicationUsage (revision 8306)
@@ -0,0 +1,119 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_APPLICATIONUSAGE
+#define OSG_APPLICATIONUSAGE 1
+
+#include <osg/Referenced>
+
+#include <map>
+#include <string>
+#include <ostream>
+
+namespace osg {
+
+class OSG_EXPORT ApplicationUsage : public osg::Referenced
+{
+    public:
+        
+        static ApplicationUsage* instance();
+
+        ApplicationUsage() {}
+
+        ApplicationUsage(const std::string& commandLineUsage);
+
+        typedef std::map<std::string,std::string> UsageMap;
+        
+
+        void setApplicationName(const std::string& name) { _applicationName = name; }
+        const std::string& getApplicationName() const { return _applicationName; }
+
+        void setDescription(const std::string& desc) { _description = desc; }
+        const std::string& getDescription() const { return _description; }
+
+        enum Type
+        {
+            NO_HELP = 0x0,
+            COMMAND_LINE_OPTION = 0x1,
+            ENVIRONMENTAL_VARIABLE = 0x2,
+            KEYBOARD_MOUSE_BINDING = 0x4,
+            HELP_ALL = KEYBOARD_MOUSE_BINDING|ENVIRONMENTAL_VARIABLE|COMMAND_LINE_OPTION
+        };
+        
+        void addUsageExplanation(Type type,const std::string& option,const std::string& explanation);
+        
+        void setCommandLineUsage(const std::string& explanation) { _commandLineUsage=explanation; }
+        const std::string& getCommandLineUsage() const { return _commandLineUsage; }
+
+
+        void addCommandLineOption(const std::string& option,const std::string& explanation, const std::string &defaultValue = "");
+        
+        void setCommandLineOptions(const UsageMap& usageMap) { _commandLineOptions=usageMap; }
+        const UsageMap& getCommandLineOptions() const { return _commandLineOptions; }
+
+        void setCommandLineOptionsDefaults(const UsageMap& usageMap) { _commandLineOptionsDefaults=usageMap; }
+        const UsageMap& getCommandLineOptionsDefaults() const { return _commandLineOptionsDefaults; }
+
+
+        void addEnvironmentalVariable(const std::string& option,const std::string& explanation, const std::string& defaultValue = "");
+        
+        void setEnvironmentalVariables(const UsageMap& usageMap) { _environmentalVariables=usageMap; }
+        const UsageMap& getEnvironmentalVariables() const { return _environmentalVariables; }
+
+        void setEnvironmentalVariablesDefaults(const UsageMap& usageMap) { _environmentalVariablesDefaults=usageMap; }
+        const UsageMap& getEnvironmentalVariablesDefaults() const { return _environmentalVariablesDefaults; }
+
+
+        void addKeyboardMouseBinding(const std::string& option,const std::string& explanation);
+
+        void setKeyboardMouseBindings(const UsageMap& usageMap) { _keyboardMouse=usageMap; }
+        const UsageMap& getKeyboardMouseBindings() const { return _keyboardMouse; }
+
+
+        void getFormattedString(std::string& str, const UsageMap& um,unsigned int widthOfOutput=80,bool showDefaults=false,const UsageMap& ud=UsageMap());
+
+        void write(std::ostream& output,const UsageMap& um,unsigned int widthOfOutput=80,bool showDefaults=false,const UsageMap& ud=UsageMap());
+        
+        void write(std::ostream& output,unsigned int type=COMMAND_LINE_OPTION, unsigned int widthOfOutput=80,bool showDefaults=false);
+
+        void writeEnvironmentSettings(std::ostream& output);
+
+    protected:
+    
+        virtual ~ApplicationUsage() {}
+
+        std::string _applicationName;
+        std::string _description;
+        std::string _commandLineUsage;
+        UsageMap    _commandLineOptions;
+        UsageMap    _environmentalVariables;
+        UsageMap    _keyboardMouse;
+        UsageMap    _environmentalVariablesDefaults;
+        UsageMap    _commandLineOptionsDefaults;
+        
+};
+
+class ApplicationUsageProxy
+{   
+    public:
+
+        /** register an explanation of commandline/environmentvariable/keyboard mouse usage.*/
+        ApplicationUsageProxy(ApplicationUsage::Type type,const std::string& option,const std::string& explanation)
+        {
+            ApplicationUsage::instance()->addUsageExplanation(type,option,explanation);
+        }
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Math
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Math (revision 9883)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Math (revision 9883)
@@ -0,0 +1,243 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef __OSG_MATH
+#define __OSG_MATH
+
+#include <math.h>
+
+#include <osg/Export>
+
+//certain math functions were not defined until 10.2
+//so this code checks the version so it can add in workarounds for older versions.
+#ifdef __APPLE__
+// Using std::isnan will work for OS X, but use of <cmath> 
+// and std:: are not necessarily portible with other systems so 
+// the include of <cmath> is isolated here.
+#include <cmath>
+#include <AvailabilityMacros.h>
+#if !defined(MAC_OS_X_VERSION_10_2) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_2)
+    // One extra check to verify the gcc version.
+    // The assumption is that there is no possible way to use gcc 4+
+    // on anything less than 10.3.9. So if gcc 4 is in use, this means
+    // pre-10.2 support is not intended and we need not define APPLE_PRE_10_2.
+    // The reason for this extra check is that if the user relies on default
+    // settings, MAC_OS_X_VERSION_MIN_REQUIRED will be set to 1010 and hit
+    // this code path, but this is probably not what they want if using gcc 4+. 
+    #if (__GNUC__ < 4)
+        #define APPLE_PRE_10_2
+    #endif
+#endif
+#endif
+
+#if defined(_MSC_VER)
+    #include <float.h>
+#endif
+
+#if defined (sun) || \
+    defined (__APPLE__) || \
+    (defined (_AIX) && defined (__GNUC__))
+
+    #include <float.h>
+
+    #ifndef acosf
+    inline float acosf(float value) { return static_cast<float>(acos(value)); }
+    #endif
+
+    #ifndef asinf
+    inline float asinf(float value) { return static_cast<float>(asin(value)); }
+    #endif
+
+    #ifndef cosf
+    inline float cosf(float value) { return static_cast<float>(cos(value)); }
+    #endif
+
+    #ifndef sinf
+    inline float sinf(float value) { return static_cast<float>(sin(value)); }
+    #endif
+
+    #ifndef logf
+    inline float logf(float value) { return static_cast<float>(log(value)); }
+    #endif
+
+    #ifndef powf
+    inline float powf(float value1,float value2) { return static_cast<float>(pow(value1,value2)); }
+    #endif
+
+    #ifndef sqrtf
+    inline float sqrtf(float value) { return static_cast<float>(sqrt(value)); }
+    #endif
+    
+    #ifndef fabsf
+    inline float fabsf(float value) { return static_cast<float>(fabs(value)); }
+    #endif
+
+    #ifndef atan2f
+    inline float atan2f(float value1, float value2) { return static_cast<float>(atan2(value1,value2)); }
+    #endif
+
+    #ifndef tanf
+    inline float tanf(float value) { return static_cast<float>(tan(value)); }
+    #endif
+
+#endif
+
+
+#if defined (sun) || \
+    defined (__hpux) || \
+    defined (APPLE_PRE_10_2) || \
+    (defined (_AIX) && defined (__GNUC__))
+
+    #ifndef floorf
+    inline float floorf(float value) { return static_cast<float>(floor(value)); }
+    #endif
+
+    #ifndef ceilf
+    inline float ceilf(float value) { return static_cast<float>(ceil(value)); }
+    #endif
+
+#endif
+
+namespace osg {
+
+// define the standard trig values
+#ifdef PI
+#undef PI
+#undef PI_2
+#undef PI_4
+#endif
+const double PI   = 3.14159265358979323846;
+const double PI_2 = 1.57079632679489661923;
+const double PI_4 = 0.78539816339744830962;
+const double LN_2 = 0.69314718055994530942;
+const double INVLN_2 = 1.0 / LN_2;
+
+
+/** return the minimum of two values, equivalent to std::min.
+  * std::min not used because of STL implementation under IRIX not
+  * containing std::min.
+*/
+template<typename T>
+inline T absolute(T v) { return v<(T)0?-v:v; }
+
+/** return true if float lhs and rhs are equivalent,
+  * meaning that the difference between them is less than an epsilon value
+  * which defaults to 1e-6.
+*/
+inline bool equivalent(float lhs,float rhs,float epsilon=1e-6)
+  { float delta = rhs-lhs; return delta<0.0f?delta>=-epsilon:delta<=epsilon; }
+
+/** return true if double lhs and rhs are equivalent,
+  * meaning that the difference between them is less than an epsilon value
+  * which defaults to 1e-6.
+*/
+inline bool equivalent(double lhs,double rhs,double epsilon=1e-6)
+  { double delta = rhs-lhs; return delta<0.0?delta>=-epsilon:delta<=epsilon; }
+
+/** return the minimum of two values, equivalent to std::min.
+  * std::min not used because of STL implementation under IRIX not containing
+  * std::min.
+*/
+template<typename T>
+inline T minimum(T lhs,T rhs) { return lhs<rhs?lhs:rhs; }
+
+/** return the maximum of two values, equivalent to std::max.
+  * std::max not used because of STL implementation under IRIX not containing
+  * std::max.
+*/
+template<typename T>
+inline T maximum(T lhs,T rhs) { return lhs>rhs?lhs:rhs; }
+
+template<typename T>
+inline T clampTo(T v,T minimum,T maximum)
+  { return v<minimum?minimum:v>maximum?maximum:v; }
+
+template<typename T>
+inline T clampAbove(T v,T minimum) { return v<minimum?minimum:v; }
+
+template<typename T>
+inline T clampBelow(T v,T maximum) { return v>maximum?maximum:v; }
+
+template<typename T>
+inline T clampBetween(T v,T minimum, T maximum)
+  { return clampBelow(clampAbove(v,minimum),maximum); }
+
+template<typename T>
+inline T sign(T v) { return v<(T)0?(T)-1:(T)1; }
+
+template<typename T>
+inline T signOrZero(T v) { return v<(T)0 ? (T)-1 : ( v>(T)0 ? (T)1 : 0 ); }
+
+template<typename T>
+inline T square(T v) { return v*v; }
+
+template<typename T>
+inline T signedSquare(T v) { return v<(T)0?-v*v:v*v;; }
+
+inline float inDegrees(float angle) { return angle*(float)PI/180.0f; }
+inline double inDegrees(double angle) { return angle*PI/180.0; }
+
+template<typename T>
+inline T inRadians(T angle) { return angle; }
+
+inline float DegreesToRadians(float angle) { return angle*(float)PI/180.0f; }
+inline double DegreesToRadians(double angle) { return angle*PI/180.0; }
+
+inline float RadiansToDegrees(float angle) { return angle*180.0f/(float)PI; }
+inline double RadiansToDegrees(double angle) { return angle*180.0/PI; }
+
+inline float round(float v) { return v>=0.0f?floorf(v+0.5f):ceilf(v-0.5f); }
+inline double round(double v) { return v>=0.0?floor(v+0.5):ceil(v-0.5); }
+
+#if defined(WIN32) && !defined(__CYGWIN__) && !defined(__MWERKS__)
+    inline bool isNaN(float v) { return _isnan(v)!=0; }
+    inline bool isNaN(double v) { return _isnan(v)!=0; }
+#else
+    #if defined(__APPLE__)
+        inline bool isNaN(float v) { return std::isnan(v); }
+        inline bool isNaN(double v) { return std::isnan(v); }
+    #else
+        // Need to use to std::isnan to avoid undef problem from <cmath>
+        inline bool isNaN(float v) { return isnan(v); }
+        inline bool isNaN(double v) { return isnan(v); }
+    #endif
+#endif
+
+
+/** compute the volume of a tetrahedron. */
+template<typename T>
+inline float computeVolume(const T& a,const T& b,const T& c,const T& d)
+{
+    return fabsf(((b-c)^(a-b))*(d-b));
+}
+
+/** compute the volume of a prism. */
+template<typename T>
+inline float computeVolume(const T& f1,const T& f2,const T& f3,
+                           const T& b1,const T& b2,const T& b3)
+{
+    return computeVolume(f1,f2,f3,b1)+
+           computeVolume(b1,b2,b3,f2)+
+           computeVolume(b1,b3,f2,f3);
+}
+
+/** Convert a ascii number to a double, ignoring locale settings.*/
+extern OSG_EXPORT double asciiToDouble(const char* str);
+
+/** Convert a ascii number to a float, ignoring locale settings.*/
+inline float asciiToFloat(const char* str) { return static_cast<float>(asciiToDouble(str)); }
+
+}
+
+#endif  // __OSG_MATH
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Geometry
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Geometry (revision 9599)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Geometry (revision 9599)
@@ -0,0 +1,446 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_GEOMETRY
+#define OSG_GEOMETRY 1
+
+#include <osg/Drawable>
+#include <osg/Vec2>
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/Array>
+#include <osg/PrimitiveSet>
+
+namespace osg {
+
+
+class OSG_EXPORT Geometry : public Drawable
+{
+    public:
+
+        Geometry();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Geometry(const Geometry& geometry,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+            
+        virtual Object* cloneType() const { return new Geometry(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new Geometry(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Geometry*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Geometry"; }
+
+        virtual Geometry* asGeometry() { return this; }
+        virtual const Geometry* asGeometry() const { return this; }
+
+        bool empty() const;
+
+        enum AttributeBinding
+        {
+            BIND_OFF=0,
+            BIND_OVERALL,
+            BIND_PER_PRIMITIVE_SET,
+            BIND_PER_PRIMITIVE,
+            BIND_PER_VERTEX
+        };
+               
+        struct OSG_EXPORT ArrayData
+        {
+            ArrayData():
+                binding(BIND_OFF),
+                normalize(GL_FALSE) {}
+                
+            ArrayData(const ArrayData& data,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+            ArrayData(Array* a, AttributeBinding b, GLboolean n = GL_FALSE):
+                array(a),
+                indices(0),
+                binding(b),
+                normalize(n) {}
+
+            ArrayData(Array* a, IndexArray* i, AttributeBinding b, GLboolean n = GL_FALSE):
+                array(a),
+                indices(i),
+                binding(b),
+                normalize(n) {}
+
+            ArrayData& operator = (const ArrayData& rhs)
+            {
+                array = rhs.array;
+                indices = rhs.indices;
+                binding = rhs.binding;
+                normalize = rhs.normalize;
+                return *this;
+            }
+            
+            inline bool empty() const { return !array.valid(); } 
+
+            ref_ptr<Array>          array;
+            ref_ptr<IndexArray>     indices;
+            AttributeBinding        binding;
+            GLboolean               normalize;
+        };
+        
+        struct OSG_EXPORT Vec3ArrayData
+        {
+            Vec3ArrayData():
+                binding(BIND_OFF),
+                normalize(GL_FALSE) {}
+                
+            Vec3ArrayData(const Vec3ArrayData& data,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+            Vec3ArrayData(Vec3Array* a, AttributeBinding b, GLboolean n = GL_FALSE):
+                array(a),
+                indices(0),
+                binding(b),
+                normalize(n) {}
+
+            Vec3ArrayData(Vec3Array* a, IndexArray* i, AttributeBinding b, GLboolean n = GL_FALSE):
+                array(a),
+                indices(i),
+                binding(b),
+                normalize(n) {}
+
+            Vec3ArrayData& operator = (const Vec3ArrayData& rhs)
+            {
+                array = rhs.array;
+                indices = rhs.indices;
+                binding = rhs.binding;
+                normalize = rhs.normalize;
+                return *this;
+            }
+
+            inline bool empty() const { return !array.valid(); } 
+
+            ref_ptr<Vec3Array>          array;
+            ref_ptr<IndexArray>     indices;
+            AttributeBinding        binding;
+            GLboolean               normalize;
+        };
+
+        /** Static ArrayData which is returned from getTexCoordData(i) const and getVertexAttribData(i) const 
+          * when i is out of range.
+        */
+        static const ArrayData s_InvalidArrayData;
+        
+        typedef std::vector< ArrayData >  ArrayDataList;
+               
+
+        void setVertexArray(Array* array);
+        Array* getVertexArray() { return _vertexData.array.get(); }
+        const Array* getVertexArray() const  { return _vertexData.array.get(); }
+
+        void setVertexData(const ArrayData& arrayData);
+        ArrayData& getVertexData() { return _vertexData; }
+        const ArrayData& getVertexData() const { return _vertexData; }
+        
+
+        void setNormalBinding(AttributeBinding ab);
+        AttributeBinding getNormalBinding() const { return _normalData.binding; }
+
+        void setNormalArray(Array* array);
+        Array* getNormalArray() { return _normalData.array.get(); }
+        const Array* getNormalArray() const { return _normalData.array.get(); }
+
+        void setNormalData(const ArrayData& arrayData);
+        ArrayData& getNormalData() { return _normalData; }
+        const ArrayData& getNormalData() const { return _normalData; }
+
+        void setColorBinding(AttributeBinding ab);
+        AttributeBinding getColorBinding() const { return _colorData.binding; }
+
+        void setColorArray(Array* array);
+        Array* getColorArray() { return _colorData.array.get(); }
+        const Array* getColorArray() const { return _colorData.array.get(); }
+
+        void setColorData(const ArrayData& arrayData);
+        ArrayData& getColorData() { return _colorData; }
+        const ArrayData& getColorData() const { return _colorData; }
+
+
+        void setSecondaryColorBinding(AttributeBinding ab);
+        AttributeBinding getSecondaryColorBinding() const { return _secondaryColorData.binding; }
+
+        void setSecondaryColorArray(Array* array);
+        Array* getSecondaryColorArray() { return _secondaryColorData.array.get(); }
+        const Array* getSecondaryColorArray() const { return _secondaryColorData.array.get(); }
+
+        void setSecondaryColorData(const ArrayData& arrayData);
+        ArrayData& getSecondaryColorData() { return _secondaryColorData; }
+        const ArrayData& getSecondaryColorData() const { return _secondaryColorData; }
+
+
+        void setFogCoordBinding(AttributeBinding ab);
+        AttributeBinding getFogCoordBinding() const { return _fogCoordData.binding; }
+
+        void setFogCoordArray(Array* array);
+        Array* getFogCoordArray() { return _fogCoordData.array.get(); }
+        const Array* getFogCoordArray() const { return _fogCoordData.array.get(); }
+
+        void setFogCoordData(const ArrayData& arrayData);
+        ArrayData& getFogCoordData() { return _fogCoordData; }
+        const ArrayData& getFogCoordData() const { return _fogCoordData; }
+        
+
+        void setTexCoordArray(unsigned int unit,Array*);
+        Array* getTexCoordArray(unsigned int unit);
+        const Array* getTexCoordArray(unsigned int unit) const;
+
+        void setTexCoordData(unsigned int index,const ArrayData& arrayData);
+        ArrayData& getTexCoordData(unsigned int index);
+        const ArrayData& getTexCoordData(unsigned int index) const;
+
+        unsigned int getNumTexCoordArrays() const {  return static_cast<unsigned int>(_texCoordList.size()); }
+        ArrayDataList& getTexCoordArrayList() { return _texCoordList; }
+        const ArrayDataList& getTexCoordArrayList() const { return _texCoordList; }
+
+
+
+        void setVertexAttribArray(unsigned int index,Array* array);
+        Array *getVertexAttribArray(unsigned int index);
+        const Array *getVertexAttribArray(unsigned int index) const;
+
+        void setVertexAttribBinding(unsigned int index,AttributeBinding ab);
+        AttributeBinding getVertexAttribBinding(unsigned int index) const;
+
+        void setVertexAttribNormalize(unsigned int index,GLboolean norm);
+        GLboolean getVertexAttribNormalize(unsigned int index) const;
+
+        void setVertexAttribData(unsigned int index,const ArrayData& arrayData);
+        ArrayData& getVertexAttribData(unsigned int index);
+        const ArrayData& getVertexAttribData(unsigned int index) const;
+
+        unsigned int getNumVertexAttribArrays() const { return static_cast<unsigned int>(_vertexAttribList.size()); }
+        ArrayDataList& getVertexAttribArrayList() { return _vertexAttribList; }
+        const ArrayDataList& getVertexAttribArrayList() const { return _vertexAttribList; }
+
+
+
+        typedef std::vector< ref_ptr<PrimitiveSet> > PrimitiveSetList;
+
+        void setPrimitiveSetList(const PrimitiveSetList& primitives) { _primitives = primitives; dirtyDisplayList(); dirtyBound(); }
+        PrimitiveSetList& getPrimitiveSetList() { return _primitives; }
+        const PrimitiveSetList& getPrimitiveSetList() const { return _primitives; }
+
+        unsigned int getNumPrimitiveSets() const { return static_cast<unsigned int>(_primitives.size()); }
+        PrimitiveSet* getPrimitiveSet(unsigned int pos) { return _primitives[pos].get(); }
+        const PrimitiveSet* getPrimitiveSet(unsigned int pos) const { return _primitives[pos].get(); }
+        
+        /** Add a primitive set to the geometry. */
+        bool addPrimitiveSet(PrimitiveSet* primitiveset);
+        
+        /** Set a primitive set to the specified position in geometry's primitive set list. */
+        bool setPrimitiveSet(unsigned int i,PrimitiveSet* primitiveset);
+        
+        /** Insert a primitive set to the specified position in geometry's primitive set list. */
+        bool insertPrimitiveSet(unsigned int i,PrimitiveSet* primitiveset);
+        
+        /** Remove primitive set(s) from the specified position in geometry's primitive set list. */
+        bool removePrimitiveSet(unsigned int i,unsigned int numElementsToRemove=1);
+
+        /** Get the index number of a primitive set, return a value between
+          * 0 and getNumPrimitiveSet()-1 if found, if not found then return getNumPrimitiveSet().
+          * When checking for a valid find value use if ((value=geometry->getPrimitiveSetIndex(primitive))!=geometry.getNumPrimitiveSet())
+        */
+        unsigned int getPrimitiveSetIndex(const PrimitiveSet* primitiveset) const;
+
+
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setVertexIndices(IndexArray* array);
+        IndexArray* getVertexIndices() { return _vertexData.indices.get(); }
+        const IndexArray* getVertexIndices() const  { return _vertexData.indices.get(); }
+     
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setNormalIndices(IndexArray* array);
+        IndexArray* getNormalIndices() { return _normalData.indices.get(); }
+        const IndexArray* getNormalIndices() const { return _normalData.indices.get(); }
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setColorIndices(IndexArray* array);
+        IndexArray* getColorIndices() { return _colorData.indices.get(); }
+        const IndexArray* getColorIndices() const { return _colorData.indices.get(); }
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setSecondaryColorIndices(IndexArray* array);
+        IndexArray* getSecondaryColorIndices() { return _secondaryColorData.indices.get(); }
+        const IndexArray* getSecondaryColorIndices() const { return _secondaryColorData.indices.get(); }
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setFogCoordIndices(IndexArray* array);
+        IndexArray* getFogCoordIndices() { return _fogCoordData.indices.get(); }
+        const IndexArray* getFogCoordIndices() const { return _fogCoordData.indices.get(); }
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setTexCoordIndices(unsigned int unit,IndexArray*);
+        IndexArray* getTexCoordIndices(unsigned int unit);
+        const IndexArray* getTexCoordIndices(unsigned int unit) const;
+
+        /** deprecated - forces OpenGL slow path, just kept for backwards compatibility.*/
+        void setVertexAttribIndices(unsigned int index,IndexArray* array);
+        IndexArray* getVertexAttribIndices(unsigned int index);
+        const IndexArray* getVertexAttribIndices(unsigned int index) const;
+
+
+
+
+        /** When set to true, ignore the setUseDisplayList() settings, and hints to the drawImplementation 
+            method to use OpenGL vertex buffer objects for rendering.*/
+        virtual void setUseVertexBufferObjects(bool flag);
+
+        /** Force a recompile on next draw() of any OpenGL display list associated with this geoset.*/
+        virtual void dirtyDisplayList();
+
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** If State is non-zero, this function releases OpenGL objects for
+          * the specified graphics context. Otherwise, releases OpenGL objects
+          * for all graphics contexts. */
+        virtual void releaseGLObjects(State* state=0) const;
+
+        typedef std::vector<osg::Array*>  ArrayList;
+        bool getArrayList(ArrayList& arrayList) const;
+
+        typedef std::vector<osg::DrawElements*>  DrawElementsList;
+        bool getDrawElementsList(DrawElementsList& drawElementsList) const;
+
+        osg::VertexBufferObject* getOrCreateVertexBufferObject();
+
+        osg::ElementBufferObject* getOrCreateElementBufferObject();
+
+
+        /** Set whether fast paths should be used when supported. */
+        void setFastPathHint(bool on) {  _fastPathHint = on; }
+
+        /** Get whether fast paths should be used when supported. */
+        bool getFastPathHint() const { return _fastPathHint; }
+
+        /** Return true if OpenGL fast paths will be used with drawing this Geometry.
+          * Fast paths use vertex arrays, and glDrawArrays/glDrawElements.  Slow paths
+          * use glBegin()/glVertex.../glEnd(). Use of per primitive bindings or per vertex indexed
+          * arrays will drop the rendering path off the fast path.
+        */
+        inline bool areFastPathsUsed() const { return _fastPath && _fastPathHint; }
+
+        bool computeFastPathsUsed();
+
+        bool verifyBindings() const;
+
+        void computeCorrectBindingsAndArraySizes();
+
+
+        bool suitableForOptimization() const;
+
+        void copyToAndOptimize(Geometry& target);
+
+
+        bool containsSharedArrays() const;
+        
+        void duplicateSharedArrays();
+        
+
+        void computeInternalOptimizedGeometry();
+
+        void removeInternalOptimizedGeometry() { _internalOptimizedGeometry = 0; }
+
+        void setInternalOptimizedGeometry(osg::Geometry* geometry) { _internalOptimizedGeometry = geometry; }
+
+        osg::Geometry* getInternalOptimizedGeometry() { return _internalOptimizedGeometry.get(); }
+
+        const osg::Geometry* getInternalOptimizedGeometry() const { return _internalOptimizedGeometry.get(); }
+
+
+        /** Return the estimated size of GLObjects (display lists/vertex buffer objects) that are associated with this drawable.
+          * This size is used a hint for reuse of deleted display lists/vertex buffer objects. */
+        virtual unsigned int getGLObjectSizeHint() const;
+        
+        /** Draw Geometry directly ignoring an OpenGL display list which could be attached.
+          * This is the internal draw method which does the drawing itself,
+          * and is the method to override when deriving from Geometry for user-drawn objects.
+        */
+        virtual void drawImplementation(RenderInfo& renderInfo) const;
+
+        /** Return true, osg::Geometry does support accept(Drawable::AttributeFunctor&). */
+        virtual bool supports(const Drawable::AttributeFunctor&) const { return true; }
+
+        /** Accept an Drawable::AttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */
+        virtual void accept(Drawable::AttributeFunctor& af);
+
+        /** Return true, osg::Geometry does support accept(Drawable::ConstAttributeFunctor&). */
+        virtual bool supports(const Drawable::ConstAttributeFunctor&) const { return true; }
+
+        /** Accept a Drawable::ConstAttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */
+        virtual void accept(Drawable::ConstAttributeFunctor& af) const;
+
+        /** Return true, osg::Geometry does support accept(PrimitiveFunctor&). */
+        virtual bool supports(const PrimitiveFunctor&) const { return true; }
+
+        /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. */
+        virtual void accept(PrimitiveFunctor& pf) const;
+
+        /** Return true, osg::Geometry does support accept(PrimitiveIndexFunctor&). */
+        virtual bool supports(const PrimitiveIndexFunctor&) const { return true; }
+
+        /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. */
+        virtual void accept(PrimitiveIndexFunctor& pf) const;
+
+
+    protected:
+
+        Geometry& operator = (const Geometry&) { return *this;}
+
+        virtual ~Geometry();
+       
+        bool verifyBindings(const ArrayData& arrayData) const;
+        bool verifyBindings(const Vec3ArrayData& arrayData) const;
+        
+        void computeCorrectBindingsAndArraySizes(ArrayData& arrayData,const char* arrayName);
+        void computeCorrectBindingsAndArraySizes(Vec3ArrayData& arrayData,const char* arrayName);
+        
+        void addVertexBufferObjectIfRequired(osg::Array* array);
+        void addElementBufferObjectIfRequired(osg::PrimitiveSet* primitiveSet);
+        
+
+        PrimitiveSetList                _primitives;
+        ArrayData                       _vertexData;
+        ArrayData                       _normalData;
+        ArrayData                       _colorData;
+        ArrayData                       _secondaryColorData;
+        ArrayData                       _fogCoordData;
+        ArrayDataList                   _texCoordList;
+        ArrayDataList                   _vertexAttribList;
+
+        mutable bool                    _fastPath;
+        bool                            _fastPathHint;
+
+        ref_ptr<Geometry>               _internalOptimizedGeometry;
+};
+
+/** Convenience function to be used for creating quad geometry with texture coords.
+  * Tex coords go from left bottom (l,b) to right top (r,t).
+*/
+extern OSG_EXPORT Geometry* createTexturedQuadGeometry(const Vec3& corner,const Vec3& widthVec,const Vec3& heightVec, float l, float b, float r, float t);
+
+/** Convenience function to be used for creating quad geometry with texture coords.
+  * Tex coords go from bottom left (0,0) to top right (s,t).
+*/
+inline Geometry* createTexturedQuadGeometry(const Vec3& corner,const Vec3& widthVec,const Vec3& heightVec, float s=1.0f, float t=1.0f)
+{
+    return createTexturedQuadGeometry(corner,widthVec,heightVec, 0.0f, 0.0f, s, t);
+}
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/RenderInfo
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/RenderInfo (revision 7896)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/RenderInfo (revision 7896)
@@ -0,0 +1,80 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_RENDERINFO
+#define OSG_RENDERINFO 1
+
+#include <osg/State>
+#include <osg/View>
+#include <osg/observer_ptr>
+
+namespace osg {
+
+class RenderInfo
+{
+public:
+
+    RenderInfo():
+        _view(0) {}
+
+    RenderInfo(const RenderInfo& rhs):
+        _state(rhs._state),
+        _view(rhs._view),
+        _cameras(rhs._cameras),
+        _userData(rhs._userData) {}
+
+    RenderInfo(State* state, View* view):
+        _state(state),
+        _view(view) {}
+        
+    RenderInfo& operator = (const RenderInfo& rhs)
+    {
+        _state = rhs._state;
+        _view = rhs._view;
+        _cameras = rhs._cameras;
+        _userData = rhs._userData;
+        return *this;
+    }
+
+    unsigned int getContextID() const { return _state.valid() ? _state->getContextID() : 0; }
+    
+    void setState(State* state) { _state = state; }
+    State* getState() { return _state.get(); }
+    const State* getState() const { return _state.get(); }
+    
+    void setView(View* view) { _view = view; }
+    View* getView() { return _view.get(); }
+    const View* getView() const { return _view.get(); }
+    
+    void pushCamera(Camera* camera) { _cameras.push_back(camera); }    
+    void popCamera() { if (!_cameras.empty()) _cameras.pop_back(); }
+    
+    Camera* getCurrentCamera() { return _cameras.empty() ? 0 : _cameras.back(); }
+
+    void setUserData(Referenced* userData) { _userData = userData; }
+    Referenced* getUserData() { return _userData.get(); }
+    const Referenced* getUserData() const { return _userData.get(); }
+
+protected:
+
+    typedef std::vector<Camera*> Cameras;
+
+    ref_ptr<State>          _state;
+    observer_ptr<View>      _view;
+    Cameras                 _cameras;
+    ref_ptr<Referenced>     _userData;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/AnimationPath
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/AnimationPath (revision 8889)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/AnimationPath (revision 8889)
@@ -0,0 +1,314 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_ANIMATIONPATH
+#define OSG_ANIMATIONPATH 1
+
+#include <map>
+#include <istream>
+#include <float.h>
+
+#include <osg/Matrixf>
+#include <osg/Matrixd>
+#include <osg/Quat>
+#include <osg/NodeCallback>
+
+namespace osg {
+
+/** AnimationPath encapsulates a time varying transformation pathway. Can be
+  * used for updating camera position and model object position.
+  * AnimationPathCallback can be attached directly to Transform nodes to
+  * move subgraphs around the scene.
+*/
+class OSG_EXPORT AnimationPath : public virtual osg::Object
+{
+    public:
+    
+        AnimationPath():_loopMode(LOOP) {}
+
+        AnimationPath(const AnimationPath& ap, const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            Object(ap,copyop),
+            _timeControlPointMap(ap._timeControlPointMap),
+            _loopMode(ap._loopMode) {}
+
+        META_Object(osg,AnimationPath);
+
+        class ControlPoint
+        {
+        public:
+            ControlPoint():
+                _scale(1.0,1.0,1.0) {}
+
+            ControlPoint(const osg::Vec3d& position):
+                _position(position),
+                _rotation(),
+                _scale(1.0,1.0,1.0) {}
+
+            ControlPoint(const osg::Vec3d& position, const osg::Quat& rotation):
+                _position(position),
+                _rotation(rotation),
+                _scale(1.0,1.0,1.0) {}
+
+            ControlPoint(const osg::Vec3d& position, const osg::Quat& rotation, const osg::Vec3d& scale):
+                _position(position),
+                _rotation(rotation),
+                _scale(scale) {}
+        
+            void setPosition(const osg::Vec3d& position) { _position = position; }
+            const osg::Vec3d& getPosition() const { return _position; }
+
+            void setRotation(const osg::Quat& rotation) { _rotation = rotation; }
+            const osg::Quat& getRotation() const { return _rotation; }
+
+            void setScale(const osg::Vec3d& scale) { _scale = scale; }
+            const osg::Vec3d& getScale() const { return _scale; }
+
+            inline void interpolate(float ratio,const ControlPoint& first, const ControlPoint& second)
+            {
+                float one_minus_ratio = 1.0f-ratio;
+                _position = first._position*one_minus_ratio + second._position*ratio;
+                _rotation.slerp(ratio,first._rotation,second._rotation);
+                _scale = first._scale*one_minus_ratio + second._scale*ratio;
+            }
+            
+            inline void interpolate(double ratio,const ControlPoint& first, const ControlPoint& second)
+            {
+                double one_minus_ratio = 1.0f-ratio;
+                _position = first._position*one_minus_ratio + second._position*ratio;
+                _rotation.slerp(ratio,first._rotation,second._rotation);
+                _scale = first._scale*one_minus_ratio + second._scale*ratio;
+            }
+
+            inline void getMatrix(Matrixf& matrix) const
+            {
+                matrix.makeRotate(_rotation);
+                matrix.preMultScale(_scale);
+                matrix.postMultTranslate(_position);
+            }
+
+            inline void getMatrix(Matrixd& matrix) const
+            {
+                matrix.makeRotate(_rotation);
+                matrix.preMultScale(_scale);
+                matrix.postMultTranslate(_position);
+            }
+
+            inline void getInverse(Matrixf& matrix) const
+            {
+                matrix.makeRotate(_rotation.inverse());
+                matrix.postMultScale(osg::Vec3d(1.0/_scale.x(),1.0/_scale.y(),1.0/_scale.z()));
+                matrix.preMultTranslate(-_position);
+            }
+
+            inline void getInverse(Matrixd& matrix) const
+            {
+                matrix.makeRotate(_rotation.inverse());
+                matrix.postMultScale(osg::Vec3d(1.0/_scale.x(),1.0/_scale.y(),1.0/_scale.z()));
+                matrix.preMultTranslate(-_position);
+            }
+
+        protected:
+
+            osg::Vec3d _position;
+            osg::Quat _rotation;
+            osg::Vec3d _scale;
+
+        };
+        
+
+        /** Given a specific time, return the transformation matrix for a point. */
+        bool getMatrix(double time,Matrixf& matrix) const
+        {
+            ControlPoint cp;
+            if (!getInterpolatedControlPoint(time,cp)) return false;
+            cp.getMatrix(matrix);
+            return true;
+        }
+
+        /** Given a specific time, return the transformation matrix for a point. */
+        bool getMatrix(double time,Matrixd& matrix) const
+        {
+            ControlPoint cp;
+            if (!getInterpolatedControlPoint(time,cp)) return false;
+            cp.getMatrix(matrix);
+            return true;
+        }
+
+        /** Given a specific time, return the inverse transformation matrix for a point. */
+        bool getInverse(double time,Matrixf& matrix) const
+        {
+            ControlPoint cp;
+            if (!getInterpolatedControlPoint(time,cp)) return false;
+            cp.getInverse(matrix);
+            return true;
+        }
+        
+        bool getInverse(double time,Matrixd& matrix) const
+        {
+            ControlPoint cp;
+            if (!getInterpolatedControlPoint(time,cp)) return false;
+            cp.getInverse(matrix);
+            return true;
+        }
+
+        /** Given a specific time, return the local ControlPoint frame for a point. */
+        virtual bool getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const;
+        
+        /** Insert a control point into the AnimationPath.*/
+        void insert(double time,const ControlPoint& controlPoint);
+        
+        double getFirstTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.begin()->first; else return 0.0;}
+        double getLastTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.rbegin()->first; else return 0.0;}
+        double getPeriod() const { return getLastTime()-getFirstTime();}
+        
+        enum LoopMode
+        {
+            SWING,
+            LOOP,
+            NO_LOOPING
+        };
+        
+        void setLoopMode(LoopMode lm) { _loopMode = lm; }
+        
+        LoopMode getLoopMode() const { return _loopMode; }
+
+
+        typedef std::map<double,ControlPoint> TimeControlPointMap;
+        
+        void setTimeControlPointMap(TimeControlPointMap& tcpm) { _timeControlPointMap=tcpm; }
+
+        TimeControlPointMap& getTimeControlPointMap() { return _timeControlPointMap; }
+        
+        const TimeControlPointMap& getTimeControlPointMap() const { return _timeControlPointMap; }
+        
+        bool empty() const { return _timeControlPointMap.empty(); }
+        
+        void clear() { _timeControlPointMap.clear(); }
+
+        /** Read the animation path from a flat ASCII file stream. */
+        void read(std::istream& in);
+
+        /** Write the animation path to a flat ASCII file stream. */
+        void write(std::ostream& out) const;
+
+        /** Write the control point to a flat ASCII file stream. */
+        void write(TimeControlPointMap::const_iterator itr, std::ostream& out) const;
+
+    protected:
+    
+        virtual ~AnimationPath() {}
+
+        TimeControlPointMap _timeControlPointMap;
+        LoopMode            _loopMode;
+
+};
+
+
+class OSG_EXPORT AnimationPathCallback : public NodeCallback
+{
+    public:
+
+        AnimationPathCallback():
+            _pivotPoint(0.0,0.0,0.0),
+            _useInverseMatrix(false),
+            _timeOffset(0.0),
+            _timeMultiplier(1.0),
+            _firstTime(DBL_MAX),
+            _latestTime(0.0),
+            _pause(false),
+            _pauseTime(0.0) {}
+
+        AnimationPathCallback(const AnimationPathCallback& apc,const CopyOp& copyop):
+            NodeCallback(apc,copyop),
+            _animationPath(apc._animationPath),
+            _pivotPoint(apc._pivotPoint),
+            _useInverseMatrix(apc._useInverseMatrix),
+            _timeOffset(apc._timeOffset),
+            _timeMultiplier(apc._timeMultiplier),
+            _firstTime(apc._firstTime),
+            _latestTime(apc._latestTime),
+            _pause(apc._pause),
+            _pauseTime(apc._pauseTime) {}
+
+        
+        META_Object(osg,AnimationPathCallback);
+
+        /** Construct an AnimationPathCallback with a specified animation path.*/
+        AnimationPathCallback(AnimationPath* ap,double timeOffset=0.0,double timeMultiplier=1.0):
+            _animationPath(ap),
+            _pivotPoint(0.0,0.0,0.0),
+            _useInverseMatrix(false),
+            _timeOffset(timeOffset),
+            _timeMultiplier(timeMultiplier),
+            _firstTime(DBL_MAX),
+            _latestTime(0.0),
+            _pause(false),
+            _pauseTime(0.0) {}
+
+        /** Construct an AnimationPathCallback and automatical create an animation path to produce a rotation about a point.*/
+        AnimationPathCallback(const osg::Vec3d& pivot,const osg::Vec3d& axis,float angularVelocity);
+ 
+            
+        void setAnimationPath(AnimationPath* path) { _animationPath = path; }
+        AnimationPath* getAnimationPath() { return _animationPath.get(); }
+        const AnimationPath* getAnimationPath() const { return _animationPath.get(); }
+
+        inline void setPivotPoint(const Vec3d& pivot) { _pivotPoint = pivot; }
+        inline const Vec3d& getPivotPoint() const { return _pivotPoint; }
+
+        void setUseInverseMatrix(bool useInverseMatrix) { _useInverseMatrix = useInverseMatrix; }
+        bool getUseInverseMatrix() const { return _useInverseMatrix; }
+
+        void setTimeOffset(double offset) { _timeOffset = offset; }
+        double getTimeOffset() const { return _timeOffset; }
+        
+        void setTimeMultiplier(double multiplier) { _timeMultiplier = multiplier; }
+        double getTimeMultiplier() const { return _timeMultiplier; }
+
+
+        virtual void reset();
+
+        void setPause(bool pause);
+        bool getPause() const { return _pause; }
+
+        /** Get the animation time that is used to specify the position along
+          * the AnimationPath. Animation time is computed from the formula:
+          *   ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier.*/
+        virtual double getAnimationTime() const;
+
+        /** Implements the callback. */
+        virtual void operator()(Node* node, NodeVisitor* nv);
+        
+        void update(osg::Node& node);
+
+    public:
+
+        ref_ptr<AnimationPath>  _animationPath;
+        osg::Vec3d              _pivotPoint;
+        bool                    _useInverseMatrix;
+        double                  _timeOffset;
+        double                  _timeMultiplier;
+        double                  _firstTime;
+        double                  _latestTime;
+        bool                    _pause;
+        double                  _pauseTime;
+
+    protected:
+    
+        ~AnimationPathCallback(){}
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TextureCubeMap
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TextureCubeMap (revision 7385)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TextureCubeMap (revision 7385)
@@ -0,0 +1,200 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXTURECUBEMAP
+#define OSG_TEXTURECUBEMAP 1
+
+#include <osg/Texture>
+
+#ifndef GL_TEXTURE_CUBE_MAP
+    #define GL_TEXTURE_CUBE_MAP             0x8513
+    #define GL_TEXTURE_BINDING_CUBE_MAP     0x8514
+    #define GL_TEXTURE_CUBE_MAP_POSITIVE_X  0x8515
+    #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X  0x8516
+    #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y  0x8517
+    #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y  0x8518
+    #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z  0x8519
+    #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z  0x851A
+    #define GL_PROXY_TEXTURE_CUBE_MAP       0x851B
+    #define GL_MAX_CUBE_MAP_TEXTURE_SIZE    0x851C
+#endif
+
+namespace osg {
+
+/** TextureCubeMap state class which encapsulates OpenGL texture cubemap functionality. */
+class OSG_EXPORT TextureCubeMap : public Texture
+{
+
+    public :
+        
+        TextureCubeMap();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        TextureCubeMap(const TextureCubeMap& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osg, TextureCubeMap,TEXTURE);
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& rhs) const;
+
+        virtual GLenum getTextureTarget() const { return GL_TEXTURE_CUBE_MAP; }
+
+        enum Face {
+            POSITIVE_X=0,
+            NEGATIVE_X=1,
+            POSITIVE_Y=2,
+            NEGATIVE_Y=3,
+            POSITIVE_Z=4,
+            NEGATIVE_Z=5
+        };
+
+        /** Set the texture image for specified face. */
+        virtual void setImage(unsigned int face, Image* image);
+
+        /** Get the texture image for specified face. */
+        virtual Image* getImage(unsigned int face);
+
+        /** Get the const texture image for specified face. */
+        virtual const Image* getImage(unsigned int face) const;
+
+        /** Get the number of images that can be assigned to the Texture. */
+        virtual unsigned int getNumImages() const { return 6; }
+
+        inline unsigned int& getModifiedCount(unsigned int face,unsigned int contextID) const
+        {
+            // get the modified count for the current contextID.
+            return _modifiedCount[face][contextID];
+        }
+
+        /** Set the texture width and height. If width or height are zero then
+          * the repsective size value is calculated from the source image sizes.
+        */
+        inline void setTextureSize(int width, int height) const
+        {
+            _textureWidth = width;
+            _textureHeight = height;
+        }
+
+        void setTextureWidth(int width) { _textureWidth=width; }
+        void setTextureHeight(int height) { _textureHeight=height; }
+
+        virtual int getTextureWidth() const { return _textureWidth; }
+        virtual int getTextureHeight() const { return _textureHeight; }
+        virtual int getTextureDepth() const { return 1; }
+
+        class OSG_EXPORT SubloadCallback : public Referenced
+        {
+            public:
+                virtual void load(const TextureCubeMap& texture,State& state) const = 0;
+                virtual void subload(const TextureCubeMap& texture,State& state) const = 0;
+        };
+        
+        void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; }
+        
+        SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
+
+        const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
+
+
+        /** Set the number of mip map levels the the texture has been created with.
+          * Should only be called within an osg::Texuture::apply() and custom OpenGL texture load.
+        */
+        void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; }
+
+        /** Get the number of mip map levels the the texture has been created with. */
+        unsigned int getNumMipmapLevels() const { return _numMipmapLevels; }        
+
+        /** Copies a two-dimensional texture subimage, as per
+          * glCopyTexSubImage2D. Updates a portion of an existing OpenGL
+          * texture object from the current OpenGL background framebuffer
+          * contents at position \a x, \a y with width \a width and height
+          * \a height. Loads framebuffer data into the texture using offsets
+          * \a xoffset and \a yoffset. \a width and \a height must be powers
+          * of two. */
+        void copyTexSubImageCubeMap(State& state, int face, int xoffset, int yoffset, int x, int y, int width, int height );
+
+
+        /** On first apply (unless already compiled), create the mipmapped
+          * texture and bind it. Subsequent apply will simple bind to texture.
+        */
+        virtual void apply(State& state) const;
+        
+
+        /** Extensions class which encapsulates the querying of extensions and
+          * associated function pointers, and provides convinience wrappers to 
+          * check for the extensions or use the associated functions.
+        */
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setCubeMapSupported(bool flag) { _isCubeMapSupported=flag; }
+                bool isCubeMapSupported() const { return _isCubeMapSupported; }
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool    _isCubeMapSupported;
+
+        };
+        
+        /** Function to call to get the extension of a specified context.
+          * If the Exentsion object for that context has not yet been created
+          * and the 'createIfNotInitalized' flag been set to false then returns NULL.
+          * If 'createIfNotInitalized' is true then the Extensions object is 
+          * automatically created. However, in this case the extension object will
+          * only be created with the graphics context associated with ContextID.
+        */
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** The setExtensions method allows users to override the extensions across graphics contexts.
+          * Typically used when you have different extensions supported across graphics pipes
+          * but need to ensure that they all use the same low common denominator extensions.
+        */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+    protected :
+
+        virtual ~TextureCubeMap();
+        
+        bool imagesValid() const;
+        
+        virtual void computeInternalFormat() const;
+        void allocateMipmap(State& state) const;
+
+        ref_ptr<Image> _images[6];
+
+        // subloaded images can have different texture and image sizes.
+        mutable GLsizei _textureWidth, _textureHeight;
+        
+        // number of mip map levels the the texture has been created with,        
+        mutable GLsizei _numMipmapLevels;
+
+        ref_ptr<SubloadCallback> _subloadCallback;
+
+        typedef buffered_value<unsigned int> ImageModifiedCount;
+        mutable ImageModifiedCount _modifiedCount[6];
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec2
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec2 (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec2 (revision 5328)
@@ -0,0 +1,25 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VEC2
+#define OSG_VEC2 1
+
+#include <osg/Vec2f>
+
+namespace osg {
+
+    typedef Vec2f Vec2;
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexGenNode
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexGenNode (revision 5958)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexGenNode (revision 5958)
@@ -0,0 +1,79 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TexGenNode
+#define OSG_TexGenNode 1
+
+#include <osg/Group>
+#include <osg/TexGen>
+
+namespace osg {
+
+/** Node for defining the position of TexGen in the scene. */
+class OSG_EXPORT TexGenNode : public Group
+{
+
+    public:
+
+        TexGenNode();
+        TexGenNode(TexGen* texgen);
+
+        TexGenNode(const TexGenNode& tgb, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Node(osg, TexGenNode);
+    
+        
+        enum ReferenceFrame
+        {
+            RELATIVE_RF,
+            ABSOLUTE_RF
+        };
+        
+        /** Set the TexGenNode's ReferenceFrame, either to be relative to its
+          * parent reference frame. */
+        void setReferenceFrame(ReferenceFrame rf);
+        
+        /** Ge thte TexGenNode's ReferenceFrame.*/
+        ReferenceFrame getReferenceFrame() const { return _referenceFrame; }
+
+        /** Set the texture unit that this TexGenNode is associated with.*/
+        void setTextureUnit(unsigned int textureUnit) { _textureUnit = textureUnit; }
+
+        unsigned int getTextureUnit() const { return _textureUnit; }
+
+        /** Set the TexGen. */
+        void setTexGen(TexGen* texgen);
+        
+        /** Get the TexGen. */
+        inline TexGen* getTexGen() { return _texgen.get(); }
+
+        /** Get the const TexGen. */
+        inline const TexGen* getTexGen() const { return _texgen.get(); }
+
+        /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/
+        virtual void setThreadSafeRefUnref(bool threadSafe);
+
+    protected:
+
+        virtual ~TexGenNode();
+
+        unsigned int _textureUnit;
+        StateAttribute::GLModeValue _value;
+        osg::ref_ptr<TexGen> _texgen;
+
+        ReferenceFrame                  _referenceFrame;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec3
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec3 (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec3 (revision 5328)
@@ -0,0 +1,25 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VEC3
+#define OSG_VEC3 1
+
+#include <osg/Vec3f>
+
+namespace osg {
+
+    typedef Vec3f Vec3;
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Stencil
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Stencil (revision 6311)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Stencil (revision 6311)
@@ -0,0 +1,174 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_STENCIL
+#define OSG_STENCIL 1
+
+#include <osg/StateAttribute>
+
+namespace osg {
+
+#ifndef GL_INCR_WRAP
+#define GL_INCR_WRAP 0x8507
+#define GL_DECR_WRAP 0x8508
+#endif
+
+
+/** Encapsulate OpenGL glStencilFunc/Op/Mask functions.
+*/     
+class OSG_EXPORT Stencil : public StateAttribute
+{
+    public :
+    
+    
+        Stencil();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Stencil(const Stencil& stencil,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(stencil,copyop),
+            _func(stencil._func),
+            _funcRef(stencil._funcRef),
+            _funcMask(stencil._funcMask),
+            _sfail(stencil._sfail),
+            _zfail(stencil._zfail),
+            _zpass(stencil._zpass),
+            _writeMask(stencil._writeMask) {}
+
+
+        META_StateAttribute(osg, Stencil, STENCIL);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Parameter macro's below.
+            COMPARE_StateAttribute_Types(Stencil,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_func)
+            COMPARE_StateAttribute_Parameter(_funcRef)
+            COMPARE_StateAttribute_Parameter(_funcMask)
+            COMPARE_StateAttribute_Parameter(_sfail)
+            COMPARE_StateAttribute_Parameter(_zfail)
+            COMPARE_StateAttribute_Parameter(_zpass)
+            COMPARE_StateAttribute_Parameter(_writeMask)
+
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_STENCIL_TEST);
+            return true;
+        }
+
+        enum Function
+        {
+            NEVER = GL_NEVER,
+            LESS = GL_LESS,
+            EQUAL = GL_EQUAL,
+            LEQUAL = GL_LEQUAL,
+            GREATER = GL_GREATER,
+            NOTEQUAL = GL_NOTEQUAL,
+            GEQUAL = GL_GEQUAL,
+            ALWAYS = GL_ALWAYS
+        };
+
+        inline void setFunction(Function func,int ref,unsigned int mask)
+        {
+            _func = func;
+            _funcRef = ref;
+            _funcMask = mask;
+        }
+        
+        inline void setFunction(Function func) { _func = func; }
+        inline Function getFunction() const { return _func; }
+        
+        inline void setFunctionRef(int ref) { _funcRef=ref; }
+        inline int getFunctionRef() const { return _funcRef; }
+
+        inline void setFunctionMask(unsigned int mask) { _funcMask=mask; }
+        inline unsigned int getFunctionMask() const { return _funcMask; }
+        
+        
+        enum Operation 
+        {
+            KEEP = GL_KEEP,
+            ZERO = GL_ZERO,
+            REPLACE = GL_REPLACE,
+            INCR = GL_INCR,
+            DECR = GL_DECR,
+            INVERT = GL_INVERT,
+            INCR_WRAP = GL_INCR_WRAP,
+            DECR_WRAP = GL_DECR_WRAP
+        };
+        
+        /** set the operations to apply when the various stencil and depth 
+          * tests fail or pass.  First parameter is to control the operation
+          * when the stencil test fails.  The second parameter is to control the
+          * operation when the stencil test passes, but depth test fails. The
+          * third parameter controls the operation when both the stencil test
+          * and depth pass.  Ordering of parameter is the same as if using
+          * glStencilOp(,,).*/
+        inline void setOperation(Operation sfail, Operation zfail, Operation zpass)
+        {
+            _sfail = sfail;
+            _zfail = zfail;
+            _zpass = zpass;
+        }
+        
+        /** set the operation when the stencil test fails.*/
+        inline void setStencilFailOperation(Operation sfail) { _sfail = sfail; }
+
+        /** get the operation when the stencil test fails.*/
+        inline Operation getStencilFailOperation() const { return _sfail; }
+        
+        /** set the operation when the stencil test passes but the depth test fails.*/
+        inline void setStencilPassAndDepthFailOperation(Operation zfail) { _zfail=zfail; }
+        
+        /** get the operation when the stencil test passes but the depth test fails.*/
+        inline Operation getStencilPassAndDepthFailOperation() const { return _zfail; }
+
+        /** set the operation when both the stencil test and the depth test pass.*/
+        inline void setStencilPassAndDepthPassOperation(Operation zpass) { _zpass=zpass; }
+
+        /** get the operation when both the stencil test and the depth test pass.*/
+        inline Operation getStencilPassAndDepthPassOperation() const { return _zpass; }
+        
+
+        inline void setWriteMask(unsigned int mask) { _writeMask = mask; }
+        
+        inline unsigned int getWriteMask() const { return _writeMask; }
+
+
+        virtual void apply(State& state) const;
+
+    protected:
+    
+        virtual ~Stencil();
+
+        Function            _func;
+        int                 _funcRef;
+        unsigned int        _funcMask;
+        
+        Operation           _sfail;
+        Operation           _zfail;
+        Operation           _zpass;
+        
+        unsigned int        _writeMask;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4 (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Vec4 (revision 5328)
@@ -0,0 +1,25 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VEC4
+#define OSG_VEC4 1
+
+#include <osg/Vec4f>
+
+namespace osg {
+
+    typedef Vec4f Vec4;
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CoordinateSystemNode
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CoordinateSystemNode (revision 8095)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CoordinateSystemNode (revision 8095)
@@ -0,0 +1,229 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_COORDINATESYSTEMNODE
+#define OSG_COORDINATESYSTEMNODE 1
+
+#include <osg/Group>
+#include <osg/Matrixd>
+
+namespace osg
+{
+
+const double WGS_84_RADIUS_EQUATOR = 6378137.0;
+const double WGS_84_RADIUS_POLAR = 6356752.3142;
+
+/** EllipsoidModel encapsulates the ellipsoid used to model astronomical bodies,
+ * such as sun, planets, moon etc. 
+ * All distance quantities (i.e. heights + radius) are in meters,
+ * and latitude and longitude are in radians.*/
+class EllipsoidModel : public Object
+{
+    public:
+
+        /** WGS_84 is a common representation of the earth's spheroid */
+        EllipsoidModel(double radiusEquator = WGS_84_RADIUS_EQUATOR,
+                       double radiusPolar = WGS_84_RADIUS_POLAR):
+            _radiusEquator(radiusEquator),
+            _radiusPolar(radiusPolar) { computeCoefficients(); }
+
+        EllipsoidModel(const EllipsoidModel& et,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            Object(et,copyop),
+            _radiusEquator(et._radiusEquator),
+            _radiusPolar(et._radiusPolar) { computeCoefficients(); }
+
+        META_Object(osg,EllipsoidModel);
+
+        void setRadiusEquator(double radius) { _radiusEquator = radius; computeCoefficients(); }
+        double getRadiusEquator() const { return _radiusEquator; }
+
+        void setRadiusPolar(double radius) { _radiusPolar = radius; computeCoefficients(); }
+        double getRadiusPolar() const { return _radiusPolar; }
+
+        inline void convertLatLongHeightToXYZ(double latitude, double longitude, double height,
+                                              double& X, double& Y, double& Z) const;
+
+        inline void convertXYZToLatLongHeight(double X, double Y, double Z,
+                                              double& latitude, double& longitude, double& height) const;
+
+        inline void computeLocalToWorldTransformFromLatLongHeight(double latitude, double longitude, double height, osg::Matrixd& localToWorld) const;
+
+        inline void computeLocalToWorldTransformFromXYZ(double X, double Y, double Z, osg::Matrixd& localToWorld) const;
+
+        inline osg::Vec3d computeLocalUpVector(double X, double Y, double Z) const;
+
+    protected:
+
+        void computeCoefficients()
+        {
+            double flattening = (_radiusEquator-_radiusPolar)/_radiusEquator;
+            _eccentricitySquared = 2*flattening - flattening*flattening;
+        }
+
+        double _radiusEquator;
+        double _radiusPolar;
+        double _eccentricitySquared;
+
+};
+
+/** CoordinateFrame encapsulates the orientation of east, north and up.*/ 
+typedef Matrixd CoordinateFrame;
+
+/** CoordinateSystem encapsulate the coordinate system that is associated with objects in a scene.
+    For an overview of common earth bases coordinate systems see http://www.colorado.edu/geography/gcraft/notes/coordsys/coordsys_f.html */
+class OSG_EXPORT CoordinateSystemNode : public Group
+{
+    public:
+
+        CoordinateSystemNode();
+
+        CoordinateSystemNode(const std::string& format, const std::string& cs);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        CoordinateSystemNode(const CoordinateSystemNode&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+        
+        META_Node(osg,CoordinateSystemNode);
+        
+        
+        /** Set the coordinate system node up by copy the format, coordinate system string, and ellipsoid model of another coordinate system node.*/
+        void set(const CoordinateSystemNode& csn);
+                
+        /** Set the coordinate system format string. Typical values would be WKT, PROJ4, USGS etc.*/
+        void setFormat(const std::string& format) { _format = format; }
+        
+        /** Get the coordinate system format string.*/
+        const std::string& getFormat() const { return _format; }
+
+        /** Set the CoordinateSystem reference string, should be stored in a form consistent with the Format.*/
+        void setCoordinateSystem(const std::string& cs) { _cs = cs; }
+        
+        /** Get the CoordinateSystem reference string.*/
+        const std::string& getCoordinateSystem() const { return _cs; }
+        
+        
+        /** Set EllipsoidModel to describe the model used to map lat, long and height into geocentric XYZ and back. */
+        void setEllipsoidModel(EllipsoidModel* ellipsode) { _ellipsoidModel = ellipsode; }
+        
+        /** Get the EllipsoidModel.*/
+        EllipsoidModel* getEllipsoidModel() { return _ellipsoidModel.get(); }
+        
+        /** Get the const EllipsoidModel.*/
+        const EllipsoidModel* getEllipsoidModel() const { return _ellipsoidModel.get(); }
+        
+        /** Compute the local coordinate frame for specified point.*/
+        CoordinateFrame computeLocalCoordinateFrame(const Vec3d& position) const;
+        
+        /** Compute the local coordinate frame for specified point.*/
+        osg::Vec3d computeLocalUpVector(const Vec3d& position) const;
+
+    protected:
+
+        virtual ~CoordinateSystemNode() {}
+                
+        std::string             _format;
+        std::string             _cs;
+        ref_ptr<EllipsoidModel> _ellipsoidModel;
+
+};
+
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// implement inline methods.
+//
+inline void EllipsoidModel::convertLatLongHeightToXYZ(double latitude, double longitude, double height,
+                                      double& X, double& Y, double& Z) const
+{
+    // for details on maths see http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif
+    double sin_latitude = sin(latitude);
+    double cos_latitude = cos(latitude);
+    double N = _radiusEquator / sqrt( 1.0 - _eccentricitySquared*sin_latitude*sin_latitude);
+    X = (N+height)*cos_latitude*cos(longitude);
+    Y = (N+height)*cos_latitude*sin(longitude);
+    Z = (N*(1-_eccentricitySquared)+height)*sin_latitude;
+}
+
+
+inline void EllipsoidModel::convertXYZToLatLongHeight(double X, double Y, double Z,
+                                      double& latitude, double& longitude, double& height) const
+{
+    // http://www.colorado.edu/geography/gcraft/notes/datum/gif/xyzllh.gif
+    double p = sqrt(X*X + Y*Y);
+    double theta = atan2(Z*_radiusEquator , (p*_radiusPolar));
+    double eDashSquared = (_radiusEquator*_radiusEquator - _radiusPolar*_radiusPolar)/
+                          (_radiusPolar*_radiusPolar);
+
+    double sin_theta = sin(theta);
+    double cos_theta = cos(theta);
+
+    latitude = atan( (Z + eDashSquared*_radiusPolar*sin_theta*sin_theta*sin_theta) /
+                     (p - _eccentricitySquared*_radiusEquator*cos_theta*cos_theta*cos_theta) );
+    longitude = atan2(Y,X);
+
+    double sin_latitude = sin(latitude);
+    double N = _radiusEquator / sqrt( 1.0 - _eccentricitySquared*sin_latitude*sin_latitude);
+
+    height = p/cos(latitude) - N;
+}
+
+inline void EllipsoidModel::computeLocalToWorldTransformFromLatLongHeight(double latitude, double longitude, double height, osg::Matrixd& localToWorld) const
+{
+    double X, Y, Z;
+    convertLatLongHeightToXYZ(latitude,longitude,height,X,Y,Z);
+    computeLocalToWorldTransformFromXYZ(X,Y,Z,localToWorld);
+}
+
+inline void EllipsoidModel::computeLocalToWorldTransformFromXYZ(double X, double Y, double Z, osg::Matrixd& localToWorld) const
+{
+    localToWorld.makeTranslate(X,Y,Z);
+
+
+    // normalize X,Y,Z
+    double inverse_length = 1.0/sqrt(X*X + Y*Y + Z*Z);
+    
+    X *= inverse_length;
+    Y *= inverse_length;
+    Z *= inverse_length;
+
+    double length_XY = sqrt(X*X + Y*Y);
+    double inverse_length_XY = 1.0/length_XY;
+
+    // Vx = |(-Y,X,0)|
+    localToWorld(0,0) = -Y*inverse_length_XY;
+    localToWorld(0,1) = X*inverse_length_XY;
+    localToWorld(0,2) = 0.0;
+
+    // Vy = /(-Z*X/(sqrt(X*X+Y*Y), -Z*Y/(sqrt(X*X+Y*Y),sqrt(X*X+Y*Y))| 
+    double Vy_x = -Z*X*inverse_length_XY;
+    double Vy_y = -Z*Y*inverse_length_XY;
+    double Vy_z = length_XY;
+    inverse_length = 1.0/sqrt(Vy_x*Vy_x + Vy_y*Vy_y + Vy_z*Vy_z);            
+    localToWorld(1,0) = Vy_x*inverse_length;
+    localToWorld(1,1) = Vy_y*inverse_length;
+    localToWorld(1,2) = Vy_z*inverse_length;
+
+    // Vz = (X,Y,Z)
+    localToWorld(2,0) = X;
+    localToWorld(2,1) = Y;
+    localToWorld(2,2) = Z;
+}
+
+inline osg::Vec3d EllipsoidModel::computeLocalUpVector(double X, double Y, double Z) const
+{
+    osg::Vec3d normal(X,Y,Z);
+    normal.normalize();
+    return normal;
+}
+
+}
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrix
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrix (revision 8477)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrix (revision 8477)
@@ -0,0 +1,34 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_MATRIX
+#define OSG_MATRIX 1
+
+#include <osg/Config>
+#include <osg/Matrixd>
+#include <osg/Matrixf>
+
+namespace osg {
+
+#ifdef OSG_USE_FLOAT_MATRIX
+    typedef Matrixf Matrix;
+    typedef RefMatrixf RefMatrix;
+#else
+    typedef Matrixd Matrix;
+    typedef RefMatrixd RefMatrix;
+#endif
+
+} //namespace osg
+
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GraphicsContext
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GraphicsContext (revision 9376)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GraphicsContext (revision 9376)
@@ -0,0 +1,504 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_GRAPHICSCONTEXT
+#define OSG_GRAPHICSCONTEXT 1
+
+#include <osg/State>
+#include <osg/GraphicsThread>
+#include <vector>
+
+namespace osg {
+
+// forward declare osg::Camera
+class Camera;
+
+/** Base class for providing Windowing API agnostic access to creating and managing graphics context.*/
+class OSG_EXPORT GraphicsContext : public Object
+{
+    public:
+    
+        struct OSG_EXPORT ScreenIdentifier
+        {
+            ScreenIdentifier();
+
+            ScreenIdentifier(int in_screenNum);
+
+            ScreenIdentifier(const std::string& in_hostName,int in_displayNum, int in_screenNum);
+            
+            /** Return the display name in the form hostName::displayNum:screenNum. */    
+            std::string displayName() const;
+            
+            /** Read the DISPLAY environmental variable, and set the ScreenIdentifier accordingly.
+              * Note, if either of displayNum or screenNum are not defined then -1 is set respectively to
+              * signify the this parameter has not been set. When parameters are undefined one can call
+              * call setUndefinedScreenDetalstoDefaultScreen() method after readDISPLAY() to ensure valid values. */
+            void readDISPLAY();
+            
+            /** Set the screenIndentifier from the displayName string.
+              * Note, if either of displayNum or screenNum are not defined then -1 is set respectively to
+              * signify the this parameter has not been set. When parameters are undefined one can call
+              * call setUndefinedScreenDetalstoDefaultScreen() method after readDISPLAY() to ensure valid values. */
+            void setScreenIdentifier(const std::string& displayName);
+
+            /** Set any undefined displayNum or screenNum values (i.e. -1) to the default display & screen of 0 respectively.*/
+            void setUndefinedScreenDetailsToDefaultScreen()
+            {
+                if (displayNum<0) displayNum = 0;
+                if (screenNum<0) screenNum = 0;
+            }
+
+            std::string  hostName;
+            int displayNum;
+            int screenNum;
+        };
+    
+        /** GraphicsContext Traits object provides the specification of what type of graphics context is required.*/
+        struct Traits : public osg::Referenced, public ScreenIdentifier
+        {
+            Traits():
+                x(0),
+                y(0),
+                width(0),
+                height(0),
+                windowDecoration(false),
+                supportsResize(true),
+                red(8),
+                blue(8),
+                green(8),
+                alpha(0),
+                depth(24),
+                stencil(0),
+                sampleBuffers(0),
+                samples(0),
+                pbuffer(false),
+                quadBufferStereo(false),
+                doubleBuffer(false),
+                target(0),
+                format(0),
+                level(0),
+                face(0),
+                mipMapGeneration(false),
+                vsync(true),
+                useMultiThreadedOpenGLEngine(false),
+                useCursor(true),
+                sharedContext(0),
+                setInheritedWindowPixelFormat(false),
+                overrideRedirect(false) {}
+                            
+            // graphics context original and size
+            int x;
+            int y;
+            int width;
+            int height;
+            
+            // window decoration and behaviour
+            std::string windowName;
+            bool        windowDecoration;
+            bool        supportsResize;
+            
+            // buffer depths, 0 equals off.
+            unsigned int red;
+            unsigned int blue;
+            unsigned int green;
+            unsigned int alpha;
+            unsigned int depth;
+            unsigned int stencil;
+
+            // multi sample parameters
+            unsigned int sampleBuffers;
+            unsigned int samples;
+
+            // buffer configuration
+            bool pbuffer;
+            bool quadBufferStereo;
+            bool doubleBuffer;
+
+            // render to texture
+            GLenum          target;
+            GLenum          format;
+            unsigned int    level;
+            unsigned int    face;
+            unsigned int    mipMapGeneration;
+            
+            // V-sync
+            bool            vsync;
+            
+            // use multithreaded OpenGL-engine (OS X only)
+            bool            useMultiThreadedOpenGLEngine;
+            
+            // enable cursor
+            bool            useCursor;
+            
+            // shared context
+            GraphicsContext* sharedContext;
+            
+            osg::ref_ptr<osg::Referenced> inheritedWindowData;
+            
+            // ask the GraphicsWindow implementation to set the pixel format of an inherited window
+            bool setInheritedWindowPixelFormat;
+            
+            // X11 hint whether to override the window managers window size/position redirection
+            bool overrideRedirect;
+        };
+
+        /** Simple resolution structure used by WindowingSystemInterface to get and set screen resolution.
+          * Note the '0' value stands for 'unset'. */
+        struct ScreenSettings {
+            ScreenSettings() :
+                width(0),
+                height(0),
+                refreshRate(0),
+                colorDepth(0)
+            {}
+            ScreenSettings(int width, int height, double refreshRate=0, unsigned int colorDepth=0) :
+                width(width),
+                height(height),
+                refreshRate(refreshRate),
+                colorDepth(colorDepth)
+            {}
+
+            int width;
+            int height;
+            double refreshRate;         ///< Screen refresh rate, in Hz.
+            unsigned int colorDepth;    ///< RGB(A) color buffer depth.
+        };
+
+        typedef std::vector<ScreenSettings> ScreenSettingsList;
+
+        /** Callback to be implemented to provide access to Windowing API's ability to create Windows/pbuffers.*/
+        struct WindowingSystemInterface : public osg::Referenced
+        {
+            virtual unsigned int getNumScreens(const ScreenIdentifier& screenIdentifier = ScreenIdentifier()) = 0;
+
+            virtual void getScreenSettings(const ScreenIdentifier& screenIdentifier, ScreenSettings & resolution) = 0;
+
+            virtual bool setScreenSettings(const ScreenIdentifier& /*screenIdentifier*/, const ScreenSettings & /*resolution*/) { return false; }
+
+            virtual void enumerateScreenSettings(const ScreenIdentifier& screenIdentifier, ScreenSettingsList & resolutionList) = 0;
+
+            virtual GraphicsContext* createGraphicsContext(Traits* traits) = 0;
+            
+            virtual ~WindowingSystemInterface() {}
+
+
+            /** Gets screen resolution without using the ScreenResolution structure.
+              * \deprecated Provided only for backward compatibility. */
+            inline void getScreenResolution(const ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)
+            {
+                ScreenSettings settings;
+                getScreenSettings(screenIdentifier, settings);
+                width = settings.width;
+                height = settings.height;
+            }
+
+            /** Sets screen resolution without using the ScreenSettings structure.
+              * \deprecated Provided only for backward compatibility. */
+            inline bool setScreenResolution(const ScreenIdentifier& screenIdentifier, unsigned int width, unsigned int height)
+            {
+                return setScreenSettings(screenIdentifier, ScreenSettings(width, height));
+            }
+
+            /** \deprecated Provided only for backward compatibility. */
+            inline bool setScreenRefreshRate(const ScreenIdentifier& screenIdentifier, double refreshRate)
+            {
+                ScreenSettings settings;
+                getScreenSettings(screenIdentifier, settings);
+                settings.refreshRate = refreshRate;
+                return setScreenSettings(screenIdentifier, settings);
+            }
+        };
+    
+    
+        /** Set the query the windowing system for screens and create graphics context - this functor should be supplied by the windows toolkit. */
+        static void setWindowingSystemInterface(WindowingSystemInterface* wsInterface);
+        
+        /** Get the WindowingSystemInterface*/
+        static WindowingSystemInterface* getWindowingSystemInterface();
+    
+        /** Create a graphics context for a specified set of traits.*/
+        static GraphicsContext* createGraphicsContext(Traits* traits);
+        
+        /** Create a contextID for a new graphics context, this contextID is used to set up the osg::State associate with context.
+          * Automatically increments the usage count of the contextID to 1.*/
+        static unsigned int createNewContextID();
+
+        /** Get the current max ContextID.*/
+        static unsigned int getMaxContextID();
+
+        /** Increment the usage count associate with a contextID. The usage count specifies how many graphics contexts a specific contextID is shared between.*/
+        static void incrementContextIDUsageCount(unsigned int contextID);
+
+        /** Decrement the usage count associate with a contextID. Once the contextID goes to 0 the contextID is then free to be reused.*/
+        static void decrementContextIDUsageCount(unsigned int contextID);
+    
+        typedef std::vector<GraphicsContext*> GraphicsContexts;
+        
+        /** Get all the registered graphics contexts.*/
+        static GraphicsContexts getAllRegisteredGraphicsContexts();
+        
+        /** Get all the registered graphics contexts associated with a specific contextID.*/
+        static GraphicsContexts getRegisteredGraphicsContexts(unsigned int contextID);
+        
+        /** Get the GraphicsContext for doing background compilation for GraphicsContexts associated with specified contextID.*/
+        static void setCompileContext(unsigned int contextID, GraphicsContext* gc);
+
+        /** Get existing or create a new GraphicsContext to do background compilation for GraphicsContexts associated with specified contextID.*/
+        static  GraphicsContext* getOrCreateCompileContext(unsigned int contextID);
+        
+        /** Get the GraphicsContext for doing background compilation for GraphicsContexts associated with specified contextID.*/
+        static GraphicsContext* getCompileContext(unsigned int contextID);
+
+    public:
+    
+        /** Add operation to end of OperationQueue.*/
+        void add(Operation* operation);
+        
+        /** Remove operation from OperationQueue.*/
+        void remove(Operation* operation);
+
+        /** Remove named operation from OperationQueue.*/
+        void remove(const std::string& name);
+
+        /** Remove all operations from OperationQueue.*/
+        void removeAllOperations();
+
+        /** Run the operations. */
+        void runOperations();
+
+        typedef std::list< ref_ptr<Operation> > OperationQueue;
+        
+        /** Get the operations queue, not you must use the OperationsMutex when accessing the queue.*/
+        OperationQueue& getOperationsQueue() { return _operations; }
+
+        /** Get the operations queue mutex.*/
+        OpenThreads::Mutex* getOperationsMutex() { return &_operationsMutex; }
+
+        /** Get the operations queue block used to mark an empty queue, if you end items into the empty queue you must release this block.*/
+        osg::RefBlock* getOperationsBlock() { return _operationsBlock.get(); }
+
+        /** Get the current operations that is being run.*/
+        Operation* getCurrentOperation() { return _currentOperation.get(); }
+
+
+    public:
+    
+        /** Get the traits of the GraphicsContext.*/
+        inline const Traits* getTraits() const { return _traits.get(); }
+
+        /** Return whether a valid and usable GraphicsContext has been created.*/
+        virtual bool valid() const = 0;
+
+
+        /** Set the State object which tracks the current OpenGL state for this graphics context.*/
+        inline void setState(State* state) { _state = state; }
+        
+        /** Get the State object which tracks the current OpenGL state for this graphics context.*/
+        inline State* getState() { return _state.get(); }
+        
+        /** Get the const State object which tracks the current OpenGL state for this graphics context.*/
+        inline const State* getState() const { return _state.get(); }
+
+
+        /** Sets the clear color. */
+        inline void setClearColor(const Vec4& color) { _clearColor = color; }
+
+        /** Returns the clear color. */
+        inline const Vec4& getClearColor() const { return _clearColor; }
+        
+        /** Set the clear mask used in glClear(..).
+          * Defaults to 0 - so no clear is done by default by the GraphicsContext, instead the Camera's attached the GraphicsContext will do the clear. 
+          * GraphicsContext::setClearMask() is useful for when the Camera's Viewports don't conver the whole context, so the context will fill in the gaps. */
+        inline void setClearMask(GLbitfield mask) { _clearMask = mask; }
+
+        /** Get the clear mask.*/
+        inline GLbitfield getClearMask() const { return _clearMask; }
+        
+        /** Do an OpenGL clear of the full graphics context/window.
+          * Note, must only be called from a thread with this context current.*/
+        virtual void clear();
+        
+
+        /** Realize the GraphicsContext.*/
+        bool realize();
+
+        /** close the graphics context.
+          * close(bool) stops any associated graphics threads, releases the contextID for the GraphicsContext then
+          * optional calls closeImplementation() to do the actual deletion of the graphics.  This call is made optional
+          * as there are times when the graphics context has already been deleted externally and only the OSG side
+          * of the its data need to be closed down. */
+        void close(bool callCloseImplementation=true);
+
+        /** swap the front and back buffers.*/
+        void swapBuffers();
+
+        /** Return true if the graphics context has been realized and is ready to use.*/
+        inline bool isRealized() const { return isRealizedImplementation(); }
+
+
+        /** Make this graphics context current.
+          * Implemented by calling makeCurrentImplementation(). 
+          * Returns true on success. */
+        bool makeCurrent();
+        
+        /** Make this graphics context current with specified read context.
+          * Implemented by calling makeContextCurrentImplementation().
+          * Returns true on success. */
+        bool makeContextCurrent(GraphicsContext* readContext);
+        
+        /** Release the graphics context.
+          * Returns true on success. */
+        bool releaseContext();
+        
+        /** Return true if the current thread has this OpenGL graphics context.*/
+        inline bool isCurrent() const { return _threadOfLastMakeCurrent == OpenThreads::Thread::CurrentThread(); }
+
+        /** Bind the graphics context to associated texture.*/
+        inline void bindPBufferToTexture(GLenum buffer) { bindPBufferToTextureImplementation(buffer); }
+
+
+
+        /** Create a graphics thread to the graphics context, so that the thread handles all OpenGL operations.*/
+        void createGraphicsThread();
+
+        /** Assign a graphics thread to the graphics context, so that the thread handles all OpenGL operations.*/
+        void setGraphicsThread(GraphicsThread* gt);
+
+        /** Get the graphics thread assigned the graphics context.*/
+        GraphicsThread* getGraphicsThread() { return _graphicsThread.get(); }
+
+        /** Get the const graphics thread assigned the graphics context.*/
+        const GraphicsThread* getGraphicsThread() const { return _graphicsThread.get(); }
+
+
+        /** Realize the GraphicsContext implementation, 
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual bool realizeImplementation() = 0;
+
+        /** Return true if the graphics context has been realized, and is ready to use, implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual bool isRealizedImplementation() const = 0;
+
+        /** Close the graphics context implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual void closeImplementation() = 0;
+
+        /** Make this graphics context current implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual bool makeCurrentImplementation() = 0;
+        
+        /** Make this graphics context current with specified read context implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual bool makeContextCurrentImplementation(GraphicsContext* readContext) = 0;
+
+        /** Release the graphics context implementation.*/
+        virtual bool releaseContextImplementation() = 0;
+
+        /** Pure virtual, Bind the graphics context to associated texture implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual void bindPBufferToTextureImplementation(GLenum buffer) = 0;
+
+        /** Swap the front and back buffers implementation.
+          * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */
+        virtual void swapBuffersImplementation() = 0;
+
+
+
+        /** resized method should be called when the underlying window has been resized and the GraphicsWindow and associated Cameras must
+            be updated to keep in sync with the new size. */
+        void resized(int x, int y, int width, int height)
+        {
+            if (_resizedCallback.valid()) _resizedCallback->resizedImplementation(this, x, y, width, height);
+            else resizedImplementation(x, y, width, height);
+        }
+
+        struct ResizedCallback : public osg::Referenced
+        {
+            virtual void resizedImplementation(GraphicsContext* gc, int x, int y, int width, int height) = 0;
+        };
+
+        /** Set the resized callback which overrides the GraphicsConext::realizedImplementation(), allow developers to provide custom behavior
+          * in response to a window being resized.*/
+        void setResizedCallback(ResizedCallback* rc) { _resizedCallback = rc; }
+
+        /** Get the resized callback which overrides the GraphicsConext::realizedImplementation().*/
+        ResizedCallback* getResizedCallback() { return _resizedCallback.get(); }
+
+        /** Get the const resized callback which overrides the GraphicsConext::realizedImplementation().*/
+        const ResizedCallback* getResizedCallback() const { return _resizedCallback.get(); }
+
+        /** resized implementation, by default resizes the viewports and aspect ratios the cameras associated with the graphics Window. */
+        virtual void resizedImplementation(int x, int y, int width, int height);
+
+
+        typedef std::list< osg::Camera* > Cameras;
+
+        /** Get the the list of cameras associated with this graphics context.*/
+        Cameras& getCameras() { return _cameras; }
+
+        /** Get the the const list of cameras associated with this graphics context.*/
+        const Cameras& getCameras() const { return _cameras; }
+
+    public:
+
+        virtual bool isSameKindAs(const Object* object) const { return dynamic_cast<const GraphicsContext*>(object)!=0; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "GraphicsContext"; }
+
+    protected:
+        
+        GraphicsContext();
+        GraphicsContext(const GraphicsContext&, const osg::CopyOp&);
+
+        virtual ~GraphicsContext();
+
+        virtual Object* cloneType() const { return 0; }
+        virtual Object* clone(const CopyOp&) const { return 0; }
+
+        /** Register a GraphicsContext.*/
+        static void registerGraphicsContext(GraphicsContext* gc);
+
+        /** Unregister a GraphicsContext.*/
+        static void unregisterGraphicsContext(GraphicsContext* gc);
+
+
+        void addCamera(osg::Camera* camera);
+        void removeCamera(osg::Camera* camera);
+        
+        Cameras _cameras;
+
+        friend class osg::Camera;
+
+        ref_ptr<Traits>         _traits;        
+        ref_ptr<State>          _state;
+
+        Vec4                    _clearColor;
+        GLbitfield              _clearMask;
+
+        OpenThreads::Thread*    _threadOfLastMakeCurrent;
+        
+        OpenThreads::Mutex                  _operationsMutex;
+        osg::ref_ptr<osg::RefBlock>         _operationsBlock;
+        OperationQueue                      _operations;
+        osg::ref_ptr<Operation>             _currentOperation;
+
+        ref_ptr<GraphicsThread>             _graphicsThread;
+        
+        ref_ptr<ResizedCallback>            _resizedCallback;
+        
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/VertexProgram
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/VertexProgram (revision 9380)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/VertexProgram (revision 9380)
@@ -0,0 +1,320 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_VERTEXPROGRAM
+#define OSG_VERTEXPROGRAM 1
+
+#include <osg/StateAttribute>
+#include <osg/Vec4>
+#include <osg/Matrix>
+#include <osg/buffered_value>
+
+#include <map>
+#include <string>
+
+// if not defined by gl.h use the definition found in:
+// http://oss.sgi.com/projects/ogl-sample/registry/ARB/vertex_program.txt
+#ifndef GL_ARB_vertex_program
+#define GL_VERTEX_PROGRAM_ARB                              0x8620
+#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB                   0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB                     0x8643
+#define GL_COLOR_SUM_ARB                                   0x8458
+#define GL_PROGRAM_FORMAT_ASCII_ARB                        0x8875
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB                 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB                    0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB                  0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB                    0x8625
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB              0x886A
+#define GL_CURRENT_VERTEX_ATTRIB_ARB                       0x8626
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB                 0x8645
+#define GL_PROGRAM_LENGTH_ARB                              0x8627
+#define GL_PROGRAM_FORMAT_ARB                              0x8876
+#define GL_PROGRAM_BINDING_ARB                             0x8677
+#define GL_PROGRAM_INSTRUCTIONS_ARB                        0x88A0
+#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB                    0x88A1
+#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB                 0x88A2
+#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB             0x88A3
+#define GL_PROGRAM_TEMPORARIES_ARB                         0x88A4
+#define GL_MAX_PROGRAM_TEMPORARIES_ARB                     0x88A5
+#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB                  0x88A6
+#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB              0x88A7
+#define GL_PROGRAM_PARAMETERS_ARB                          0x88A8
+#define GL_MAX_PROGRAM_PARAMETERS_ARB                      0x88A9
+#define GL_PROGRAM_NATIVE_PARAMETERS_ARB                   0x88AA
+#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB               0x88AB
+#define GL_PROGRAM_ATTRIBS_ARB                             0x88AC
+#define GL_MAX_PROGRAM_ATTRIBS_ARB                         0x88AD
+#define GL_PROGRAM_NATIVE_ATTRIBS_ARB                      0x88AE
+#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB                  0x88AF
+#define GL_PROGRAM_ADDRESS_REGISTERS_ARB                   0x88B0
+#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB               0x88B1
+#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB            0x88B2
+#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB        0x88B3
+#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB                0x88B4
+#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB                  0x88B5
+#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB                 0x88B6
+#define GL_PROGRAM_STRING_ARB                              0x8628
+#define GL_PROGRAM_ERROR_POSITION_ARB                      0x864B
+#define GL_CURRENT_MATRIX_ARB                              0x8641
+#define GL_TRANSPOSE_CURRENT_MATRIX_ARB                    0x88B7
+#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB                  0x8640
+#define GL_MAX_VERTEX_ATTRIBS_ARB                          0x8869
+#define GL_MAX_PROGRAM_MATRICES_ARB                        0x862F
+#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB              0x862E
+#define GL_PROGRAM_ERROR_STRING_ARB                        0x8874
+#define GL_MATRIX0_ARB                                     0x88C0
+#define GL_MATRIX1_ARB                                     0x88C1
+#define GL_MATRIX2_ARB                                     0x88C2
+#define GL_MATRIX3_ARB                                     0x88C3
+#define GL_MATRIX4_ARB                                     0x88C4
+#define GL_MATRIX5_ARB                                     0x88C5
+#define GL_MATRIX6_ARB                                     0x88C6
+#define GL_MATRIX7_ARB                                     0x88C7
+#define GL_MATRIX8_ARB                                     0x88C8
+#define GL_MATRIX9_ARB                                     0x88C9
+#define GL_MATRIX10_ARB                                    0x88CA
+#define GL_MATRIX11_ARB                                    0x88CB
+#define GL_MATRIX12_ARB                                    0x88CC
+#define GL_MATRIX13_ARB                                    0x88CD
+#define GL_MATRIX14_ARB                                    0x88CE
+#define GL_MATRIX15_ARB                                    0x88CF
+#define GL_MATRIX16_ARB                                    0x88D0
+#define GL_MATRIX17_ARB                                    0x88D1
+#define GL_MATRIX18_ARB                                    0x88D2
+#define GL_MATRIX19_ARB                                    0x88D3
+#define GL_MATRIX20_ARB                                    0x88D4
+#define GL_MATRIX21_ARB                                    0x88D5
+#define GL_MATRIX22_ARB                                    0x88D6
+#define GL_MATRIX23_ARB                                    0x88D7
+#define GL_MATRIX24_ARB                                    0x88D8
+#define GL_MATRIX25_ARB                                    0x88D9
+#define GL_MATRIX26_ARB                                    0x88DA
+#define GL_MATRIX27_ARB                                    0x88DB
+#define GL_MATRIX28_ARB                                    0x88DC
+#define GL_MATRIX29_ARB                                    0x88DD
+#define GL_MATRIX30_ARB                                    0x88DE
+#define GL_MATRIX31_ARB                                    0x88DF
+#endif
+
+
+namespace osg {
+
+
+
+/** VertexProgram - encapsulates the OpenGL ARB vertex program state. */
+class OSG_EXPORT VertexProgram : public StateAttribute
+{
+    public:
+
+        VertexProgram();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        VertexProgram(const VertexProgram& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osg, VertexProgram, VERTEXPROGRAM);
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const osg::StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(VertexProgram,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_vertexProgram)
+
+            return 0; // passed all the above comparison macros, must be equal.
+        }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_VERTEX_PROGRAM_ARB);
+            return true;
+        }
+
+        // data access methods.
+
+        /** Get the handle to the vertex program ID for the current context. */
+        inline GLuint& getVertexProgramID(unsigned int contextID) const
+        {
+            return _vertexProgramIDList[contextID];
+        }
+
+        
+        /** Set the vertex program using a C style string. */
+        inline void setVertexProgram( const char* program ) 
+        { 
+            _vertexProgram = program; 
+            dirtyVertexProgramObject();
+        }
+
+        /** Set the vertex program using C++ style string. */
+        inline void setVertexProgram( const std::string& program )
+        {
+            _vertexProgram = program;
+            dirtyVertexProgramObject();
+        }
+
+        /** Get the vertex program. */
+        inline const std::string& getVertexProgram() const { return _vertexProgram; }
+
+        /** Set Program Parameters */
+        inline void setProgramLocalParameter(const GLuint index, const Vec4& p)
+        {
+            _programLocalParameters[index] = p;
+        }
+
+        typedef std::map<GLuint,Vec4> LocalParamList;
+
+        /** Set list of Program Parameters */
+        inline void setLocalParameters(const LocalParamList& lpl) { _programLocalParameters = lpl; }
+
+        /** Get list of Program Parameters */
+        inline LocalParamList& getLocalParameters() { return _programLocalParameters; }
+
+        /** Get const list of Program Parameters */
+        inline const LocalParamList& getLocalParameters() const { return _programLocalParameters; }
+
+        /** Matrix */
+        inline void setMatrix(const GLenum mode, const Matrix& matrix)
+        {
+            _matrixList[mode] = matrix;
+        }
+
+        typedef std::map<GLenum,Matrix> MatrixList;
+
+        /** Set list of Matrices */
+        inline void setMatrices(const MatrixList& matrices) { _matrixList = matrices; }
+
+        /** Get list of Matrices */
+        inline MatrixList& getMatrices() { return _matrixList; }
+
+        /** Get list of Matrices */
+        inline const MatrixList& getMatrices() const { return _matrixList; }
+
+        /** Force a recompile on next apply() of associated OpenGL vertex program objects. */
+        void dirtyVertexProgramObject();        
+
+        /** Use deleteVertexProgramObject instead of glDeletePrograms to allow
+          * OpenGL Vertex Program objects to cached until they can be deleted
+          * by the OpenGL context in which they were created, specified
+          * by contextID.
+        */
+        static void deleteVertexProgramObject(unsigned int contextID,GLuint handle);
+
+        /** Flush all the cached vertex programs which need to be deleted
+          * in the OpenGL context related to contextID.
+        */
+        static void flushDeletedVertexProgramObjects(unsigned int contextID,double currentTime, double& availableTime);
+
+        /** discard all the cached vertex programs which need to be deleted
+          * in the OpenGL context related to contextID.
+          * Note, unlike flush no OpenGL calls are made, instead the handles are all removed.
+          * this call is useful for when an OpenGL context has been destroyed.
+        */
+        static void discardDeletedVertexProgramObjects(unsigned int contextID);
+
+        virtual void apply(State& state) const;
+
+        virtual void compileGLObjects(State& state) const { apply(state); }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** Release any OpenGL objects in specified graphics context if State
+          * object is passed, otherwise release OpenGL objects for all graphics contexts if
+          * State object pointer is NULL.
+        */
+        virtual void releaseGLObjects(State* state=0) const;
+
+        /** Extensions class which encapsulates the querying of extensions and
+          * associated function pointers, and provide convenience wrappers to 
+          * check for the extensions or use the associated functions.
+        */
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setVertexProgramSupported(bool flag) { _isVertexProgramSupported=flag; }
+                bool isVertexProgramSupported() const { return _isVertexProgramSupported; }
+
+                void glBindProgram(GLenum target, GLuint id) const;
+                void glGenPrograms(GLsizei n, GLuint *programs) const;
+                void glDeletePrograms(GLsizei n, GLuint *programs) const;
+                void glProgramString(GLenum target, GLenum format, GLsizei len, const void *string) const; 
+                void glProgramLocalParameter4fv(GLenum target, GLuint index, const GLfloat *params) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool _isVertexProgramSupported;
+                
+                typedef void (APIENTRY * BindProgramProc) (GLenum target, GLuint id);
+                typedef void (APIENTRY * GenProgramsProc) (GLsizei n, GLuint *programs);
+                typedef void (APIENTRY * DeleteProgramsProc) (GLsizei n, GLuint *programs);
+                typedef void (APIENTRY * ProgramStringProc) (GLenum target, GLenum format, GLsizei len, const void *string); 
+                typedef void (APIENTRY * ProgramLocalParameter4fvProc) (GLenum target, GLuint index, const GLfloat *params);
+
+                BindProgramProc _glBindProgram;
+                GenProgramsProc _glGenPrograms;
+                DeleteProgramsProc _glDeletePrograms;
+                ProgramStringProc _glProgramString;
+                ProgramLocalParameter4fvProc _glProgramLocalParameter4fv;
+ 
+        };
+        
+        /** Function to call to get the extension of a specified context.
+          * If the Extension object for that context has not yet been created
+          * and the 'createIfNotInitalized' flag been set to false then returns NULL.
+          * If 'createIfNotInitalized' is true then the Extensions object is
+          * automatically created. However, in this case the extension object
+          * will only be created with the graphics context associated with ContextID.
+        */
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** The setExtensions method allows users to override the extensions across graphics contexts.
+          * Typically used when you have different extensions supported across graphics pipes
+          * but need to ensure that they all use the same low common denominator extensions.
+        */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+    protected:
+
+
+        virtual ~VertexProgram();
+
+        typedef buffered_value<GLuint> VertexProgramIDList;
+        mutable VertexProgramIDList _vertexProgramIDList;
+
+        std::string     _vertexProgram;
+
+        LocalParamList  _programLocalParameters;
+
+        MatrixList  _matrixList;
+};
+
+
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Shader
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Shader (revision 7908)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Shader (revision 7908)
@@ -0,0 +1,199 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ * Copyright (C) 2003-2005 3Dlabs Inc. Ltd.
+ * Copyright (C) 2004-2005 Nathan Cournia
+ * Copyright (C) 2008 Zebra Imaging
+ *
+ * This application is open source and may be redistributed and/or modified   
+ * freely and without restriction, both in commericial and non commericial
+ * applications, as long as this copyright notice is maintained.
+ * 
+ * This application is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+*/
+
+/* file:   include/osg/Shader
+ * author: Mike Weiblen 2008-01-02
+*/
+
+#ifndef OSG_SHADER
+#define OSG_SHADER 1
+
+
+#include <osg/GL2Extensions>
+#include <osg/Object>
+#include <osg/buffered_value>
+
+#include <set>
+
+namespace osg {
+
+class Program;
+
+///////////////////////////////////////////////////////////////////////////
+/** osg::Shader is an application-level abstraction of an OpenGL glShader.
+  * It is a container to load the shader source code text and manage its
+  * compilation.
+  * An osg::Shader may be attached to more than one osg::Program.
+  * Shader will automatically manage per-context instancing of the
+  * internal objects, if that is necessary for a particular display
+  * configuration.
+  */
+
+class OSG_EXPORT Shader : public osg::Object
+{
+    public:
+
+        enum Type {
+            VERTEX = GL_VERTEX_SHADER,
+            FRAGMENT = GL_FRAGMENT_SHADER,
+            GEOMETRY = GL_GEOMETRY_SHADER_EXT,
+            UNDEFINED = -1
+        };
+
+        Shader( Type type = UNDEFINED);
+        Shader( Type type, const std::string& source );
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Shader(const Shader& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, Shader);
+
+        int compare(const Shader& rhs) const;
+
+        bool setType( Type t );
+        
+
+        /** Load the Shader's source code text from a string. */
+        void setShaderSource( const std::string& sourceText );
+
+        /** Read shader source from file and then constructor shader of specified type.
+          * Return the resulting Shader or 0 if no valid shader source code be read.*/
+        static Shader* readShaderFile( Type type, const std::string& fileName );
+
+        /** Load the Shader's source code text from a file. */
+        bool loadShaderSourceFromFile( const std::string& fileName );
+
+        /** Query the shader's source code text */
+        inline const std::string& getShaderSource() const { return _shaderSource; }
+
+        /** Get the Shader type as an enum. */
+        inline Type getType() const { return _type; }
+
+        /** Get the Shader type as a descriptive string. */
+        const char* getTypename() const;
+
+        /** Set file name for the shader source code. */
+        inline void setFileName(const std::string& fileName) { _shaderFileName = fileName; }
+
+        /** Get filename to which the shader source code belongs. */
+        inline const std::string& getFileName() const { return _shaderFileName; }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** release OpenGL objects in specified graphics context if State
+            object is passed, otherwise release OpenGL objects for all graphics context if
+            State object pointer NULL.*/
+        void releaseGLObjects(osg::State* state=0) const;
+
+        /** Mark our PCSs as needing recompilation.
+          * Also mark Programs that depend on us as needing relink */
+        void dirtyShader();        
+
+        /** If needed, compile the PCS's glShader */
+        void compileShader(unsigned int contextID) const;
+
+        /** For a given GL context, attach a glShader to a glProgram */
+        void attachShader(unsigned int contextID, GLuint program) const;
+
+        /** For a given GL context, detach a glShader to a glProgram */
+        void detachShader(unsigned int contextID, GLuint program) const;
+
+        /** Query InfoLog from a glShader */
+        bool getGlShaderInfoLog(unsigned int contextID, std::string& log) const;
+
+        /** Mark internal glShader for deletion.
+          * Deletion requests are queued until they can be executed
+          * in the proper GL context. */
+        static void deleteGlShader(unsigned int contextID, GLuint shader);
+
+        /** flush all the cached glShaders which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void flushDeletedGlShaders(unsigned int contextID,double currentTime, double& availableTime);
+
+        /** discard all the cached glShaders which need to be deleted in the OpenGL context related to contextID.
+          * Note, unlike flush no OpenGL calls are made, instead the handles are all removed.
+          * this call is useful for when an OpenGL context has been destroyed. */
+        static void discardDeletedGlShaders(unsigned int contextID);
+
+        static Shader::Type getTypeId( const std::string& tname );
+
+    protected:
+        /** PerContextShader (PCS) is an OSG-internal encapsulation of glShader per-GL context. */
+        class PerContextShader : public osg::Referenced
+        {
+            public:
+                PerContextShader(const Shader* shader, unsigned int contextID);
+
+                GLuint getHandle() const {return _glShaderHandle;}
+
+                void requestCompile();
+                void compileShader();
+                bool needsCompile() const {return _needsCompile;}
+                bool isCompiled() const {return _isCompiled;}
+                bool getInfoLog( std::string& infoLog ) const;
+
+                /** Attach our glShader to a glProgram */
+                void attachShader(GLuint program) const;
+
+                /** Detach our glShader from a glProgram */
+                void detachShader(GLuint program) const;
+
+            protected:        /*methods*/
+                ~PerContextShader();
+
+            protected:        /*data*/
+                /** Pointer to our parent osg::Shader */
+                const Shader* _shader;
+                /** Pointer to this context's extension functions. */
+                osg::ref_ptr<osg::GL2Extensions> _extensions;
+                /** Handle to the actual glShader. */
+                GLuint _glShaderHandle;
+                /** Does our glShader need to be recompiled? */
+                bool _needsCompile;
+                /** Is our glShader successfully compiled? */
+                bool _isCompiled;
+                const unsigned int _contextID;
+
+            private:
+                PerContextShader();        // disallowed
+                PerContextShader(const PerContextShader&);        // disallowed
+                PerContextShader& operator=(const PerContextShader&);        // disallowed
+        };
+
+    protected:        /*methods*/
+        virtual ~Shader();
+
+        PerContextShader* getPCS(unsigned int contextID) const;
+
+        friend class osg::Program;
+        bool addProgramRef( osg::Program* program );
+        bool removeProgramRef( osg::Program* program );
+
+    protected:        /*data*/
+        Type _type;
+        std::string _shaderSource;
+        std::string _shaderFileName;
+        /** osg::Programs that this osg::Shader is attached to */
+        typedef std::set< osg::Program* > ProgramSet;
+        ProgramSet _programSet;
+        mutable osg::buffered_value< osg::ref_ptr<PerContextShader> > _pcsList;
+
+    private:
+        Shader& operator=(const Shader&);        // disallowed
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ClipPlane
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ClipPlane (revision 7812)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ClipPlane (revision 7812)
@@ -0,0 +1,118 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_CLIPPLANE
+#define OSG_CLIPPLANE 1
+
+#include <osg/Vec4d>
+#include <osg/Plane>
+#include <osg/StateAttribute>
+
+namespace osg {
+
+/** Encapsulates OpenGL glClipPlane().
+*/
+class OSG_EXPORT ClipPlane : public StateAttribute
+{
+    public :
+
+        ClipPlane();
+        inline ClipPlane(unsigned int no):_clipPlaneNum(no) {}
+        inline ClipPlane(unsigned int no,const Vec4d& plane):_clipPlaneNum(no) { setClipPlane(plane); }
+        inline ClipPlane(unsigned int no,const Plane& plane):_clipPlaneNum(no) { setClipPlane(plane); }
+        inline ClipPlane(unsigned int no,double a,double b,double c,double d): _clipPlaneNum(no) { setClipPlane(a,b,c,d); }
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        ClipPlane(const ClipPlane& cp,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(cp,copyop)
+        {
+            _clipPlane[0]=cp._clipPlane[0];
+            _clipPlane[1]=cp._clipPlane[1];
+            _clipPlane[2]=cp._clipPlane[2];
+            _clipPlane[3]=cp._clipPlane[3];
+            _clipPlaneNum=cp._clipPlaneNum;
+        }
+        
+        virtual osg::Object* cloneType() const { return new ClipPlane( _clipPlaneNum ); }
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new ClipPlane(*this,copyop); }
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const ClipPlane *>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "ClipPlane"; }
+        virtual Type getType() const { return CLIPPLANE; }
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // Check for equal types, then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macros below.
+            COMPARE_StateAttribute_Types(ClipPlane,sa)
+
+            // Compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_clipPlaneNum)
+            COMPARE_StateAttribute_Parameter(_clipPlane[0])
+            COMPARE_StateAttribute_Parameter(_clipPlane[1])
+            COMPARE_StateAttribute_Parameter(_clipPlane[2])
+            COMPARE_StateAttribute_Parameter(_clipPlane[3])
+
+            return 0; // Passed all the above comparison macros, so must be equal.
+        }
+
+        virtual unsigned int getMember() const { return _clipPlaneNum; }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode((GLMode)(GL_CLIP_PLANE0+_clipPlaneNum));
+            return true;
+        }
+
+
+        /** Set the clip plane with the given Plane. */
+        void setClipPlane(const Plane& plane) 
+        {
+           _clipPlane.set(plane[0],plane[1],plane[2],plane[3]);
+        }
+
+        /** Defines the plane as [ a b c d ]. */
+        void setClipPlane(double a,double b,double c,double d)
+        {
+            _clipPlane.set(a,b,c,d);
+        }
+
+        /** Set the clip plane with the given Vec4. */
+        inline void setClipPlane(const Vec4d& plane) { _clipPlane = plane; }
+
+        /** Gets the clip plane as a Vec4d. */
+        const Vec4d& getClipPlane() const { return _clipPlane; }
+
+
+        /** Sets the clip plane number. */
+        void setClipPlaneNum(unsigned int num);
+
+        /** Gets the clip plane number. */
+        unsigned int getClipPlaneNum() const;
+
+        /** Applies the clip plane's state to the OpenGL state machine. */
+        virtual void apply(State& state) const;
+
+    protected :
+    
+        virtual ~ClipPlane();
+        
+        Vec4d               _clipPlane;
+        unsigned int        _clipPlaneNum;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Notify
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Notify (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Notify (revision 5328)
@@ -0,0 +1,74 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_NOTIFY
+#define OSG_NOTIFY 1
+
+#include <osg/Export>
+
+#include <ostream>
+
+namespace osg {
+
+/** Range of notify levels from DEBUG_FP through to FATAL, ALWAYS
+  * is reserved for forcing the absorption of all messages.  The
+  * keywords are also used verbatim when specified by the environmental
+  * variable OSGNOTIFYLEVEL.  See documentation on osg::notify() for
+  * further details.
+  */
+enum NotifySeverity {
+    ALWAYS=0,
+    FATAL=1,
+    WARN=2,
+    NOTICE=3,
+    INFO=4,
+    DEBUG_INFO=5,
+    DEBUG_FP=6
+};
+
+/** set the notify level, overriding the default or the value set by
+  * the environmental variable OSGNOTIFYLEVEL.
+  */
+extern OSG_EXPORT void setNotifyLevel(NotifySeverity severity);
+
+/** get the notify level. */
+extern OSG_EXPORT NotifySeverity getNotifyLevel();
+
+/** is notification enabled, given the current setNotifyLevel() setting? */
+extern OSG_EXPORT bool isNotifyEnabled(NotifySeverity severity);
+
+/** initialize notify level. */
+extern OSG_EXPORT bool initNotifyLevel();
+
+/** notify messaging function for providing fatal through to verbose
+  * debugging messages.  Level of messages sent to the console can
+  * be controlled by setting the NotifyLevel either within your 
+  * application or via the an environmental variable. For instance
+  * setenv OSGNOTIFYLEVEL DEBUG (for tsh), export OSGNOTIFYLEVEL=DEBUG
+  * (for bourne shell) or set OSGNOTIFYLEVEL=DEBUG (for Windows) all
+  * tell the osg to redirect all debugging and more important messages
+  * to the console (useful for debugging :-)  setting ALWAYS will force
+  * all messages to be absorbed, which might be appropriate for final
+  * applications.  Default NotifyLevel is NOTICE.  Check the enum 
+  * NotifySeverity for full range of possibilities.  To use the notify
+  * with your code simply use the notify function as a normal file
+  * stream (like cout) i.e osg::notify(osg::DEBUG) << "Hello Bugs!"<<endl;
+  */
+  
+extern OSG_EXPORT std::ostream& notify(const NotifySeverity severity);
+
+inline std::ostream& notify(void) { return notify(osg::INFO); }
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixd
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixd (revision 8868)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixd (revision 8868)
@@ -0,0 +1,815 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_MATRIXD
+#define OSG_MATRIXD 1
+
+#include <osg/Object>
+#include <osg/Vec3d>
+#include <osg/Vec4d>
+#include <osg/Quat>
+
+namespace osg {
+
+class Matrixf;
+
+class OSG_EXPORT Matrixd
+{
+    public:
+    
+        typedef double value_type;
+
+        inline Matrixd() { makeIdentity(); }
+        inline Matrixd( const Matrixd& mat) { set(mat.ptr()); }
+        Matrixd( const Matrixf& mat );
+        inline explicit Matrixd( float const * const ptr ) { set(ptr); }
+        inline explicit Matrixd( double const * const ptr ) { set(ptr); }
+        inline explicit Matrixd( const Quat& quat ) { makeRotate(quat); }
+
+        Matrixd(value_type a00, value_type a01, value_type a02, value_type a03,
+                value_type a10, value_type a11, value_type a12, value_type a13,
+                value_type a20, value_type a21, value_type a22, value_type a23,
+                value_type a30, value_type a31, value_type a32, value_type a33);
+
+        ~Matrixd() {}
+
+        int compare(const Matrixd& m) const;
+
+        bool operator < (const Matrixd& m) const { return compare(m)<0; }
+        bool operator == (const Matrixd& m) const { return compare(m)==0; }
+        bool operator != (const Matrixd& m) const { return compare(m)!=0; }
+
+        inline value_type& operator()(int row, int col) { return _mat[row][col]; }
+        inline value_type operator()(int row, int col) const { return _mat[row][col]; }
+
+        inline bool valid() const { return !isNaN(); }
+        inline bool isNaN() const { return osg::isNaN(_mat[0][0]) || osg::isNaN(_mat[0][1]) || osg::isNaN(_mat[0][2]) || osg::isNaN(_mat[0][3]) ||
+                                                 osg::isNaN(_mat[1][0]) || osg::isNaN(_mat[1][1]) || osg::isNaN(_mat[1][2]) || osg::isNaN(_mat[1][3]) ||
+                                                 osg::isNaN(_mat[2][0]) || osg::isNaN(_mat[2][1]) || osg::isNaN(_mat[2][2]) || osg::isNaN(_mat[2][3]) ||
+                                                 osg::isNaN(_mat[3][0]) || osg::isNaN(_mat[3][1]) || osg::isNaN(_mat[3][2]) || osg::isNaN(_mat[3][3]); }
+
+        inline Matrixd& operator = (const Matrixd& rhs)
+        {
+            if( &rhs == this ) return *this;
+            set(rhs.ptr());
+            return *this;
+        }
+        
+        Matrixd& operator = (const Matrixf& other);
+
+        inline void set(const Matrixd& rhs) { set(rhs.ptr()); }
+
+        void set(const Matrixf& rhs);
+
+        inline void set(float const * const ptr)
+        {
+            value_type* local_ptr = (value_type*)_mat;
+            for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i];
+        }
+        
+        inline void set(double const * const ptr)
+        {
+            value_type* local_ptr = (value_type*)_mat;
+            for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i];
+        }
+
+        void set(value_type a00, value_type a01, value_type a02,value_type a03,
+                 value_type a10, value_type a11, value_type a12,value_type a13,
+                 value_type a20, value_type a21, value_type a22,value_type a23,
+                 value_type a30, value_type a31, value_type a32,value_type a33);
+                  
+        value_type * ptr() { return (value_type*)_mat; }
+        const value_type * ptr() const { return (const value_type *)_mat; }
+
+        bool isIdentity() const
+        {
+            return _mat[0][0]==1.0 && _mat[0][1]==0.0 && _mat[0][2]==0.0 &&  _mat[0][3]==0.0 &&
+                   _mat[1][0]==0.0 && _mat[1][1]==1.0 && _mat[1][2]==0.0 &&  _mat[1][3]==0.0 &&
+                   _mat[2][0]==0.0 && _mat[2][1]==0.0 && _mat[2][2]==1.0 &&  _mat[2][3]==0.0 &&
+                   _mat[3][0]==0.0 && _mat[3][1]==0.0 && _mat[3][2]==0.0 &&  _mat[3][3]==1.0;
+        }
+
+        void makeIdentity();
+        
+        void makeScale( const Vec3f& );
+        void makeScale( const Vec3d& );
+        void makeScale( value_type, value_type, value_type );
+        
+        void makeTranslate( const Vec3f& );
+        void makeTranslate( const Vec3d& );
+        void makeTranslate( value_type, value_type, value_type );
+        
+        void makeRotate( const Vec3f& from, const Vec3f& to );
+        void makeRotate( const Vec3d& from, const Vec3d& to );
+        void makeRotate( value_type angle, const Vec3f& axis );
+        void makeRotate( value_type angle, const Vec3d& axis );
+        void makeRotate( value_type angle, value_type x, value_type y, value_type z );
+        void makeRotate( const Quat& );
+        void makeRotate( value_type angle1, const Vec3f& axis1, 
+                         value_type angle2, const Vec3f& axis2,
+                         value_type angle3, const Vec3f& axis3);
+        void makeRotate( value_type angle1, const Vec3d& axis1, 
+                         value_type angle2, const Vec3d& axis2,
+                         value_type angle3, const Vec3d& axis3);
+
+
+        /** decompose the matrix into translation, rotation, scale and scale orientation.*/        
+        void decompose( osg::Vec3f& translation,
+                        osg::Quat& rotation, 
+                        osg::Vec3f& scale, 
+                        osg::Quat& so ) const;
+
+        /** decompose the matrix into translation, rotation, scale and scale orientation.*/        
+        void decompose( osg::Vec3d& translation,
+                        osg::Quat& rotation, 
+                        osg::Vec3d& scale, 
+                        osg::Quat& so ) const;
+
+
+        /** Set to an orthographic projection.
+         * See glOrtho for further details.
+        */
+        void makeOrtho(double left,   double right,
+                       double bottom, double top,
+                       double zNear,  double zFar);
+
+        /** Get the orthographic settings of the orthographic projection matrix.
+          * Note, if matrix is not an orthographic matrix then invalid values 
+          * will be returned.
+        */
+        bool getOrtho(double& left,   double& right,
+                      double& bottom, double& top,
+                      double& zNear,  double& zFar) const;
+
+        /** Set to a 2D orthographic projection.
+          * See glOrtho2D for further details.
+        */
+        inline void makeOrtho2D(double left,   double right,
+                                double bottom, double top)
+        {
+            makeOrtho(left,right,bottom,top,-1.0,1.0);
+        }
+
+
+        /** Set to a perspective projection.
+          * See glFrustum for further details.
+        */
+        void makeFrustum(double left,   double right,
+                         double bottom, double top,
+                         double zNear,  double zFar);
+
+        /** Get the frustum settings of a perspective projection matrix.
+          * Note, if matrix is not a perspective matrix then invalid values
+          * will be returned.
+        */
+        bool getFrustum(double& left,   double& right,
+                        double& bottom, double& top,
+                        double& zNear,  double& zFar) const;
+
+        /** Set to a symmetrical perspective projection.
+          * See gluPerspective for further details.
+          * Aspect ratio is defined as width/height.
+        */
+        void makePerspective(double fovy,  double aspectRatio,
+                             double zNear, double zFar);
+
+        /** Get the frustum settings of a symmetric perspective projection
+          * matrix.
+          * Return false if matrix is not a perspective matrix,
+          * where parameter values are undefined. 
+          * Note, if matrix is not a symmetric perspective matrix then the
+          * shear will be lost.
+          * Asymmetric matrices occur when stereo, power walls, caves and
+          * reality center display are used.
+          * In these configuration one should use the AsFrustum method instead.
+        */
+        bool getPerspective(double& fovy,  double& aspectRatio,
+                            double& zNear, double& zFar) const;
+
+        /** Set the position and orientation to be a view matrix,
+          * using the same convention as gluLookAt.
+        */
+        void makeLookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up);
+
+        /** Get to the position and orientation of a modelview matrix,
+          * using the same convention as gluLookAt.
+        */
+        void getLookAt(Vec3f& eye,Vec3f& center,Vec3f& up,
+                       value_type lookDistance=1.0f) const;
+
+        /** Get to the position and orientation of a modelview matrix,
+          * using the same convention as gluLookAt.
+        */
+        void getLookAt(Vec3d& eye,Vec3d& center,Vec3d& up,
+                       value_type lookDistance=1.0f) const;
+
+        /** invert the matrix rhs, automatically select invert_4x3 or invert_4x4. */
+        inline bool invert( const Matrixd& rhs)
+        {
+            bool is_4x3 = (rhs._mat[0][3]==0.0 && rhs._mat[1][3]==0.0 &&  rhs._mat[2][3]==0.0 && rhs._mat[3][3]==1.0);
+            return is_4x3 ? invert_4x3(rhs) :  invert_4x4(rhs);
+        }
+
+        /** 4x3 matrix invert, not right hand column is assumed to be 0,0,0,1. */
+        bool invert_4x3( const Matrixd& rhs);
+
+        /** full 4x4 matrix invert. */
+        bool invert_4x4( const Matrixd& rhs);
+
+        /** ortho-normalize the 3x3 rotation & scale matrix */ 
+        void orthoNormalize(const Matrixd& rhs); 
+
+        // basic utility functions to create new matrices
+        inline static Matrixd identity( void );
+        inline static Matrixd scale( const Vec3f& sv);
+        inline static Matrixd scale( const Vec3d& sv);
+        inline static Matrixd scale( value_type sx, value_type sy, value_type sz);
+        inline static Matrixd translate( const Vec3f& dv);
+        inline static Matrixd translate( const Vec3d& dv);
+        inline static Matrixd translate( value_type x, value_type y, value_type z);
+        inline static Matrixd rotate( const Vec3f& from, const Vec3f& to);
+        inline static Matrixd rotate( const Vec3d& from, const Vec3d& to);
+        inline static Matrixd rotate( value_type angle, value_type x, value_type y, value_type z);
+        inline static Matrixd rotate( value_type angle, const Vec3f& axis);
+        inline static Matrixd rotate( value_type angle, const Vec3d& axis);
+        inline static Matrixd rotate( value_type angle1, const Vec3f& axis1, 
+                                      value_type angle2, const Vec3f& axis2,
+                                      value_type angle3, const Vec3f& axis3);
+        inline static Matrixd rotate( value_type angle1, const Vec3d& axis1, 
+                                      value_type angle2, const Vec3d& axis2,
+                                      value_type angle3, const Vec3d& axis3);
+        inline static Matrixd rotate( const Quat& quat);
+        inline static Matrixd inverse( const Matrixd& matrix);
+        inline static Matrixd orthoNormal(const Matrixd& matrix); 
+        /** Create an orthographic projection matrix.
+          * See glOrtho for further details.
+        */
+        inline static Matrixd ortho(double left,   double right,
+                                    double bottom, double top,
+                                    double zNear,  double zFar);
+
+        /** Create a 2D orthographic projection.
+          * See glOrtho for further details.
+        */
+        inline static Matrixd ortho2D(double left,   double right,
+                                      double bottom, double top);
+
+        /** Create a perspective projection.
+          * See glFrustum for further details.
+        */
+        inline static Matrixd frustum(double left,   double right,
+                                      double bottom, double top,
+                                      double zNear,  double zFar);
+
+        /** Create a symmetrical perspective projection.
+          * See gluPerspective for further details.
+          * Aspect ratio is defined as width/height.
+        */
+        inline static Matrixd perspective(double fovy,  double aspectRatio,
+                                          double zNear, double zFar);
+
+        /** Create the position and orientation as per a camera,
+          * using the same convention as gluLookAt.
+        */
+        inline static Matrixd lookAt(const Vec3f& eye,
+                                     const Vec3f& center,
+                                     const Vec3f& up);
+
+        /** Create the position and orientation as per a camera,
+          * using the same convention as gluLookAt.
+        */
+        inline static Matrixd lookAt(const Vec3d& eye,
+                                     const Vec3d& center,
+                                     const Vec3d& up);
+
+        inline Vec3f preMult( const Vec3f& v ) const;
+        inline Vec3d preMult( const Vec3d& v ) const;
+        inline Vec3f postMult( const Vec3f& v ) const;
+        inline Vec3d postMult( const Vec3d& v ) const;
+        inline Vec3f operator* ( const Vec3f& v ) const;
+        inline Vec3d operator* ( const Vec3d& v ) const;
+        inline Vec4f preMult( const Vec4f& v ) const;
+        inline Vec4d preMult( const Vec4d& v ) const;
+        inline Vec4f postMult( const Vec4f& v ) const;
+        inline Vec4d postMult( const Vec4d& v ) const;
+        inline Vec4f operator* ( const Vec4f& v ) const;
+        inline Vec4d operator* ( const Vec4d& v ) const;
+
+#ifdef USE_DEPRECATED_API
+        inline void set(const Quat& q) { makeRotate(q); }
+        inline void get(Quat& q) const { q = getRotate(); }
+#endif
+
+        void setRotate(const Quat& q);
+        /** Get the matrix rotation as a Quat. Note that this function
+          * assumes a non-scaled matrix and will return incorrect results
+          * for scaled matrixces. Consider decompose() instead.
+          */
+        Quat getRotate() const;
+
+        void setTrans( value_type tx, value_type ty, value_type tz );
+        void setTrans( const Vec3f& v );
+        void setTrans( const Vec3d& v );
+        
+        inline Vec3d getTrans() const { return Vec3d(_mat[3][0],_mat[3][1],_mat[3][2]); } 
+        
+        inline Vec3d getScale() const {
+          Vec3d x_vec(_mat[0][0],_mat[1][0],_mat[2][0]); 
+          Vec3d y_vec(_mat[0][1],_mat[1][1],_mat[2][1]); 
+          Vec3d z_vec(_mat[0][2],_mat[1][2],_mat[2][2]); 
+          return Vec3d(x_vec.length(), y_vec.length(), z_vec.length()); 
+        }
+        
+        /** apply a 3x3 transform of v*M[0..2,0..2]. */
+        inline static Vec3f transform3x3(const Vec3f& v,const Matrixd& m);
+
+        /** apply a 3x3 transform of v*M[0..2,0..2]. */
+        inline static Vec3d transform3x3(const Vec3d& v,const Matrixd& m);
+
+        /** apply a 3x3 transform of M[0..2,0..2]*v. */
+        inline static Vec3f transform3x3(const Matrixd& m,const Vec3f& v);
+
+        /** apply a 3x3 transform of M[0..2,0..2]*v. */
+        inline static Vec3d transform3x3(const Matrixd& m,const Vec3d& v);
+
+        // basic Matrixd multiplication, our workhorse methods.
+        void mult( const Matrixd&, const Matrixd& );
+        void preMult( const Matrixd& );
+        void postMult( const Matrixd& );
+
+        /** Optimized version of preMult(translate(v)); */
+        inline void preMultTranslate( const Vec3d& v );
+        inline void preMultTranslate( const Vec3f& v );
+        /** Optimized version of postMult(translate(v)); */
+        inline void postMultTranslate( const Vec3d& v );
+        inline void postMultTranslate( const Vec3f& v );
+
+        /** Optimized version of preMult(scale(v)); */
+        inline void preMultScale( const Vec3d& v );
+        inline void preMultScale( const Vec3f& v );
+        /** Optimized version of postMult(scale(v)); */
+        inline void postMultScale( const Vec3d& v );
+        inline void postMultScale( const Vec3f& v );
+
+        /** Optimized version of preMult(rotate(q)); */
+        inline void preMultRotate( const Quat& q );
+        /** Optimized version of postMult(rotate(q)); */
+        inline void postMultRotate( const Quat& q );
+
+        inline void operator *= ( const Matrixd& other ) 
+        {    if( this == &other ) {
+                Matrixd temp(other);
+                postMult( temp );
+            }
+            else postMult( other ); 
+        }
+
+        inline Matrixd operator * ( const Matrixd &m ) const
+        {
+            osg::Matrixd r;
+            r.mult(*this,m);
+            return  r;
+        }
+
+    protected:
+        value_type _mat[4][4];
+
+};
+
+class RefMatrixd : public Object, public Matrixd
+{
+    public:
+    
+        RefMatrixd():Object(false), Matrixd() {}
+        RefMatrixd( const Matrixd& other) : Object(false), Matrixd(other) {}
+        RefMatrixd( const Matrixf& other) : Object(false), Matrixd(other) {}
+        RefMatrixd( const RefMatrixd& other) : Object(other), Matrixd(other) {}
+        explicit RefMatrixd( Matrixd::value_type const * const def ):Object(false), Matrixd(def) {}
+        RefMatrixd( Matrixd::value_type a00, Matrixd::value_type a01, Matrixd::value_type a02, Matrixd::value_type a03,
+            Matrixd::value_type a10, Matrixd::value_type a11, Matrixd::value_type a12, Matrixd::value_type a13,
+            Matrixd::value_type a20, Matrixd::value_type a21, Matrixd::value_type a22, Matrixd::value_type a23,
+            Matrixd::value_type a30, Matrixd::value_type a31, Matrixd::value_type a32, Matrixd::value_type a33):
+            Object(false), 
+            Matrixd(a00, a01, a02, a03,
+                    a10, a11, a12, a13,
+                    a20, a21, a22, a23,
+                    a30, a31, a32, a33) {}
+
+        virtual Object* cloneType() const { return new RefMatrixd(); } 
+        virtual Object* clone(const CopyOp&) const { return new RefMatrixd(*this); }
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const RefMatrixd*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Matrix"; }
+        
+        
+    protected:
+    
+        virtual ~RefMatrixd() {}
+};
+
+
+// static utility methods
+inline Matrixd Matrixd::identity(void)
+{
+    Matrixd m;
+    m.makeIdentity();
+    return m;
+}
+
+inline Matrixd Matrixd::scale(value_type sx, value_type sy, value_type sz)
+{
+    Matrixd m;
+    m.makeScale(sx,sy,sz);
+    return m;
+}
+
+inline Matrixd Matrixd::scale(const Vec3f& v )
+{
+    return scale(v.x(), v.y(), v.z() );
+}
+
+inline Matrixd Matrixd::scale(const Vec3d& v )
+{
+    return scale(v.x(), v.y(), v.z() );
+}
+
+inline Matrixd Matrixd::translate(value_type tx, value_type ty, value_type tz)
+{
+    Matrixd m;
+    m.makeTranslate(tx,ty,tz);
+    return m;
+}
+
+inline Matrixd Matrixd::translate(const Vec3f& v )
+{
+    return translate(v.x(), v.y(), v.z() );
+}
+
+inline Matrixd Matrixd::translate(const Vec3d& v )
+{
+    return translate(v.x(), v.y(), v.z() );
+}
+
+inline Matrixd Matrixd::rotate( const Quat& q )
+{
+    return Matrixd(q);
+}
+inline Matrixd Matrixd::rotate(value_type angle, value_type x, value_type y, value_type z )
+{
+    Matrixd m;
+    m.makeRotate(angle,x,y,z);
+    return m;
+}
+inline Matrixd Matrixd::rotate(value_type angle, const Vec3f& axis )
+{
+    Matrixd m;
+    m.makeRotate(angle,axis);
+    return m;
+}
+inline Matrixd Matrixd::rotate(value_type angle, const Vec3d& axis )
+{
+    Matrixd m;
+    m.makeRotate(angle,axis);
+    return m;
+}
+inline Matrixd Matrixd::rotate( value_type angle1, const Vec3f& axis1, 
+                                value_type angle2, const Vec3f& axis2,
+                                value_type angle3, const Vec3f& axis3)
+{
+    Matrixd m;
+    m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+    return m;
+}
+inline Matrixd Matrixd::rotate( value_type angle1, const Vec3d& axis1, 
+                                value_type angle2, const Vec3d& axis2,
+                                value_type angle3, const Vec3d& axis3)
+{
+    Matrixd m;
+    m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+    return m;
+}
+inline Matrixd Matrixd::rotate(const Vec3f& from, const Vec3f& to )
+{
+    Matrixd m;
+    m.makeRotate(from,to);
+    return m;
+}
+inline Matrixd Matrixd::rotate(const Vec3d& from, const Vec3d& to )
+{
+    Matrixd m;
+    m.makeRotate(from,to);
+    return m;
+}
+
+inline Matrixd Matrixd::inverse( const Matrixd& matrix)
+{
+    Matrixd m;
+    m.invert(matrix);
+    return m;
+}
+
+inline Matrixd Matrixd::orthoNormal(const Matrixd& matrix)
+{
+  Matrixd m;
+  m.orthoNormalize(matrix);
+  return m; 
+}
+
+inline Matrixd Matrixd::ortho(double left,   double right,
+                              double bottom, double top,
+                              double zNear,  double zFar)
+{
+    Matrixd m;
+    m.makeOrtho(left,right,bottom,top,zNear,zFar);
+    return m;
+}
+
+inline Matrixd Matrixd::ortho2D(double left,   double right,
+                                double bottom, double top)
+{
+    Matrixd m;
+    m.makeOrtho2D(left,right,bottom,top);
+    return m;
+}
+
+inline Matrixd Matrixd::frustum(double left,   double right,
+                                double bottom, double top,
+                                double zNear,  double zFar)
+{
+    Matrixd m;
+    m.makeFrustum(left,right,bottom,top,zNear,zFar);
+    return m;
+}
+
+inline Matrixd Matrixd::perspective(double fovy,  double aspectRatio,
+                                    double zNear, double zFar)
+{
+    Matrixd m;
+    m.makePerspective(fovy,aspectRatio,zNear,zFar);
+    return m;
+}
+
+inline Matrixd Matrixd::lookAt(const Vec3f& eye,
+                               const Vec3f& center,
+                               const Vec3f& up)
+{
+    Matrixd m;
+    m.makeLookAt(eye,center,up);
+    return m;
+}
+
+inline Matrixd Matrixd::lookAt(const Vec3d& eye,
+                               const Vec3d& center,
+                               const Vec3d& up)
+{
+    Matrixd m;
+    m.makeLookAt(eye,center,up);
+    return m;
+}
+
+inline Vec3f Matrixd::postMult( const Vec3f& v ) const
+{
+    value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ;
+    return Vec3f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d,
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d,
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ;
+}
+
+inline Vec3d Matrixd::postMult( const Vec3d& v ) const
+{
+    value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ;
+    return Vec3d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d,
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d,
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ;
+}
+
+inline Vec3f Matrixd::preMult( const Vec3f& v ) const
+{
+    value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ;
+    return Vec3f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d,
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d,
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d);
+}
+
+inline Vec3d Matrixd::preMult( const Vec3d& v ) const
+{
+    value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ;
+    return Vec3d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d,
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d,
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d);
+}
+
+inline Vec4f Matrixd::postMult( const Vec4f& v ) const
+{
+    return Vec4f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()),
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()),
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()),
+        (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ;
+}
+inline Vec4d Matrixd::postMult( const Vec4d& v ) const
+{
+    return Vec4d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()),
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()),
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()),
+        (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ;
+}
+
+inline Vec4f Matrixd::preMult( const Vec4f& v ) const
+{
+    return Vec4f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()),
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()),
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()),
+        (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w()));
+}
+
+inline Vec4d Matrixd::preMult( const Vec4d& v ) const
+{
+    return Vec4d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()),
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()),
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()),
+        (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w()));
+}
+
+inline Vec3f Matrixd::transform3x3(const Vec3f& v,const Matrixd& m)
+{
+    return Vec3f( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()),
+                 (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()),
+                 (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z()));
+}
+inline Vec3d Matrixd::transform3x3(const Vec3d& v,const Matrixd& m)
+{
+    return Vec3d( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()),
+                 (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()),
+                 (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z()));
+}
+
+inline Vec3f Matrixd::transform3x3(const Matrixd& m,const Vec3f& v)
+{
+    return Vec3f( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()),
+                 (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()),
+                 (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ;
+}
+inline Vec3d Matrixd::transform3x3(const Matrixd& m,const Vec3d& v)
+{
+    return Vec3d( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()),
+                 (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()),
+                 (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ;
+}
+
+inline void Matrixd::preMultTranslate( const Vec3d& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        double tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[3][0] += tmp*_mat[i][0];
+        _mat[3][1] += tmp*_mat[i][1];
+        _mat[3][2] += tmp*_mat[i][2];
+        _mat[3][3] += tmp*_mat[i][3];
+    }
+}
+
+inline void Matrixd::preMultTranslate( const Vec3f& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        float tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[3][0] += tmp*_mat[i][0];
+        _mat[3][1] += tmp*_mat[i][1];
+        _mat[3][2] += tmp*_mat[i][2];
+        _mat[3][3] += tmp*_mat[i][3];
+    }
+}
+
+inline void Matrixd::postMultTranslate( const Vec3d& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        double tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[0][i] += tmp*_mat[0][3];
+        _mat[1][i] += tmp*_mat[1][3];
+        _mat[2][i] += tmp*_mat[2][3];
+        _mat[3][i] += tmp*_mat[3][3];
+    }
+}
+
+inline void Matrixd::postMultTranslate( const Vec3f& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        float tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[0][i] += tmp*_mat[0][3];
+        _mat[1][i] += tmp*_mat[1][3];
+        _mat[2][i] += tmp*_mat[2][3];
+        _mat[3][i] += tmp*_mat[3][3];
+    }
+}
+
+inline void Matrixd::preMultScale( const Vec3d& v )
+{
+    _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0];
+    _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1];
+    _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2];
+}
+
+inline void Matrixd::preMultScale( const Vec3f& v )
+{
+    _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0];
+    _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1];
+    _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2];
+}
+
+inline void Matrixd::postMultScale( const Vec3d& v )
+{
+    _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0];
+    _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1];
+    _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2];
+}
+
+inline void Matrixd::postMultScale( const Vec3f& v )
+{
+    _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0];
+    _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1];
+    _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2];
+}
+
+inline void Matrixd::preMultRotate( const Quat& q )
+{
+    if (q.zeroRotation())
+        return;
+    Matrixd r;
+    r.setRotate(q);
+    preMult(r);
+}
+
+inline void Matrixd::postMultRotate( const Quat& q )
+{
+    if (q.zeroRotation())
+        return;
+    Matrixd r;
+    r.setRotate(q);
+    postMult(r);
+}
+
+inline Vec3f operator* (const Vec3f& v, const Matrixd& m )
+{
+    return m.preMult(v);
+}
+
+inline Vec3d operator* (const Vec3d& v, const Matrixd& m )
+{
+    return m.preMult(v);
+}
+
+inline Vec4f operator* (const Vec4f& v, const Matrixd& m )
+{
+    return m.preMult(v);
+}
+
+inline Vec4d operator* (const Vec4d& v, const Matrixd& m )
+{
+    return m.preMult(v);
+}
+
+inline Vec3f Matrixd::operator* (const Vec3f& v) const
+{
+    return postMult(v);
+}
+
+inline Vec3d Matrixd::operator* (const Vec3d& v) const
+{
+    return postMult(v);
+}
+
+inline Vec4f Matrixd::operator* (const Vec4f& v) const
+{
+    return postMult(v);
+}
+
+inline Vec4d Matrixd::operator* (const Vec4d& v) const
+{
+    return postMult(v);
+}
+
+
+} //namespace osg
+
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixf
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixf (revision 8868)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Matrixf (revision 8868)
@@ -0,0 +1,804 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_MATRIXF
+#define OSG_MATRIXF 1
+
+#include <osg/Object>
+#include <osg/Vec3d>
+#include <osg/Vec4d>
+#include <osg/Quat>
+
+namespace osg {
+
+class Matrixf;
+
+class OSG_EXPORT Matrixf
+{
+    public:
+    
+        typedef float value_type;
+
+        inline Matrixf() { makeIdentity(); }
+        inline Matrixf( const Matrixf& mat) { set(mat.ptr()); }
+        Matrixf( const Matrixd& mat );
+        inline explicit Matrixf( float const * const ptr ) { set(ptr); }
+        inline explicit Matrixf( double const * const ptr ) { set(ptr); }
+        inline explicit Matrixf( const Quat& quat ) { makeRotate(quat); }
+
+        Matrixf( value_type a00, value_type a01, value_type a02, value_type a03,
+                 value_type a10, value_type a11, value_type a12, value_type a13,
+                 value_type a20, value_type a21, value_type a22, value_type a23,
+                 value_type a30, value_type a31, value_type a32, value_type a33);
+
+        ~Matrixf() {}
+
+        int compare(const Matrixf& m) const;
+
+        bool operator < (const Matrixf& m) const { return compare(m)<0; }
+        bool operator == (const Matrixf& m) const { return compare(m)==0; }
+        bool operator != (const Matrixf& m) const { return compare(m)!=0; }
+
+        inline value_type& operator()(int row, int col) { return _mat[row][col]; }
+        inline value_type operator()(int row, int col) const { return _mat[row][col]; }
+
+        inline bool valid() const { return !isNaN(); }
+        inline bool isNaN() const { return osg::isNaN(_mat[0][0]) || osg::isNaN(_mat[0][1]) || osg::isNaN(_mat[0][2]) || osg::isNaN(_mat[0][3]) ||
+                                                 osg::isNaN(_mat[1][0]) || osg::isNaN(_mat[1][1]) || osg::isNaN(_mat[1][2]) || osg::isNaN(_mat[1][3]) ||
+                                                 osg::isNaN(_mat[2][0]) || osg::isNaN(_mat[2][1]) || osg::isNaN(_mat[2][2]) || osg::isNaN(_mat[2][3]) ||
+                                                 osg::isNaN(_mat[3][0]) || osg::isNaN(_mat[3][1]) || osg::isNaN(_mat[3][2]) || osg::isNaN(_mat[3][3]); }
+
+        inline Matrixf& operator = (const Matrixf& rhs)
+        {
+            if( &rhs == this ) return *this;
+            set(rhs.ptr());
+            return *this;
+        }
+        
+        Matrixf& operator = (const Matrixd& other);
+
+        inline void set(const Matrixf& rhs) { set(rhs.ptr()); }
+
+        void set(const Matrixd& rhs);
+
+        inline void set(float const * const ptr)
+        {
+            value_type* local_ptr = (value_type*)_mat;
+            for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i];
+        }
+        
+        inline void set(double const * const ptr)
+        {
+            value_type* local_ptr = (value_type*)_mat;
+            for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i];
+        }
+
+        void set(value_type a00, value_type a01, value_type a02,value_type a03,
+                 value_type a10, value_type a11, value_type a12,value_type a13,
+                 value_type a20, value_type a21, value_type a22,value_type a23,
+                 value_type a30, value_type a31, value_type a32,value_type a33);
+                  
+        value_type * ptr() { return (value_type*)_mat; }
+        const value_type * ptr() const { return (const value_type *)_mat; }
+
+        bool isIdentity() const
+        {
+            return _mat[0][0]==1.0f && _mat[0][1]==0.0f && _mat[0][2]==0.0f &&  _mat[0][3]==0.0f &&
+                   _mat[1][0]==0.0f && _mat[1][1]==1.0f && _mat[1][2]==0.0f &&  _mat[1][3]==0.0f &&
+                   _mat[2][0]==0.0f && _mat[2][1]==0.0f && _mat[2][2]==1.0f &&  _mat[2][3]==0.0f &&
+                   _mat[3][0]==0.0f && _mat[3][1]==0.0f && _mat[3][2]==0.0f &&  _mat[3][3]==1.0f;
+        }
+
+        void makeIdentity();
+        
+        void makeScale( const Vec3f& );
+        void makeScale( const Vec3d& );
+        void makeScale( value_type, value_type, value_type );
+        
+        void makeTranslate( const Vec3f& );
+        void makeTranslate( const Vec3d& );
+        void makeTranslate( value_type, value_type, value_type );
+        
+        void makeRotate( const Vec3f& from, const Vec3f& to );
+        void makeRotate( const Vec3d& from, const Vec3d& to );
+        void makeRotate( value_type angle, const Vec3f& axis );
+        void makeRotate( value_type angle, const Vec3d& axis );
+        void makeRotate( value_type angle, value_type x, value_type y, value_type z );
+        void makeRotate( const Quat& );
+        void makeRotate( value_type angle1, const Vec3f& axis1, 
+                         value_type angle2, const Vec3f& axis2,
+                         value_type angle3, const Vec3f& axis3);
+        void makeRotate( value_type angle1, const Vec3d& axis1, 
+                         value_type angle2, const Vec3d& axis2,
+                         value_type angle3, const Vec3d& axis3);
+
+        
+        /** decompose the matrix into translation, rotation, scale and scale orientation.*/        
+        void decompose( osg::Vec3f& translation,
+                        osg::Quat& rotation, 
+                        osg::Vec3f& scale, 
+                        osg::Quat& so ) const;
+
+        /** decompose the matrix into translation, rotation, scale and scale orientation.*/        
+        void decompose( osg::Vec3d& translation,
+                        osg::Quat& rotation, 
+                        osg::Vec3d& scale, 
+                        osg::Quat& so ) const;
+
+
+        /** Set to an orthographic projection.
+         * See glOrtho for further details.
+        */
+        void makeOrtho(double left,   double right,
+                       double bottom, double top,
+                       double zNear,  double zFar);
+
+        /** Get the orthographic settings of the orthographic projection matrix.
+          * Note, if matrix is not an orthographic matrix then invalid values 
+          * will be returned.
+        */
+        bool getOrtho(double& left,   double& right,
+                      double& bottom, double& top,
+                      double& zNear,  double& zFar) const;
+
+        /** Set to a 2D orthographic projection.
+          * See glOrtho2D for further details.
+        */
+        inline void makeOrtho2D(double left,   double right,
+                                double bottom, double top)
+        {
+            makeOrtho(left,right,bottom,top,-1.0,1.0);
+        }
+
+
+        /** Set to a perspective projection.
+          * See glFrustum for further details.
+        */
+        void makeFrustum(double left,   double right,
+                         double bottom, double top,
+                         double zNear,  double zFar);
+
+        /** Get the frustum settings of a perspective projection matrix.
+          * Note, if matrix is not a perspective matrix then invalid values
+          * will be returned.
+        */
+        bool getFrustum(double& left,   double& right,
+                        double& bottom, double& top,
+                        double& zNear,  double& zFar) const;
+
+        /** Set to a symmetrical perspective projection.
+          * See gluPerspective for further details.
+          * Aspect ratio is defined as width/height.
+        */
+        void makePerspective(double fovy,  double aspectRatio,
+                             double zNear, double zFar);
+
+        /** Get the frustum settings of a symmetric perspective projection
+          * matrix.
+          * Return false if matrix is not a perspective matrix,
+          * where parameter values are undefined. 
+          * Note, if matrix is not a symmetric perspective matrix then the
+          * shear will be lost.
+          * Asymmetric matrices occur when stereo, power walls, caves and
+          * reality center display are used.
+          * In these configuration one should use the AsFrustum method instead.
+        */
+        bool getPerspective(double& fovy,  double& aspectRatio,
+                            double& zNear, double& zFar) const;
+
+        /** Set the position and orientation to be a view matrix,
+          * using the same convention as gluLookAt.
+        */
+        void makeLookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up);
+
+        /** Get to the position and orientation of a modelview matrix,
+          * using the same convention as gluLookAt.
+        */
+        void getLookAt(Vec3f& eye,Vec3f& center,Vec3f& up,
+                       value_type lookDistance=1.0f) const;
+
+        /** Get to the position and orientation of a modelview matrix,
+          * using the same convention as gluLookAt.
+        */
+        void getLookAt(Vec3d& eye,Vec3d& center,Vec3d& up,
+                       value_type lookDistance=1.0f) const;
+
+        /** invert the matrix rhs, automatically select invert_4x3 or invert_4x4. */
+        inline bool invert( const Matrixf& rhs)
+        {
+            bool is_4x3 = (rhs._mat[0][3]==0.0f && rhs._mat[1][3]==0.0f &&  rhs._mat[2][3]==0.0f && rhs._mat[3][3]==1.0f);
+            return is_4x3 ? invert_4x3(rhs) :  invert_4x4(rhs);
+        }
+
+        /** 4x3 matrix invert, not right hand column is assumed to be 0,0,0,1. */
+        bool invert_4x3( const Matrixf& rhs);
+
+        /** full 4x4 matrix invert. */
+        bool invert_4x4( const Matrixf& rhs);
+
+        /** ortho-normalize the 3x3 rotation & scale matrix */ 
+        void orthoNormalize(const Matrixf& rhs); 
+
+        //basic utility functions to create new matrices
+        inline static Matrixf identity( void );
+        inline static Matrixf scale( const Vec3f& sv);
+        inline static Matrixf scale( const Vec3d& sv);
+        inline static Matrixf scale( value_type sx, value_type sy, value_type sz);
+        inline static Matrixf translate( const Vec3f& dv);
+        inline static Matrixf translate( const Vec3d& dv);
+        inline static Matrixf translate( value_type x, value_type y, value_type z);
+        inline static Matrixf rotate( const Vec3f& from, const Vec3f& to);
+        inline static Matrixf rotate( const Vec3d& from, const Vec3d& to);
+        inline static Matrixf rotate( value_type angle, value_type x, value_type y, value_type z);
+        inline static Matrixf rotate( value_type angle, const Vec3f& axis);
+        inline static Matrixf rotate( value_type angle, const Vec3d& axis);
+        inline static Matrixf rotate( value_type angle1, const Vec3f& axis1, 
+                                      value_type angle2, const Vec3f& axis2,
+                                      value_type angle3, const Vec3f& axis3);
+        inline static Matrixf rotate( value_type angle1, const Vec3d& axis1, 
+                                      value_type angle2, const Vec3d& axis2,
+                                      value_type angle3, const Vec3d& axis3);
+        inline static Matrixf rotate( const Quat& quat);
+        inline static Matrixf inverse( const Matrixf& matrix);
+        inline static Matrixf orthoNormal(const Matrixf& matrix); 
+        
+        /** Create an orthographic projection matrix.
+          * See glOrtho for further details.
+        */
+        inline static Matrixf ortho(double left,   double right,
+                                    double bottom, double top,
+                                    double zNear,  double zFar);
+
+        /** Create a 2D orthographic projection.
+          * See glOrtho for further details.
+        */
+        inline static Matrixf ortho2D(double left,   double right,
+                                      double bottom, double top);
+
+        /** Create a perspective projection.
+          * See glFrustum for further details.
+        */
+        inline static Matrixf frustum(double left,   double right,
+                                      double bottom, double top,
+                                      double zNear,  double zFar);
+
+        /** Create a symmetrical perspective projection.
+          * See gluPerspective for further details.
+          * Aspect ratio is defined as width/height.
+        */
+        inline static Matrixf perspective(double fovy,  double aspectRatio,
+                                          double zNear, double zFar);
+
+        /** Create the position and orientation as per a camera,
+          * using the same convention as gluLookAt.
+        */
+        inline static Matrixf lookAt(const Vec3f& eye,
+                                     const Vec3f& center,
+                                     const Vec3f& up);
+
+        /** Create the position and orientation as per a camera,
+          * using the same convention as gluLookAt.
+        */
+        inline static Matrixf lookAt(const Vec3d& eye,
+                                     const Vec3d& center,
+                                     const Vec3d& up);
+
+        inline Vec3f preMult( const Vec3f& v ) const;
+        inline Vec3d preMult( const Vec3d& v ) const;
+        inline Vec3f postMult( const Vec3f& v ) const;
+        inline Vec3d postMult( const Vec3d& v ) const;
+        inline Vec3f operator* ( const Vec3f& v ) const;
+        inline Vec3d operator* ( const Vec3d& v ) const;
+        inline Vec4f preMult( const Vec4f& v ) const;
+        inline Vec4d preMult( const Vec4d& v ) const;
+        inline Vec4f postMult( const Vec4f& v ) const;
+        inline Vec4d postMult( const Vec4d& v ) const;
+        inline Vec4f operator* ( const Vec4f& v ) const;
+        inline Vec4d operator* ( const Vec4d& v ) const;
+
+#ifdef USE_DEPRECATED_API
+        inline void set(const Quat& q) { makeRotate(q); }
+        inline void get(Quat& q) const { q = getRotate(); }
+#endif
+
+        void setRotate(const Quat& q);
+        /** Get the matrix rotation as a Quat. Note that this function
+          * assumes a non-scaled matrix and will return incorrect results
+          * for scaled matrixces. Consider decompose() instead.
+          */
+        Quat getRotate() const;
+
+
+        void setTrans( value_type tx, value_type ty, value_type tz );
+        void setTrans( const Vec3f& v );
+        void setTrans( const Vec3d& v );
+        
+        inline Vec3d getTrans() const { return Vec3d(_mat[3][0],_mat[3][1],_mat[3][2]); } 
+        
+        inline Vec3d getScale() const {
+          Vec3d x_vec(_mat[0][0],_mat[1][0],_mat[2][0]); 
+          Vec3d y_vec(_mat[0][1],_mat[1][1],_mat[2][1]); 
+          Vec3d z_vec(_mat[0][2],_mat[1][2],_mat[2][2]); 
+          return Vec3d(x_vec.length(), y_vec.length(), z_vec.length()); 
+        }
+        
+        /** apply a 3x3 transform of v*M[0..2,0..2]. */
+        inline static Vec3f transform3x3(const Vec3f& v,const Matrixf& m);
+
+        /** apply a 3x3 transform of v*M[0..2,0..2]. */
+        inline static Vec3d transform3x3(const Vec3d& v,const Matrixf& m);
+
+        /** apply a 3x3 transform of M[0..2,0..2]*v. */
+        inline static Vec3f transform3x3(const Matrixf& m,const Vec3f& v);
+
+        /** apply a 3x3 transform of M[0..2,0..2]*v. */
+        inline static Vec3d transform3x3(const Matrixf& m,const Vec3d& v);
+
+        // basic Matrixf multiplication, our workhorse methods.
+        void mult( const Matrixf&, const Matrixf& );
+        void preMult( const Matrixf& );
+        void postMult( const Matrixf& );
+
+        /** Optimized version of preMult(translate(v)); */
+        inline void preMultTranslate( const Vec3d& v );
+        inline void preMultTranslate( const Vec3f& v );
+        /** Optimized version of postMult(translate(v)); */
+        inline void postMultTranslate( const Vec3d& v );
+        inline void postMultTranslate( const Vec3f& v );
+
+        /** Optimized version of preMult(scale(v)); */
+        inline void preMultScale( const Vec3d& v );
+        inline void preMultScale( const Vec3f& v );
+        /** Optimized version of postMult(scale(v)); */
+        inline void postMultScale( const Vec3d& v );
+        inline void postMultScale( const Vec3f& v );
+
+        /** Optimized version of preMult(rotate(q)); */
+        inline void preMultRotate( const Quat& q );
+        /** Optimized version of postMult(rotate(q)); */
+        inline void postMultRotate( const Quat& q );
+
+        inline void operator *= ( const Matrixf& other ) 
+        {    if( this == &other ) {
+                Matrixf temp(other);
+                postMult( temp );
+            }
+            else postMult( other ); 
+        }
+
+        inline Matrixf operator * ( const Matrixf &m ) const
+        {
+            osg::Matrixf r;
+            r.mult(*this,m);
+            return  r;
+        }
+
+    protected:
+        value_type _mat[4][4];
+
+};
+
+class RefMatrixf : public Object, public Matrixf
+{
+    public:
+    
+        RefMatrixf():Object(false), Matrixf() {}
+        RefMatrixf( const Matrixf& other) : Object(false), Matrixf(other) {}
+        RefMatrixf( const Matrixd& other) : Object(false), Matrixf(other) {}
+        RefMatrixf( const RefMatrixf& other) : Object(other), Matrixf(other) {}
+        explicit RefMatrixf( Matrixf::value_type const * const def ):Object(false), Matrixf(def) {}
+        RefMatrixf( Matrixf::value_type a00, Matrixf::value_type a01, Matrixf::value_type a02, Matrixf::value_type a03,
+            Matrixf::value_type a10, Matrixf::value_type a11, Matrixf::value_type a12, Matrixf::value_type a13,
+            Matrixf::value_type a20, Matrixf::value_type a21, Matrixf::value_type a22, Matrixf::value_type a23,
+            Matrixf::value_type a30, Matrixf::value_type a31, Matrixf::value_type a32, Matrixf::value_type a33):
+            Object(false), 
+            Matrixf(a00, a01, a02, a03,
+                   a10, a11, a12, a13,
+                   a20, a21, a22, a23,
+                   a30, a31, a32, a33) {}
+
+        virtual Object* cloneType() const { return new RefMatrixf(); } 
+        virtual Object* clone(const CopyOp&) const { return new RefMatrixf(*this); }
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const RefMatrixf*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Matrix"; }
+        
+        
+    protected:
+    
+        virtual ~RefMatrixf() {}
+};
+
+
+//static utility methods
+inline Matrixf Matrixf::identity(void)
+{
+    Matrixf m;
+    m.makeIdentity();
+    return m;
+}
+
+inline Matrixf Matrixf::scale(value_type sx, value_type sy, value_type sz)
+{
+    Matrixf m;
+    m.makeScale(sx,sy,sz);
+    return m;
+}
+
+inline Matrixf Matrixf::scale(const Vec3f& v )
+{
+    return scale(v.x(), v.y(), v.z() );
+}
+
+inline Matrixf Matrixf::scale(const Vec3d& v )
+{
+    return scale(v.x(), v.y(), v.z() );
+}
+
+inline Matrixf Matrixf::translate(value_type tx, value_type ty, value_type tz)
+{
+    Matrixf m;
+    m.makeTranslate(tx,ty,tz);
+    return m;
+}
+
+inline Matrixf Matrixf::translate(const Vec3f& v )
+{
+    return translate(v.x(), v.y(), v.z() );
+}
+
+inline Matrixf Matrixf::translate(const Vec3d& v )
+{
+    return translate(v.x(), v.y(), v.z() );
+}
+
+inline Matrixf Matrixf::rotate( const Quat& q )
+{
+    return Matrixf(q);
+}
+inline Matrixf Matrixf::rotate(value_type angle, value_type x, value_type y, value_type z )
+{
+    Matrixf m;
+    m.makeRotate(angle,x,y,z);
+    return m;
+}
+inline Matrixf Matrixf::rotate(value_type angle, const Vec3f& axis )
+{
+    Matrixf m;
+    m.makeRotate(angle,axis);
+    return m;
+}
+inline Matrixf Matrixf::rotate(value_type angle, const Vec3d& axis )
+{
+    Matrixf m;
+    m.makeRotate(angle,axis);
+    return m;
+}
+inline Matrixf Matrixf::rotate( value_type angle1, const Vec3f& axis1, 
+                              value_type angle2, const Vec3f& axis2,
+                              value_type angle3, const Vec3f& axis3)
+{
+    Matrixf m;
+    m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+    return m;
+}
+inline Matrixf Matrixf::rotate( value_type angle1, const Vec3d& axis1, 
+                              value_type angle2, const Vec3d& axis2,
+                              value_type angle3, const Vec3d& axis3)
+{
+    Matrixf m;
+    m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+    return m;
+}
+inline Matrixf Matrixf::rotate(const Vec3f& from, const Vec3f& to )
+{
+    Matrixf m;
+    m.makeRotate(from,to);
+    return m;
+}
+inline Matrixf Matrixf::rotate(const Vec3d& from, const Vec3d& to )
+{
+    Matrixf m;
+    m.makeRotate(from,to);
+    return m;
+}
+
+inline Matrixf Matrixf::inverse( const Matrixf& matrix)
+{
+    Matrixf m;
+    m.invert(matrix);
+    return m;
+}
+
+inline Matrixf Matrixf::orthoNormal(const Matrixf& matrix)
+{
+  Matrixf m;
+  m.orthoNormalize(matrix);
+  return m; 
+}
+
+inline Matrixf Matrixf::ortho(double left, double right,
+                            double bottom, double top,
+                            double zNear, double zFar)
+{
+    Matrixf m;
+    m.makeOrtho(left,right,bottom,top,zNear,zFar);
+    return m;
+}
+
+inline Matrixf Matrixf::ortho2D(double left, double right,
+                              double bottom, double top)
+{
+    Matrixf m;
+    m.makeOrtho2D(left,right,bottom,top);
+    return m;
+}
+
+inline Matrixf Matrixf::frustum(double left, double right,
+                              double bottom, double top,
+                              double zNear, double zFar)
+{
+    Matrixf m;
+    m.makeFrustum(left,right,bottom,top,zNear,zFar);
+    return m;
+}
+
+inline Matrixf Matrixf::perspective(double fovy,double aspectRatio,
+                                  double zNear, double zFar)
+{
+    Matrixf m;
+    m.makePerspective(fovy,aspectRatio,zNear,zFar);
+    return m;
+}
+
+inline Matrixf Matrixf::lookAt(const Vec3f& eye,const Vec3f& center,const Vec3f& up)
+{
+    Matrixf m;
+    m.makeLookAt(eye,center,up);
+    return m;
+}
+
+inline Matrixf Matrixf::lookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up)
+{
+    Matrixf m;
+    m.makeLookAt(eye,center,up);
+    return m;
+}
+
+inline Vec3f Matrixf::postMult( const Vec3f& v ) const
+{
+    value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ;
+    return Vec3f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d,
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d,
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ;
+}
+inline Vec3d Matrixf::postMult( const Vec3d& v ) const
+{
+    value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ;
+    return Vec3d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d,
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d,
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ;
+}
+
+inline Vec3f Matrixf::preMult( const Vec3f& v ) const
+{
+    value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ;
+    return Vec3f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d,
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d,
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d);
+}
+inline Vec3d Matrixf::preMult( const Vec3d& v ) const
+{
+    value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ;
+    return Vec3d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d,
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d,
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d);
+}
+
+inline Vec4f Matrixf::postMult( const Vec4f& v ) const
+{
+    return Vec4f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()),
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()),
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()),
+        (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ;
+}
+inline Vec4d Matrixf::postMult( const Vec4d& v ) const
+{
+    return Vec4d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()),
+        (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()),
+        (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()),
+        (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ;
+}
+
+inline Vec4f Matrixf::preMult( const Vec4f& v ) const
+{
+    return Vec4f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()),
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()),
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()),
+        (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w()));
+}
+inline Vec4d Matrixf::preMult( const Vec4d& v ) const
+{
+    return Vec4d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()),
+        (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()),
+        (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()),
+        (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w()));
+}
+inline Vec3f Matrixf::transform3x3(const Vec3f& v,const Matrixf& m)
+{
+    return Vec3f( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()),
+                 (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()),
+                 (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z()));
+}
+inline Vec3d Matrixf::transform3x3(const Vec3d& v,const Matrixf& m)
+{
+    return Vec3d( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()),
+                 (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()),
+                 (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z()));
+}
+
+inline Vec3f Matrixf::transform3x3(const Matrixf& m,const Vec3f& v)
+{
+    return Vec3f( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()),
+                 (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()),
+                 (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ;
+}
+inline Vec3d Matrixf::transform3x3(const Matrixf& m,const Vec3d& v)
+{
+    return Vec3d( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()),
+                 (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()),
+                 (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ;
+}
+
+inline void Matrixf::preMultTranslate( const Vec3d& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        double tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[3][0] += tmp*_mat[i][0];
+        _mat[3][1] += tmp*_mat[i][1];
+        _mat[3][2] += tmp*_mat[i][2];
+        _mat[3][3] += tmp*_mat[i][3];
+    }
+}
+
+inline void Matrixf::preMultTranslate( const Vec3f& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        float tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[3][0] += tmp*_mat[i][0];
+        _mat[3][1] += tmp*_mat[i][1];
+        _mat[3][2] += tmp*_mat[i][2];
+        _mat[3][3] += tmp*_mat[i][3];
+    }
+}
+
+inline void Matrixf::postMultTranslate( const Vec3d& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        double tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[0][i] += tmp*_mat[0][3];
+        _mat[1][i] += tmp*_mat[1][3];
+        _mat[2][i] += tmp*_mat[2][3];
+        _mat[3][i] += tmp*_mat[3][3];
+    }
+}
+
+inline void Matrixf::postMultTranslate( const Vec3f& v )
+{
+    for (unsigned i = 0; i < 3; ++i)
+    {
+        float tmp = v[i];
+        if (tmp == 0)
+            continue;
+        _mat[0][i] += tmp*_mat[0][3];
+        _mat[1][i] += tmp*_mat[1][3];
+        _mat[2][i] += tmp*_mat[2][3];
+        _mat[3][i] += tmp*_mat[3][3];
+    }
+}
+
+inline void Matrixf::preMultScale( const Vec3d& v )
+{
+    _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0];
+    _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1];
+    _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2];
+}
+
+inline void Matrixf::preMultScale( const Vec3f& v )
+{
+    _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0];
+    _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1];
+    _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2];
+}
+
+inline void Matrixf::postMultScale( const Vec3d& v )
+{
+    _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0];
+    _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1];
+    _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2];
+}
+
+inline void Matrixf::postMultScale( const Vec3f& v )
+{
+    _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0];
+    _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1];
+    _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2];
+}
+
+
+inline void Matrixf::preMultRotate( const Quat& q )
+{
+    if (q.zeroRotation())
+        return;
+    Matrixf r;
+    r.setRotate(q);
+    preMult(r);
+}
+
+inline void Matrixf::postMultRotate( const Quat& q )
+{
+    if (q.zeroRotation())
+        return;
+    Matrixf r;
+    r.setRotate(q);
+    postMult(r);
+}
+
+inline Vec3f operator* (const Vec3f& v, const Matrixf& m )
+{
+    return m.preMult(v);
+}
+inline Vec3d operator* (const Vec3d& v, const Matrixf& m )
+{
+    return m.preMult(v);
+}
+inline Vec4f operator* (const Vec4f& v, const Matrixf& m )
+{
+    return m.preMult(v);
+}
+inline Vec4d operator* (const Vec4d& v, const Matrixf& m )
+{
+    return m.preMult(v);
+}
+
+inline Vec3f Matrixf::operator* (const Vec3f& v) const
+{
+    return postMult(v);
+}
+inline Vec3d Matrixf::operator* (const Vec3d& v) const
+{
+    return postMult(v);
+}
+inline Vec4f Matrixf::operator* (const Vec4f& v) const
+{
+    return postMult(v);
+}
+inline Vec4d Matrixf::operator* (const Vec4d& v) const
+{
+    return postMult(v);
+}
+
+
+} //namespace osg
+
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Timer
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Timer (revision 9439)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Timer (revision 9439)
@@ -0,0 +1,81 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TIMER
+#define OSG_TIMER 1
+
+#include <osg/Export>
+
+namespace osg {
+
+#if defined(_MSC_VER)
+    typedef __int64 Timer_t;
+#else
+    typedef unsigned long long Timer_t;
+#endif
+
+/** Timer class is used for measuring elapsed time or time between two points. */
+class OSG_EXPORT Timer {
+
+    public:
+
+        Timer();
+        ~Timer() {}
+
+        static Timer* instance();
+
+        /** Get the timers tick value.*/
+        Timer_t tick() const;
+
+        /** Set the start.*/
+        void setStartTick() { _startTick = tick(); }
+        void setStartTick(Timer_t t) { _startTick = t; }
+        Timer_t getStartTick() const { return _startTick; }
+
+        
+        /** Get elapsed time in seconds.*/
+        inline double time_s() const { return delta_s(_startTick, tick()); }
+
+        /** Get elapsed time in milliseconds.*/
+        inline double time_m() const { return delta_m(_startTick, tick()); }
+
+        /** Get elapsed time in micoseconds.*/
+        inline double time_u() const { return delta_u(_startTick, tick()); }
+
+        /** Get elapsed time in nanoseconds.*/
+        inline double time_n() const { return delta_n(_startTick, tick()); }
+        
+        /** Get the time in seconds between timer ticks t1 and t2.*/
+        inline double delta_s( Timer_t t1, Timer_t t2 ) const { return (double)(t2 - t1)*_secsPerTick; }
+
+        /** Get the time in milliseconds between timer ticks t1 and t2.*/
+        inline double delta_m( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e3; }
+
+        /** Get the time in microseconds between timer ticks t1 and t2.*/
+        inline double delta_u( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e6; }
+
+        /** Get the time in nanoseconds between timer ticks t1 and t2.*/
+        inline double delta_n( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e9; }
+        
+        /** Get the the number of seconds per tick. */
+        inline double getSecondsPerTick() const { return _secsPerTick; }
+
+    protected :
+
+        Timer_t _startTick;
+        double  _secsPerTick;
+
+};
+
+}
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CameraView
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CameraView (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CameraView (revision 7648)
@@ -0,0 +1,105 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_CAMERAVIEW
+#define OSG_CAMERAVIEW 1
+
+#include <osg/Group>
+#include <osg/Transform>
+#include <osg/AnimationPath>
+#include <osg/Vec3d>
+#include <osg/Quat>
+
+namespace osg {
+
+/** CameraView - is a Transform that is used to specify camera views from within the scene graph.
+  * The application must attach a camera to a CameraView via the NodePath from the top of the scene graph
+  * to the CameraView node itself, and accumulate the view matrix from this NodePath.
+*/
+class OSG_EXPORT CameraView : public Transform
+{
+    public :
+        CameraView();
+
+        CameraView(const CameraView& pat,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            Transform(pat,copyop),
+            _position(pat._position),
+            _attitude(pat._attitude),
+            _fieldOfView(pat._fieldOfView),
+            _fieldOfViewMode(pat._fieldOfViewMode),
+            _focalLength(pat._focalLength) {}
+            
+
+        META_Node(osg, CameraView);
+
+        /** Set the position of the camera view.*/
+        inline void setPosition(const Vec3d& pos) { _position = pos; dirtyBound(); }
+
+        /** Get the position of the camera view.*/
+        inline const Vec3d& getPosition() const { return _position; }
+
+        /** Set the attitude of the camera view.*/
+        inline void setAttitude(const Quat& quat) { _attitude = quat; dirtyBound(); }
+
+        /** Get the attitude of the camera view.*/
+        inline const Quat& getAttitude() const { return _attitude; }
+
+        /** Set the field of view.
+          * The cameras field of view can be constrained to either the horizontal or vertex axis of the camera, or unconstrained
+          * in which case the camera/application are left to choose an appropriate field of view.
+          * The default value if 60 degrees. */
+        inline void setFieldOfView(double fieldOfView) { _fieldOfView = fieldOfView; }
+
+        /** Get the field of view.*/
+        inline double getFieldOfView() const { return _fieldOfView; }
+        
+        enum FieldOfViewMode
+        {
+            UNCONSTRAINED,
+            HORIZONTAL,
+            VERTICAL
+        };
+
+        /** Set the field of view mode - controlling how the field of view of the camera is constrained by the CameaView settings.*/
+        inline void setFieldOfViewMode(FieldOfViewMode mode) { _fieldOfViewMode = mode; }
+
+        /** Get the field of view mode.*/
+        inline FieldOfViewMode getFieldOfViewMode() const { return _fieldOfViewMode; }
+
+        /** Set the focal length of the camera.
+          * A focal length of 0.0 indicates that the camera/application should determine the focal length.
+          * The default value is 0.0. */
+        inline void setFocalLength(double focalLength) { _focalLength = focalLength; }
+
+        /** Get the focal length of the camera.*/
+        inline double getFocalLength() const { return _focalLength; }
+        
+
+        virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor* nv) const;
+        virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor* nv) const;
+
+
+    protected :
+            
+        virtual ~CameraView() {}
+
+        Vec3d           _position;
+        Quat            _attitude;
+        double          _fieldOfView;
+        FieldOfViewMode _fieldOfViewMode;
+        double          _focalLength;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PrimitiveSet
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PrimitiveSet (revision 9599)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/PrimitiveSet (revision 9599)
@@ -0,0 +1,689 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_PRIMITIVESET
+#define OSG_PRIMITIVESET 1
+
+#include <osg/GL>
+#include <osg/Object>
+#include <osg/buffered_value>
+#include <osg/Vec2>
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/Vec2d>
+#include <osg/Vec3d>
+#include <osg/Vec4d>
+#include <osg/MixinVector>
+
+#include <osg/BufferObject>
+
+#include <vector>
+
+namespace osg {
+
+typedef MixinVector<GLsizei> VectorGLsizei;
+typedef MixinVector<GLubyte> VectorGLubyte;
+typedef MixinVector<GLushort> VectorGLushort;
+typedef MixinVector<GLuint> VectorGLuint;
+
+class State;
+
+/** A \c PrimitiveFunctor is used (in conjunction with
+ *  <tt>osg::Drawable::accept (PrimitiveFunctor&)</tt>) to get access to the
+ *  primitives that compose the things drawn by OSG.
+ *  <p>If \c osg::Drawable::accept() is called with a \c PrimitiveFunctor
+ *  parameter, the \c Drawable will "pretend" it is drawing itself, but instead
+ *  of calling real OpenGL functions, it will call <tt>PrimitiveFunctor</tt>'s
+ *  member functions that "mimic" the OpenGL calls.
+ *  <p>Concrete subclasses of \c PrimitiveFunctor must implement these methods
+ *  so that they performs whatever they want.
+ */
+class PrimitiveFunctor
+{
+public:
+
+    virtual ~PrimitiveFunctor() {}
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec2* vertices) = 0;
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec3* vertices) = 0;
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec4* vertices) = 0;
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec2d* vertices) = 0;
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec3d* vertices) = 0;
+
+    /** Sets the array of vertices used to describe the primitives. Somehow
+     *  mimics the OpenGL \c glVertexPointer() function.
+     */
+    virtual void setVertexArray(unsigned int count,const Vec4d* vertices) = 0;
+
+    /// Mimics the OpenGL \c glDrawArrays() function.
+    virtual void drawArrays(GLenum mode,GLint first,GLsizei count) = 0;
+
+    /// Mimics the OpenGL \c glDrawElements() function.
+    virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 0;
+
+    /// Mimics the OpenGL \c glDrawElements() function.
+    virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) = 0;
+
+    /// Mimics the OpenGL \c glDrawElements() function.
+    virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0;
+
+    /// Mimics the OpenGL \c glBegin() function.
+    virtual void begin(GLenum mode) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(const Vec2& vert) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(const Vec3& vert) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(const Vec4& vert) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(float x,float y) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(float x,float y,float z) = 0;
+
+    /// Mimics the OpenGL \c glVertex() "family of functions".
+    virtual void vertex(float x,float y,float z,float w) = 0;
+
+    /// Mimics the OpenGL \c glEnd() function.
+    virtual void end() = 0;
+};
+
+class PrimitiveIndexFunctor
+{
+public:
+
+    virtual ~PrimitiveIndexFunctor() {}
+
+    virtual void setVertexArray(unsigned int count,const Vec2* vertices) = 0;
+    virtual void setVertexArray(unsigned int count,const Vec3* vertices) = 0;
+    virtual void setVertexArray(unsigned int count,const Vec4* vertices) = 0;
+
+    virtual void setVertexArray(unsigned int count,const Vec2d* vertices) = 0;
+    virtual void setVertexArray(unsigned int count,const Vec3d* vertices) = 0;
+    virtual void setVertexArray(unsigned int count,const Vec4d* vertices) = 0;
+
+    virtual void drawArrays(GLenum mode,GLint first,GLsizei count) = 0;
+    virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 0;
+    virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) = 0;
+    virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0;
+
+    virtual void begin(GLenum mode) = 0;
+    virtual void vertex(unsigned int pos) = 0;
+    virtual void end() = 0;
+};
+
+class DrawElements;
+
+class OSG_EXPORT PrimitiveSet : public Object
+{
+    public:
+    
+        enum Type
+        {
+            PrimitiveType,
+            DrawArraysPrimitiveType,
+            DrawArrayLengthsPrimitiveType,
+            DrawElementsUBytePrimitiveType,
+            DrawElementsUShortPrimitiveType,
+            DrawElementsUIntPrimitiveType
+        };
+
+        enum Mode
+        {
+            POINTS = GL_POINTS,
+            LINES = GL_LINES,
+            LINE_STRIP = GL_LINE_STRIP,
+            LINE_LOOP = GL_LINE_LOOP,
+            TRIANGLES = GL_TRIANGLES,
+            TRIANGLE_STRIP = GL_TRIANGLE_STRIP,
+            TRIANGLE_FAN = GL_TRIANGLE_FAN,
+            QUADS = GL_QUADS,
+            QUAD_STRIP = GL_QUAD_STRIP,
+            POLYGON = GL_POLYGON
+        };
+
+        PrimitiveSet(Type primType=PrimitiveType,GLenum mode=0, int numInstances=0):
+            _primitiveType(primType),
+            _numInstances(numInstances),
+            _mode(mode),
+            _modifiedCount(0),
+            _rangeModifiedCount(0) {}
+    
+        PrimitiveSet(const PrimitiveSet& prim,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            Object(prim,copyop),
+            _primitiveType(prim._primitiveType),
+            _numInstances(prim._numInstances),
+            _mode(prim._mode),
+            _modifiedCount(0),
+            _rangeModifiedCount(0) {}
+
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const PrimitiveSet*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "PrimitiveSet"; }
+        
+        Type                    getType() const { return _primitiveType; }
+        virtual const GLvoid*   getDataPointer() const { return 0; }
+        virtual unsigned int    getTotalDataSize() const { return 0; }
+        virtual bool            supportsBufferObject() const { return false; }
+
+        virtual DrawElements* getDrawElements() { return 0; }
+        virtual const DrawElements* getDrawElements() const { return 0; }
+            
+        void setNumInstances(int n) { _numInstances = n; }
+        int getNumInstances() const { return _numInstances; }
+
+        void setMode(GLenum mode) { _mode = mode; }
+        GLenum getMode() const { return _mode; }
+
+        virtual void draw(State& state, bool useVertexBufferObjects) const = 0;
+        
+        virtual void accept(PrimitiveFunctor& functor) const = 0;
+        virtual void accept(PrimitiveIndexFunctor& functor) const = 0;
+        
+        virtual unsigned int index(unsigned int pos) const = 0;
+        virtual unsigned int getNumIndices() const = 0;
+        virtual void offsetIndices(int offset) = 0;
+
+        virtual unsigned int getNumPrimitives() const; 
+
+        /** Dirty the primitive, which increments the modified count, to force buffer objects to update. */
+        virtual void dirty() { ++_modifiedCount; }      
+      
+        /** Set the modified count value.*/
+        inline void setModifiedCount(unsigned int value) { _modifiedCount=value; }
+
+        /** Get modified count value.*/
+        inline unsigned int getModifiedCount() const { return _modifiedCount; }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {}
+
+        /** If State is non-zero, this function releases OpenGL objects for
+          * the specified graphics context. Otherwise, releases OpenGL objects
+          * for all graphics contexts. */
+        virtual void releaseGLObjects(State* /*state*/=0) const {}
+
+        virtual void computeRange() const {}
+
+    protected:
+
+        virtual ~PrimitiveSet() {}
+
+        Type            _primitiveType;
+        int             _numInstances;
+        GLenum          _mode;
+        unsigned int    _modifiedCount;
+        mutable unsigned int    _rangeModifiedCount;
+
+        struct ObjectIDModifiedCountPair
+        {
+            ObjectIDModifiedCountPair():
+                _objectID(0),
+                _modifiedCount(0) {}
+                
+            ObjectIDModifiedCountPair(const ObjectIDModifiedCountPair& obj):
+                _objectID(obj._objectID),
+                _modifiedCount(obj._modifiedCount) {}
+                
+            ObjectIDModifiedCountPair& operator = (const ObjectIDModifiedCountPair& obj)
+            {
+                _objectID = obj._objectID;
+                _modifiedCount = obj._modifiedCount;
+                return *this;
+            }
+
+            GLuint _objectID;
+            unsigned int _modifiedCount;
+        };
+        
+        typedef osg::buffered_object<ObjectIDModifiedCountPair> GLObjectList;
+};
+
+class OSG_EXPORT DrawArrays : public PrimitiveSet
+{
+    public:
+
+        DrawArrays(GLenum mode=0):
+            PrimitiveSet(DrawArraysPrimitiveType,mode),
+            _first(0),
+            _count(0) {}
+    
+        DrawArrays(GLenum mode, GLint first, GLsizei count, int numInstances=0):
+            PrimitiveSet(DrawArraysPrimitiveType, mode, numInstances),
+            _first(first),
+            _count(count) {}
+
+        DrawArrays(const DrawArrays& da,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            PrimitiveSet(da,copyop),
+            _first(da._first),
+            _count(da._count) {}
+
+        virtual Object* cloneType() const { return new DrawArrays(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new DrawArrays(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const DrawArrays*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "DrawArrays"; }
+        
+
+        void set(GLenum mode,GLint first, GLsizei count)
+        {
+            _mode = mode;
+            _first = first;
+            _count = count;
+        }
+
+        void setFirst(GLint first) { _first = first; }
+        GLint getFirst() const { return _first; }
+        
+        void setCount(GLsizei count) { _count = count; }
+        GLsizei getCount() const { return _count; }
+
+        virtual void draw(State& state, bool useVertexBufferObjects) const;
+        
+        virtual void accept(PrimitiveFunctor& functor) const;
+        virtual void accept(PrimitiveIndexFunctor& functor) const;
+        
+        virtual unsigned int getNumIndices() const { return static_cast<unsigned int>(_count); }
+        virtual unsigned int index(unsigned int pos) const { return static_cast<unsigned int>(_first)+pos; }
+        virtual void offsetIndices(int offset) { _first += offset; }
+
+    protected:
+
+        virtual ~DrawArrays() {}
+
+        GLint   _first;
+        GLsizei _count;
+};
+
+class OSG_EXPORT DrawArrayLengths : public PrimitiveSet, public VectorGLsizei
+{
+    public:
+
+        typedef VectorGLsizei vector_type;
+
+        DrawArrayLengths(GLenum mode=0):
+            PrimitiveSet(DrawArrayLengthsPrimitiveType,mode),
+            _first(0) {}
+    
+        DrawArrayLengths(const DrawArrayLengths& dal,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            PrimitiveSet(dal,copyop),
+            vector_type(dal),
+            _first(dal._first) {}
+
+        DrawArrayLengths(GLenum mode, GLint first, unsigned int no, GLsizei* ptr) : 
+            PrimitiveSet(DrawArrayLengthsPrimitiveType,mode),
+            vector_type(ptr,ptr+no),
+            _first(first) {}
+
+        DrawArrayLengths(GLenum mode,GLint first, unsigned int no) : 
+            PrimitiveSet(DrawArrayLengthsPrimitiveType,mode),
+            vector_type(no),
+            _first(first) {}
+
+        DrawArrayLengths(GLenum mode,GLint first) : 
+            PrimitiveSet(DrawArrayLengthsPrimitiveType,mode),
+            vector_type(),
+            _first(first) {}
+
+
+        virtual Object* cloneType() const { return new DrawArrayLengths(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new DrawArrayLengths(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const DrawArrayLengths*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "DrawArrayLengths"; }
+        
+
+        void setFirst(GLint first) { _first = first; }
+        GLint getFirst() const { return _first; }
+        
+        virtual void draw(State& state, bool useVertexBufferObjects) const;
+        
+        virtual void accept(PrimitiveFunctor& functor) const;
+        virtual void accept(PrimitiveIndexFunctor& functor) const;
+        
+        virtual unsigned int getNumIndices() const;
+        virtual unsigned int index(unsigned int pos) const { return _first+pos; }
+        virtual void offsetIndices(int offset) { _first += offset; }
+
+        virtual unsigned int getNumPrimitives() const;
+
+    protected:
+
+        virtual ~DrawArrayLengths() {}
+
+        GLint   _first;
+};
+
+class DrawElements : public PrimitiveSet
+{
+    public:
+        
+        DrawElements(Type primType=PrimitiveType, GLenum mode=0, int numInstances=0):
+            PrimitiveSet(primType,mode, numInstances),
+            _eboOffset(0) {}
+    
+        DrawElements(const DrawElements& copy,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            PrimitiveSet(copy,copyop),
+            _eboOffset(0) {}
+
+
+        virtual DrawElements* getDrawElements() { return this; }
+        virtual const DrawElements* getDrawElements() const { return this; }
+
+        virtual void dirty() { ++_modifiedCount; if (_ebo.valid()) _ebo->dirty(); } 
+
+        /** Set the ElementBufferObject.*/
+        inline void setElementBufferObject(osg::ElementBufferObject* ebo)
+        {
+            if (_ebo == ebo) return;
+            
+            if (_ebo.valid())
+            {
+                _ebo->removeDrawElements(this);
+            }
+            
+            _ebo = ebo;
+
+            if (_ebo.valid())
+            {
+                _ebo->addDrawElements(this);
+            }
+        }
+        
+        /** Get the ElementBufferObject. If no EBO is assigned returns NULL*/
+        inline osg::ElementBufferObject* getElementBufferObject() { return _ebo.get(); }
+
+        /** Get the const ElementBufferObject. If no EBO is assigned returns NULL*/
+        inline const osg::ElementBufferObject* getElementBufferObject() const { return _ebo.get(); }
+
+        /** Set the offset into the ElementBufferObject, if used.*/
+        inline void setElementBufferObjectOffset(const GLvoid* offset) const { _eboOffset = offset; }
+
+        /** Get the offset into the ElementBufferOffset, if used.*/
+        inline const GLvoid* getElementBufferObjectOffset() const { return _eboOffset; }
+
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize)
+        {
+            if (_ebo.valid()) _ebo->resizeGLObjectBuffers(maxSize);
+        }
+
+        /** If State is non-zero, this function releases OpenGL objects for
+          * the specified graphics context. Otherwise, releases OpenGL objects
+          * for all graphics contexts. */
+        virtual void releaseGLObjects(State* state=0) const
+        {
+            if (_ebo.valid()) _ebo->releaseGLObjects(state);
+        }
+
+    protected:
+    
+        virtual ~DrawElements()
+        {
+            if (_ebo.valid())
+            {
+                _ebo->removeDrawElements(this);
+            }
+        }
+
+        osg::ref_ptr<ElementBufferObject>   _ebo;
+        mutable const GLvoid*               _eboOffset;
+
+};
+
+class OSG_EXPORT DrawElementsUByte : public DrawElements, public VectorGLubyte
+{
+    public:
+    
+        typedef VectorGLubyte vector_type;
+
+        DrawElementsUByte(GLenum mode=0):
+            DrawElements(DrawElementsUBytePrimitiveType,mode) {}
+    
+        DrawElementsUByte(const DrawElementsUByte& array, const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            DrawElements(array,copyop),
+            vector_type(array) {}
+
+        DrawElementsUByte(GLenum mode, unsigned int no, const GLubyte* ptr, int numInstances=0) : 
+            DrawElements(DrawElementsUBytePrimitiveType,mode,numInstances),
+            vector_type(ptr,ptr+no) {}
+
+        DrawElementsUByte(GLenum mode, unsigned int no) : 
+            DrawElements(DrawElementsUBytePrimitiveType,mode),
+            vector_type(no) {}
+
+        virtual Object* cloneType() const { return new DrawElementsUByte(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUByte(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const DrawElementsUByte*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "DrawElementsUByte"; }
+
+        virtual const GLvoid*   getDataPointer() const { return empty()?0:&front(); }
+        virtual unsigned int    getTotalDataSize() const { return static_cast<unsigned int>(size()); }
+        virtual bool            supportsBufferObject() const { return false; }
+
+        virtual void draw(State& state, bool useVertexBufferObjects) const ;
+        
+        virtual void accept(PrimitiveFunctor& functor) const;
+        virtual void accept(PrimitiveIndexFunctor& functor) const;
+
+        virtual unsigned int getNumIndices() const { return static_cast<unsigned int>(size()); }
+        virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; }
+        virtual void offsetIndices(int offset);
+        
+        virtual void computeRange() const
+        {
+            if (empty()) 
+            {
+                _minIndex = 0;
+                _maxIndex = 0;
+                _rangeModifiedCount = _modifiedCount;
+                return;
+            }
+            
+            _minIndex = front();
+            _maxIndex = _minIndex;
+
+            for(vector_type::const_iterator itr=begin(); itr!=end();  ++itr)
+            {
+                if (*itr<_minIndex) _minIndex = *itr;
+                if (*itr>_maxIndex) _maxIndex = *itr;
+            }
+            _rangeModifiedCount = _modifiedCount;
+        }
+        
+    protected:
+
+        virtual ~DrawElementsUByte();
+
+        mutable unsigned int    _minIndex;
+        mutable unsigned int    _maxIndex;
+};
+
+
+class OSG_EXPORT DrawElementsUShort : public DrawElements, public VectorGLushort
+{
+    public:
+
+        typedef VectorGLushort vector_type;
+
+        DrawElementsUShort(GLenum mode=0):
+            DrawElements(DrawElementsUShortPrimitiveType,mode) {}
+    
+        DrawElementsUShort(const DrawElementsUShort& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            DrawElements(array,copyop),
+            vector_type(array) {}
+
+        DrawElementsUShort(GLenum mode, unsigned int no, const GLushort* ptr, int numInstances=0) : 
+            DrawElements(DrawElementsUShortPrimitiveType,mode,numInstances),
+            vector_type(ptr,ptr+no) {}
+
+        DrawElementsUShort(GLenum mode, unsigned int no) : 
+            DrawElements(DrawElementsUShortPrimitiveType,mode),
+            vector_type(no) {}
+
+        template <class InputIterator>
+        DrawElementsUShort(GLenum mode, InputIterator first,InputIterator last) : 
+            DrawElements(DrawElementsUShortPrimitiveType,mode),
+            vector_type(first,last) {}
+
+        virtual Object* cloneType() const { return new DrawElementsUShort(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUShort(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const DrawElementsUShort*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "DrawElementsUShort"; }
+
+        virtual const GLvoid*   getDataPointer() const { return empty()?0:&front(); }
+        virtual unsigned int    getTotalDataSize() const { return 2u*static_cast<unsigned int>(size()); }
+        virtual bool            supportsBufferObject() const { return false; }
+
+        virtual void draw(State& state, bool useVertexBufferObjects) const;
+        
+        virtual void accept(PrimitiveFunctor& functor) const;
+        virtual void accept(PrimitiveIndexFunctor& functor) const;
+
+        virtual unsigned int getNumIndices() const { return static_cast<unsigned int>(size()); }
+        virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; }
+        virtual void offsetIndices(int offset);
+
+        virtual void computeRange() const
+        {
+            if (empty()) 
+            {
+                _minIndex = 0;
+                _maxIndex = 0;
+                _rangeModifiedCount = _modifiedCount;
+                return;
+            }
+            
+            _minIndex = front();
+            _maxIndex = _minIndex;
+
+            for(vector_type::const_iterator itr=begin(); itr!=end();  ++itr)
+            {
+                if (*itr<_minIndex) _minIndex = *itr;
+                if (*itr>_maxIndex) _maxIndex = *itr;
+            }
+            _rangeModifiedCount = _modifiedCount;
+        }
+
+    protected:
+
+        virtual ~DrawElementsUShort();
+
+        mutable unsigned int    _minIndex;
+        mutable unsigned int    _maxIndex;        
+};
+
+class OSG_EXPORT DrawElementsUInt : public DrawElements, public VectorGLuint
+{
+    public:
+
+        typedef VectorGLuint vector_type;
+
+        DrawElementsUInt(GLenum mode=0):
+            DrawElements(DrawElementsUIntPrimitiveType,mode) {}
+    
+        DrawElementsUInt(const DrawElementsUInt& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            DrawElements(array,copyop),
+            vector_type(array) {}
+
+        DrawElementsUInt(GLenum mode, unsigned int no, const GLuint* ptr, int numInstances=0) : 
+            DrawElements(DrawElementsUIntPrimitiveType,mode,numInstances),
+            vector_type(ptr,ptr+no) {}
+
+        DrawElementsUInt(GLenum mode, unsigned int no) : 
+            DrawElements(DrawElementsUIntPrimitiveType,mode),
+            vector_type(no) {}
+
+        template <class InputIterator>
+        DrawElementsUInt(GLenum mode, InputIterator first,InputIterator last) : 
+            DrawElements(DrawElementsUIntPrimitiveType,mode),
+            vector_type(first,last) {}
+
+        virtual Object* cloneType() const { return new DrawElementsUInt(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUInt(*this,copyop); }        
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const DrawElementsUInt*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "DrawElementsUInt"; }
+
+        virtual const GLvoid*   getDataPointer() const { return empty()?0:&front(); }
+        virtual unsigned int    getTotalDataSize() const { return 4u*static_cast<unsigned int>(size()); }
+        virtual bool            supportsBufferObject() const { return false; }
+
+        virtual void draw(State& state, bool useVertexBufferObjects) const;
+        
+        virtual void accept(PrimitiveFunctor& functor) const;
+        virtual void accept(PrimitiveIndexFunctor& functor) const;
+
+        virtual unsigned int getNumIndices() const { return static_cast<unsigned int>(size()); }
+        virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; }
+        virtual void offsetIndices(int offset);
+
+        
+        virtual void computeRange() const
+        {
+            if (empty()) 
+            {
+                _minIndex = 0;
+                _maxIndex = 0;
+                _rangeModifiedCount = _modifiedCount;
+                return;
+            }
+            
+            _minIndex = front();
+            _maxIndex = _minIndex;
+
+            for(vector_type::const_iterator itr=begin(); itr!=end();  ++itr)
+            {
+                if (*itr<_minIndex) _minIndex = *itr;
+                if (*itr>_maxIndex) _maxIndex = *itr;
+            }
+            _rangeModifiedCount = _modifiedCount;
+        }
+
+    protected:
+
+        virtual ~DrawElementsUInt();
+        
+        mutable unsigned int    _minIndex;
+        mutable unsigned int    _maxIndex;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2DArray
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2DArray (revision 9062)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Texture2DArray (revision 9062)
@@ -0,0 +1,230 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXTURE2DARRAY
+#define OSG_TEXTURE2DARRAY 1
+
+#include <osg/Texture>
+#include <list>
+
+namespace osg {
+
+/** Texture2DArray state class which encapsulates OpenGL 2D array texture functionality. 
+ * Texture arrays were introduced with Shader Model 4.0 hardware.
+ * 
+ * A 2D texture array does contain textures sharing the same properties (e.g. size, bitdepth,...)
+ * in a layered structure. See http://www.opengl.org/registry/specs/EXT/texture_array.txt for more info.
+ */
+class OSG_EXPORT Texture2DArray : public Texture
+{
+
+    public :
+        
+        Texture2DArray();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Texture2DArray(const Texture2DArray& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osg, Texture2DArray, TEXTURE);
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& rhs) const;
+
+        virtual GLenum getTextureTarget() const { return GL_TEXTURE_2D_ARRAY_EXT; }
+
+        /** Set the texture image for specified layer. */
+        virtual void setImage(unsigned int layer, Image* image);
+
+        /** Get the texture image for specified layer. */
+        virtual Image* getImage(unsigned int layer);
+
+        /** Get the const texture image for specified layer. */
+        virtual const Image* getImage(unsigned int layer) const;
+
+        /** Get the number of images that are assigned to the Texture. 
+         * The number is equal to the texture depth. To get the maximum possible
+         * image/layer count, you have to use the extension subclass, since it provides
+         * graphic context dependent information.
+         */
+        virtual unsigned int getNumImages() const { return getTextureDepth(); } 
+
+        /** Check how often was a certain layer in the given context modified */
+        inline unsigned int& getModifiedCount(unsigned int layer, unsigned int contextID) const
+        {
+            // get the modified count for the current contextID.
+            return _modifiedCount[layer][contextID];
+        }
+
+        /** Set the texture width and height. If width or height are zero then
+          * the respective size value is calculated from the source image sizes.
+          * Depth parameter specifies the number of layers to be used.
+        */
+        void setTextureSize(int width, int height, int depth);
+
+        void setTextureWidth(int width) { _textureWidth=width; }
+        void setTextureHeight(int height) { _textureHeight=height; }
+        void setTextureDepth(int depth);
+
+        virtual int getTextureWidth() const { return _textureWidth; }
+        virtual int getTextureHeight() const { return _textureHeight; }
+        virtual int getTextureDepth() const { return _textureDepth; }
+
+        class OSG_EXPORT SubloadCallback : public Referenced
+        {
+            public:
+                virtual void load(const Texture2DArray& texture,State& state) const = 0;
+                virtual void subload(const Texture2DArray& texture,State& state) const = 0;
+        };
+        
+        
+        void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; }
+        
+        SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
+
+        const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
+        
+        
+
+        /** Set the number of mip map levels the the texture has been created with.
+          * Should only be called within an osg::Texture::apply() and custom OpenGL texture load.
+        */
+        void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; }
+
+        /** Get the number of mip map levels the the texture has been created with. */
+        unsigned int getNumMipmapLevels() const { return _numMipmapLevels; }        
+
+        /** Copies a two-dimensional texture subimage, as per
+          * glCopyTexSubImage3D. Updates a portion of an existing OpenGL
+          * texture object from the current OpenGL background framebuffer
+          * contents at position \a x, \a y with width \a width and height
+          * \a height. Loads framebuffer data into the texture using offsets
+          * \a xoffset and \a yoffset. \a zoffset specifies the layer of the texture 
+          * array to which the result is copied. 
+          */
+        void copyTexSubImage2DArray(State& state, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height );
+
+        /** Bind the texture if already compiled. Otherwise recompile.
+        */
+        virtual void apply(State& state) const;
+        
+
+        /** Extensions class which encapsulates the querying of extensions and
+          * associated function pointers, and provides convenience wrappers to 
+          * check for the extensions or use the associated functions.
+        */
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setTexture2DArraySupported(bool flag) { _isTexture2DArraySupported=flag; }
+                bool isTexture2DArraySupported() const { return _isTexture2DArraySupported; }
+                
+                void setTexture3DSupported(bool flag) { _isTexture3DSupported=flag; }
+                bool isTexture3DSupported() const { return _isTexture3DSupported; }
+
+                void setMaxLayerCount(GLint count) { _maxLayerCount = count; }
+                GLint maxLayerCount() const { return _maxLayerCount; }
+                
+                void setMax2DSize(GLint size) { _max2DSize = size; }
+                GLint max2DSize() const { return _max2DSize; }
+                
+                void glTexImage3D( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels) const;
+
+                void glTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels) const;
+                
+                void glCopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) const;
+                
+                bool isCompressedTexImage3DSupported() const { return _glCompressedTexImage3D!=0; }
+                void glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data) const;
+
+                bool isCompressedTexSubImage3DSupported() const { return _glCompressedTexSubImage3D!=0; }
+                void glCompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data ) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool    _isTexture2DArraySupported;
+                bool    _isTexture3DSupported;
+                
+                GLint   _maxLayerCount;
+                GLint   _max2DSize;
+
+                typedef void (APIENTRY * GLTexImage3DProc)      ( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+                typedef void (APIENTRY * GLTexSubImage3DProc)   ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+                typedef void (APIENTRY * CompressedTexImage3DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * CompressedTexSubImage3DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+                typedef void (APIENTRY * GLCopyTexSubImageProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height );
+
+                GLTexImage3DProc                _glTexImage3D;
+                GLTexSubImage3DProc             _glTexSubImage3D;
+                CompressedTexImage3DArbProc     _glCompressedTexImage3D;
+                CompressedTexSubImage3DArbProc  _glCompressedTexSubImage3D;
+                GLCopyTexSubImageProc           _glCopyTexSubImage3D;
+                
+        };
+        
+        /** Function to call to get the extension of a specified context.
+          * If the Extension object for that context has not yet been created
+          * and the 'createIfNotInitalized' flag been set to false then returns NULL.
+          * If 'createIfNotInitalized' is true then the Extensions object is 
+          * automatically created. However, in this case the extension object will
+          * only be created with the graphics context associated with ContextID.
+        */
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** The setExtensions method allows users to override the extensions across graphics contexts.
+          * Typically used when you have different extensions supported across graphics pipes
+          * but need to ensure that they all use the same low common denominator extensions.
+        */
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+    protected :
+
+        virtual ~Texture2DArray();
+        
+        bool imagesValid() const;
+        
+        virtual void computeInternalFormat() const;
+        void allocateMipmap(State& state) const;
+
+        void applyTexImage2DArray_subload(State& state, Image* image, GLsizei inwidth, GLsizei inheight, GLsizei indepth, GLint inInternalFormat, GLsizei& numMipmapLevels) const;
+
+        /**
+         * Use std::vector to encapsulate referenced pointers to images of different layers.
+         * Vectors gives us a random access iterator. The overhead of non-used elements is negligeable */
+        std::vector<ref_ptr<Image> > _images;
+
+        // subloaded images can have different texture and image sizes.
+        mutable GLsizei _textureWidth, _textureHeight, _textureDepth;
+        
+        // number of mip map levels the the texture has been created with,        
+        mutable GLsizei _numMipmapLevels;
+
+        ref_ptr<SubloadCallback> _subloadCallback;
+
+        typedef buffered_value<unsigned int> ImageModifiedCount;
+        mutable std::vector<ImageModifiedCount> _modifiedCount;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Scissor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Scissor (revision 6311)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Scissor (revision 6311)
@@ -0,0 +1,110 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_Scissor
+#define OSG_Scissor 1
+
+#include <osg/StateAttribute>
+
+namespace osg {
+
+/** Encapsulate OpenGL glScissor. */     
+class OSG_EXPORT Scissor : public StateAttribute
+{
+    public :
+        Scissor();
+        
+        Scissor(int x,int y,int width,int height):
+            _x(x),
+            _y(y),
+            _width(width),
+            _height(height) {}
+            
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Scissor(const Scissor& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(vp,copyop),
+            _x(vp._x),
+            _y(vp._y),
+            _width(vp._width),
+            _height(vp._height) {}
+
+        META_StateAttribute(osg, Scissor, SCISSOR);
+        
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(Scissor,sa)
+
+            // compare each paramter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_x)
+            COMPARE_StateAttribute_Parameter(_y)
+            COMPARE_StateAttribute_Parameter(_width)
+            COMPARE_StateAttribute_Parameter(_height)
+            
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_SCISSOR_TEST);
+            return true;
+        }
+
+        inline void setScissor(int x,int y,int width,int height)
+        {
+            _x = x;
+            _y = y;
+            _width = width;
+            _height = height;
+        }
+        
+        void getScissor(int& x,int& y,int& width,int& height) const
+        {
+            x = _x;
+            y = _y;
+            width = _width;
+            height = _height;
+        }
+
+        inline int& x() { return _x; }
+        inline int x() const { return _x; }
+        
+        inline int& y() { return _y; }
+        inline int y() const { return _y; }
+
+        inline int& width() { return _width; }
+        inline int width() const { return _width; }
+
+        inline int& height() { return _height; }
+        inline int height() const { return _height; }
+
+        virtual void apply(State& state) const;
+
+    protected:
+    
+        virtual ~Scissor();
+
+        int _x;
+        int _y;
+        int _width;
+        int _height;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TransferFunction
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TransferFunction (revision 9618)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TransferFunction (revision 9618)
@@ -0,0 +1,128 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TRANSFERFUNCTION
+#define OSG_TRANSFERFUNCTION 1
+
+#include <osg/Texture>
+#include <osg/Shader>
+
+#include <map>
+
+namespace osg {
+
+
+/** TransferFunction is a class that provide a 1D,2D or 3D colour look up table
+  * that can be used on the GPU as a 1D, 2D or 3D texture.  
+  * Typically uses include mapping heights to colours when contouring terrain, 
+  * or mapping intensities to colours when volume rendering.
+*/
+class OSG_EXPORT TransferFunction : public osg::Object
+{
+    public :
+    
+        TransferFunction();
+
+       /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        TransferFunction(const TransferFunction& tf, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, TransferFunction)
+
+        /** Get the image that is used for passing the transfer function data to the GPU.*/
+        osg::Image* getImage() { return _image.get(); }
+
+        /** Get the const image that is used for passing the transfer function data to the GPU.*/
+        const osg::Image* getImage() const { return _image.get(); }
+        
+    protected:
+    
+        virtual ~TransferFunction();
+
+        osg::ref_ptr<osg::Image>    _image;
+};
+
+/** 1D variant of TransferFunction. */
+class OSG_EXPORT TransferFunction1D : public osg::TransferFunction
+{
+    public:
+    
+        TransferFunction1D();
+    
+       /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        TransferFunction1D(const TransferFunction1D& tf, const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_Object(osg, TransferFunction1D)
+        
+        /** Get the mnimum transfer function value.*/
+        float getMinimum() const { return _colorMap.empty() ? 0.0f : _colorMap.begin()->first; }
+        
+        /** Get the maximum transfer function value.*/
+        float getMaximum() const { return _colorMap.empty() ? 0.0f : _colorMap.rbegin()->first; }
+
+        /** allocate the osg::Image with specified dimension.  The Image tracks the color map, and is used to represent the
+          * transfer function when download to GPU.*/
+        void allocate(unsigned int numImageCells);
+
+        /** Clear the whole range to just represet a single color.*/
+        void clear(const osg::Vec4& color = osg::Vec4(1.0f,1.0f,1.0f,1.0f));
+        
+        /** Get pixel value from the image. */
+        osg::Vec4 getPixelValue(unsigned int i) const
+        {
+            if (_image.valid() && i<static_cast<unsigned int>(_image->s()))
+            {   
+                return *reinterpret_cast<osg::Vec4*>(_image->data(i));
+            }
+            else
+            {
+                return osg::Vec4(1.0f,1.0f,1.0f,1.0f);
+            }
+        }
+
+        /** Get the number of image cells that are assigned to the represent the transfer function when download to the GPU.*/
+        unsigned int getNumberImageCells() const { return _image.valid() ? _image->s() : 0; }
+
+        /** Set the color for a specified transfer function value.
+          * updateImage defaults to true, and tells the setColor function to update the associate osg::Image that
+          * tracks the color map.  Pass in false as the updateImage parameter if you are setting up many values
+          * at once to avoid recomputating og the image data, then once all setColor calls are made explictly call
+          * updateImage() to bring the osg::Image back into sync with the color map. */ 
+        void setColor(float v, const osg::Vec4& color, bool updateImage=true);
+        
+        /** Get the color for a specified transfer function value, interpolating the value if no exact match is found.*/
+        osg::Vec4 getColor(float v) const;
+        
+        typedef std::map<float, osg::Vec4> ColorMap;
+        
+        /** Get the color map that stores the mapping between the the tranfser function value and the colour it maps to.*/
+        ColorMap& getColorMap() { return _colorMap; }
+        
+        /** Get the const color map that stores the mapping between the the tranfser function value and the colour it maps to.*/
+        const ColorMap& getColorMap() const { return _colorMap; }
+
+        /** Assign a color map and automatically update the image to make sure they are in sync.*/
+        void assign(const ColorMap& vcm);
+        
+        /** Manually update the associate osg::Image to represent the colors assigned in the color map.*/
+        void updateImage();
+
+    protected:
+    
+        ColorMap _colorMap;
+        
+        void assignToImage(float lower_v, const osg::Vec4& lower_c, float upper_v, const osg::Vec4& upper_c);
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FragmentProgram
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FragmentProgram (revision 7773)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FragmentProgram (revision 7773)
@@ -0,0 +1,312 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_FRAGMENTPROGRAM
+#define OSG_FRAGMENTPROGRAM 1
+
+#include <osg/StateAttribute>
+#include <osg/Vec4>
+#include <osg/Matrix>
+#include <osg/buffered_value>
+
+#include <map>
+#include <string>
+
+// if not defined by gl.h use the definition found in:
+// http://oss.sgi.com/projects/ogl-sample/registry/ARB/fragment_program.txt
+#ifndef GL_ARB_fragment_program
+#define GL_FRAGMENT_PROGRAM_ARB                            0x8804
+#define GL_PROGRAM_FORMAT_ASCII_ARB                        0x8875
+#define GL_PROGRAM_LENGTH_ARB                              0x8627
+#define GL_PROGRAM_FORMAT_ARB                              0x8876
+#define GL_PROGRAM_BINDING_ARB                             0x8677
+#define GL_PROGRAM_INSTRUCTIONS_ARB                        0x88A0
+#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB                    0x88A1
+#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB                 0x88A2
+#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB             0x88A3
+#define GL_PROGRAM_TEMPORARIES_ARB                         0x88A4
+#define GL_MAX_PROGRAM_TEMPORARIES_ARB                     0x88A5
+#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB                  0x88A6
+#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB              0x88A7
+#define GL_PROGRAM_PARAMETERS_ARB                          0x88A8
+#define GL_MAX_PROGRAM_PARAMETERS_ARB                      0x88A9
+#define GL_PROGRAM_NATIVE_PARAMETERS_ARB                   0x88AA
+#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB               0x88AB
+#define GL_PROGRAM_ATTRIBS_ARB                             0x88AC
+#define GL_MAX_PROGRAM_ATTRIBS_ARB                         0x88AD
+#define GL_PROGRAM_NATIVE_ATTRIBS_ARB                      0x88AE
+#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB                  0x88AF
+#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB                0x88B4
+#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB                  0x88B5
+#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB                 0x88B6
+#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB                    0x8805
+#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB                    0x8806
+#define GL_PROGRAM_TEX_INDIRECTIONS_ARB                    0x8807
+#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB             0x8808
+#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB             0x8809
+#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB             0x880A
+#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB                0x880B
+#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB                0x880C
+#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB                0x880D
+#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB         0x880E
+#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB         0x880F
+#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB         0x8810
+#define GL_PROGRAM_STRING_ARB                              0x8628
+#define GL_PROGRAM_ERROR_POSITION_ARB                      0x864B
+#define GL_CURRENT_MATRIX_ARB                              0x8641
+#define GL_TRANSPOSE_CURRENT_MATRIX_ARB                    0x88B7
+#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB                  0x8640
+#define GL_MAX_PROGRAM_MATRICES_ARB                        0x862F
+#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB              0x862E
+#define GL_MAX_TEXTURE_COORDS_ARB                          0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB                     0x8872
+#define GL_PROGRAM_ERROR_STRING_ARB                        0x8874
+#define GL_MATRIX0_ARB                                     0x88C0
+#define GL_MATRIX1_ARB                                     0x88C1
+#define GL_MATRIX2_ARB                                     0x88C2
+#define GL_MATRIX3_ARB                                     0x88C3
+#define GL_MATRIX4_ARB                                     0x88C4
+#define GL_MATRIX5_ARB                                     0x88C5
+#define GL_MATRIX6_ARB                                     0x88C6
+#define GL_MATRIX7_ARB                                     0x88C7
+#define GL_MATRIX8_ARB                                     0x88C8
+#define GL_MATRIX9_ARB                                     0x88C9
+#define GL_MATRIX10_ARB                                    0x88CA
+#define GL_MATRIX11_ARB                                    0x88CB
+#define GL_MATRIX12_ARB                                    0x88CC
+#define GL_MATRIX13_ARB                                    0x88CD
+#define GL_MATRIX14_ARB                                    0x88CE
+#define GL_MATRIX15_ARB                                    0x88CF
+#define GL_MATRIX16_ARB                                    0x88D0
+#define GL_MATRIX17_ARB                                    0x88D1
+#define GL_MATRIX18_ARB                                    0x88D2
+#define GL_MATRIX19_ARB                                    0x88D3
+#define GL_MATRIX20_ARB                                    0x88D4
+#define GL_MATRIX21_ARB                                    0x88D5
+#define GL_MATRIX22_ARB                                    0x88D6
+#define GL_MATRIX23_ARB                                    0x88D7
+#define GL_MATRIX24_ARB                                    0x88D8
+#define GL_MATRIX25_ARB                                    0x88D9
+#define GL_MATRIX26_ARB                                    0x88DA
+#define GL_MATRIX27_ARB                                    0x88DB
+#define GL_MATRIX28_ARB                                    0x88DC
+#define GL_MATRIX29_ARB                                    0x88DD
+#define GL_MATRIX30_ARB                                    0x88DE
+#define GL_MATRIX31_ARB                                    0x88DF
+
+#endif
+
+
+namespace osg {
+
+
+
+/** FragmentProgram - encapsulates the OpenGL ARB fragment program state.*/
+class OSG_EXPORT FragmentProgram : public StateAttribute
+{
+    public:
+
+        FragmentProgram();
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        FragmentProgram(const FragmentProgram& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        META_StateAttribute(osg, FragmentProgram, FRAGMENTPROGRAM);
+
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const osg::StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macro's below.
+            COMPARE_StateAttribute_Types(FragmentProgram,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_fragmentProgram)
+
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_FRAGMENT_PROGRAM_ARB);
+            return true;
+        }
+
+        // data access methods.
+
+        /** Get the handle to the fragment program id for the current context.*/
+        inline GLuint& getFragmentProgramID(unsigned int contextID) const
+        {
+            return _fragmentProgramIDList[contextID];
+        }
+
+        
+        /** Set the fragment program using a C style string.*/
+        inline void setFragmentProgram( const char* program ) 
+        { 
+            _fragmentProgram = program; 
+            dirtyFragmentProgramObject();
+        }
+    
+        /** Set the fragment program using C++ style string.*/
+        inline void setFragmentProgram( const std::string& program )
+        {
+            _fragmentProgram = program;
+            dirtyFragmentProgramObject();
+        }
+
+        /** Get the fragment program.*/
+        inline const std::string& getFragmentProgram() const { return _fragmentProgram; }
+
+        /** Set Program Parameters */
+        inline void setProgramLocalParameter(const GLuint index, const Vec4& p)
+        {
+            _programLocalParameters[index] = p;
+        }
+
+        typedef std::map<GLuint,Vec4> LocalParamList;
+
+        /** Set list of Program Parameters */
+        inline void setLocalParameters(const LocalParamList& lpl) { _programLocalParameters = lpl; }
+
+        /** Get list of Program Parameters */
+        inline LocalParamList& getLocalParameters() { return _programLocalParameters; }
+
+        /** Get const list of Program Parameters */
+        inline const LocalParamList& getLocalParameters() const { return _programLocalParameters; }
+
+        /** Matrix */
+        inline void setMatrix(const GLenum mode, const Matrix& matrix)
+        {
+            _matrixList[mode] = matrix;
+        }
+
+        typedef std::map<GLenum,Matrix> MatrixList;
+
+        /** Set list of Matrices */
+        inline void setMatrices(const MatrixList& matrices) { _matrixList = matrices; }
+
+        /** Get list of Matrices */
+        inline MatrixList& getMatrices() { return _matrixList; }
+
+        /** Get list of Matrices */
+        inline const MatrixList& getMatrices() const { return _matrixList; }
+
+
+        /** Force a recompile on next apply() of associated OpenGL vertex program objects.*/
+        void dirtyFragmentProgramObject();        
+
+        /** use deleteFragmentProgramObject instead of glDeletePrograms to allow
+          * OpenGL Fragment Program objects to be cached until they can be deleted
+          * by the OpenGL context in which they were created, specified
+          * by contextID.*/
+        static void deleteFragmentProgramObject(unsigned int contextID,GLuint handle);
+
+        /** flush all the cached fragment programs which need to be deleted
+          * in the OpenGL context related to contextID.*/
+        static void flushDeletedFragmentProgramObjects(unsigned int contextID,double currentTime, double& availableTime);
+
+        /** discard all the cached fragment programs which need to be deleted
+          * in the OpenGL context related to contextID.
+          * Note, unlike flush no OpenGL calls are made, instead the handles are all removed.
+          * this call is useful for when an OpenGL context has been destroyed. */
+        static void discardDeletedFragmentProgramObjects(unsigned int contextID);
+
+        virtual void apply(State& state) const;
+
+        virtual void compileGLObjects(State& state) const { apply(state); }
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int maxSize);
+
+        /** release an OpenGL objects in specified graphics context if State
+            object is passed, otherwise release OpenGL objects for all graphics context if
+            State object pointer == NULL.*/
+        virtual void releaseGLObjects(State* state=0) const;
+
+        /** Extensions class which encapsulates the querying of extensions and
+          * associated function pointers, and provide convenience wrappers to 
+          * check for the extensions or use the associated functions.*/        
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setFragmentProgramSupported(bool flag) { _isFragmentProgramSupported=flag; }
+                bool isFragmentProgramSupported() const { return _isFragmentProgramSupported; }
+
+                void glBindProgram(GLenum target, GLuint id) const;
+                void glGenPrograms(GLsizei n, GLuint *programs) const;
+                void glDeletePrograms(GLsizei n, GLuint *programs) const;
+                void glProgramString(GLenum target, GLenum format, GLsizei len, const void *string) const; 
+                void glProgramLocalParameter4fv(GLenum target, GLuint index, const GLfloat *params) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool _isFragmentProgramSupported;
+                
+                typedef void (APIENTRY * BindProgramProc) (GLenum target, GLuint id);
+                typedef void (APIENTRY * GenProgramsProc) (GLsizei n, GLuint *programs);
+                typedef void (APIENTRY * DeleteProgramsProc) (GLsizei n, GLuint *programs);
+                typedef void (APIENTRY * ProgramStringProc) (GLenum target, GLenum format, GLsizei len, const void *string); 
+                typedef void (APIENTRY * ProgramLocalParameter4fvProc) (GLenum target, GLuint index, const GLfloat *params);
+
+                BindProgramProc _glBindProgram;
+                GenProgramsProc _glGenPrograms;
+                DeleteProgramsProc _glDeletePrograms;
+                ProgramStringProc _glProgramString;
+                ProgramLocalParameter4fvProc _glProgramLocalParameter4fv;
+         };
+        
+        /** Function to call to get the extension of a specified context.
+          * If the Extension object for that context has not yet been created and the 
+          * 'createIfNotInitalized' flag has been set to false then returns NULL.
+          * If 'createIfNotInitalized' is true then the Extensions object is 
+          * automatically created.  However, in this case the extension object will
+          * only be created with the graphics context associated with ContextID..*/
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** setExtensions allows users to override the extensions across graphics contexts.
+          * typically used when you have different extensions supported across graphics pipes
+          * but need to ensure that they all use the same low common denominator extensions.*/
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+    protected:
+
+
+        virtual ~FragmentProgram();
+
+        typedef buffered_value<GLuint> FragmentProgramIDList;
+        mutable FragmentProgramIDList _fragmentProgramIDList;
+
+        std::string     _fragmentProgram;
+
+        LocalParamList  _programLocalParameters;
+        MatrixList      _matrixList;
+};
+
+
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Endian
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Endian (revision 10411)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Endian (revision 10411)
@@ -0,0 +1,85 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_ENDIAN
+#define OSG_ENDIAN 1
+
+#include <algorithm>
+
+namespace osg {
+
+enum Endian
+{
+    BigEndian,
+    LittleEndian
+};
+
+inline Endian getCpuByteOrder()
+{
+    union {
+        char big_endian_1[2];
+        short is_it_really_1;
+    } u;
+    u.big_endian_1[0] = 0;
+    u.big_endian_1[1] = 1;
+
+    if (u.is_it_really_1 == 1)
+        return BigEndian;
+    else 
+        return LittleEndian;
+} 
+
+inline void swapBytes( char* in, unsigned int size )
+{
+    char* start = in;
+    char* end = start+size-1;
+    while (start<end)
+    {
+        std::swap(*start++,*end--);
+    }
+}
+
+inline void swapBytes2( char* in )
+{
+    std::swap(in[0],in[1]);
+}
+
+inline void swapBytes4( char* in )
+{
+    std::swap(in[0],in[3]);
+    std::swap(in[1],in[2]);
+}
+
+inline void swapBytes8( char* in )
+{
+    std::swap(in[0],in[7]);
+    std::swap(in[1],in[6]);
+    std::swap(in[2],in[5]);
+    std::swap(in[3],in[4]);
+}
+
+inline void swapBytes16( char* in )
+{
+    std::swap(in[0],in[15]);
+    std::swap(in[1],in[14]);
+    std::swap(in[2],in[13]);
+    std::swap(in[3],in[12]);
+    std::swap(in[4],in[11]);
+    std::swap(in[5],in[10]);
+    std::swap(in[6],in[9]);
+    std::swap(in[7],in[8]);
+}
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameStamp
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameStamp (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/FrameStamp (revision 7648)
@@ -0,0 +1,91 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_FRAMESTAMP
+#define OSG_FRAMESTAMP 1
+
+#include <osg/Referenced>
+
+#if defined(__sgi) || (defined(WIN32) && !defined(__MWERKS__))
+#include <time.h>
+#else
+#include <ctime>
+using std::tm;
+#endif
+
+namespace osg
+{
+
+/** Class which encapsulates the frame number, reference time and calendar
+  * time of specific frame, used to synchronize operations on the scene graph
+  * and other machines when using a graphics cluster.  Note the calendar
+  * time can be an artificial simulation time or capture the real time
+  * of day etc.*/ 
+class OSG_EXPORT FrameStamp : public Referenced
+{
+    public:
+
+        FrameStamp();
+        FrameStamp(const FrameStamp& fs);
+        
+        FrameStamp& operator = (const FrameStamp& fs);
+        
+        void setFrameNumber(int fnum) { _frameNumber = fnum; }
+        int getFrameNumber() const { return _frameNumber; }
+        
+        void setReferenceTime(double refTime) { _referenceTime = refTime; }
+        double getReferenceTime() const { return _referenceTime; }
+        
+        void setSimulationTime(double refTime) { _simulationTime = refTime; }
+        double getSimulationTime() const { return _simulationTime; }
+        
+        void setCalendarTime(const tm& calendarTime);
+        void getCalendarTime(tm& calendarTime) const;
+
+        // keep public to allow it to be permit allocation which is 
+        // not on the heap used osgcluster
+        virtual ~FrameStamp();
+
+    protected:
+    
+
+        // note no dynamic memory is used so that data can be passed
+        // via a simple memory copy or within a data packet across
+        // the network.
+    
+        int     _frameNumber;
+        double  _referenceTime;
+        double  _simulationTime;        
+        
+        // member variables of time.h's tm structure, copied here to
+        // ensure that all data is not dynamic. The tm structure itself
+        // is not completely consistent between implementations, which
+        // could be a problem when sending the FrameStamp across a network
+        // with different versions of tm (i.e mixing Unix and Windows.)
+        int tm_sec;            /* Seconds.        [0-60] (1 leap second) */
+        int tm_min;            /* Minutes.        [0-59] */
+        int tm_hour;           /* Hours.          [0-23] */
+        int tm_mday;           /* Day.            [1-31] */
+        int tm_mon;            /* Month.          [0-11] */
+        int tm_year;           /* Year            - 1900.  */
+        int tm_wday;           /* Day of week.    [0-6] */
+        int tm_yday;           /* Days in year.   [0-365]    */
+        int tm_isdst;           /* DST.           [-1/0/1]*/
+        
+        
+};
+
+}
+
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShapeDrawable
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShapeDrawable (revision 8767)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ShapeDrawable (revision 8767)
@@ -0,0 +1,201 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
+ *
+ * This library is open source and may be redistributed and/or modified under
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_SHAPEDRAWABLE
+#define OSG_SHAPEDRAWABLE 1
+
+#include <osg/Drawable>
+#include <osg/Vec2>
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/Array>
+#include <osg/PrimitiveSet>
+
+namespace osg {
+
+/** Describe several hints that can be passed to a Tessellator (like the one used
+ *  by \c ShapeDrawable) as a mean to try to influence the way it works.
+ */
+class TessellationHints : public Object
+{
+    public:
+
+    TessellationHints():
+        _TessellationMode(USE_SHAPE_DEFAULTS),
+        _detailRatio(1.0f),
+        _targetNumFaces(100),
+        _createFrontFace(true),
+        _createBackFace(false),
+        _createNormals(true),
+        _createTextureCoords(false),
+        _createTop(true),
+        _createBody(true),
+        _createBottom(true) {}
+
+
+    TessellationHints(const TessellationHints& tess, const CopyOp& copyop=CopyOp::SHALLOW_COPY): 
+            Object(tess,copyop),
+        _TessellationMode(tess._TessellationMode),
+            _detailRatio(tess._detailRatio),
+        _targetNumFaces(tess._targetNumFaces),
+        _createFrontFace(tess._createFrontFace),
+        _createBackFace(tess._createBackFace),
+        _createNormals(tess._createNormals),
+        _createTextureCoords(tess._createTextureCoords),
+        _createTop(tess._createTop),
+        _createBody(tess._createBody),
+        _createBottom(tess._createBottom) {}
+
+        META_Object(osg,TessellationHints);
+
+
+        enum TessellationMode
+        {
+            USE_SHAPE_DEFAULTS,
+            USE_TARGET_NUM_FACES
+        };
+
+        inline void setTessellationMode(TessellationMode mode) { _TessellationMode=mode; }
+        inline TessellationMode getTessellationMode() const { return _TessellationMode; }
+
+        inline void setDetailRatio(float ratio) { _detailRatio = ratio; }
+        inline float getDetailRatio() const { return _detailRatio; }
+
+        inline void setTargetNumFaces(unsigned int target) { _targetNumFaces=target; }
+        inline unsigned int getTargetNumFaces() const { return _targetNumFaces; }
+
+        inline void setCreateFrontFace(bool on) { _createFrontFace=on; }
+        inline bool getCreateFrontFace() const { return _createFrontFace; }
+
+        inline void setCreateBackFace(bool on) { _createBackFace=on; }
+        inline bool getCreateBackFace() const { return _createBackFace; }
+
+        inline void setCreateNormals(bool on) { _createNormals=on; }
+        inline bool getCreateNormals() const { return _createNormals; }
+
+        inline void setCreateTextureCoords(bool on) { _createTextureCoords=on; }
+        inline bool getCreateTextureCoords() const { return _createTextureCoords; }
+
+        inline void setCreateTop(bool on) { _createTop=on; }
+        inline bool getCreateTop() const { return _createTop; }
+
+        inline void setCreateBody(bool on) { _createBody=on; }
+        inline bool getCreateBody() const { return _createBody; }
+
+        inline void setCreateBottom(bool on) { _createBottom=on; }
+        inline bool getCreateBottom() const { return _createBottom; }
+
+    protected:
+
+        ~TessellationHints() {}
+
+
+        TessellationMode _TessellationMode;
+
+        float           _detailRatio;
+        unsigned int     _targetNumFaces;
+
+        bool             _createFrontFace;
+        bool             _createBackFace;
+        bool             _createNormals;
+        bool             _createTextureCoords;
+
+        bool             _createTop;
+        bool             _createBody;
+        bool             _createBottom;
+
+};
+
+
+/** Allow the use of <tt>Shape</tt>s as <tt>Drawable</tt>s, so that they can
+ *  be rendered with reduced effort. The implementation of \c ShapeDrawable is
+ *  not geared to efficiency; it's better to think of it as a convenience to
+ *  render <tt>Shape</tt>s easily (perhaps for test or debugging purposes) than
+ *  as the right way to render basic shapes in some efficiency-critical section
+ *  of code.
+ */
+class OSG_EXPORT ShapeDrawable : public Drawable
+{
+    public:
+
+        ShapeDrawable();
+
+        ShapeDrawable(Shape* shape, TessellationHints* hints=0);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        ShapeDrawable(const ShapeDrawable& pg,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        virtual Object* cloneType() const { return new ShapeDrawable(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new ShapeDrawable(*this,copyop); }
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const ShapeDrawable*>(obj)!=NULL; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "ShapeDrawable"; }
+
+        /** Set the color of the shape.*/
+        void setColor(const Vec4& color);
+
+        /** Get the color of the shape.*/
+        const Vec4& getColor() const { return _color; }
+
+        void setTessellationHints(TessellationHints* hints);
+
+        TessellationHints* getTessellationHints() { return _tessellationHints.get(); }
+        const TessellationHints* getTessellationHints() const { return _tessellationHints.get(); }
+
+
+
+        /** Draw ShapeDrawable directly ignoring an OpenGL display list which
+          * could be attached.  This is the internal draw method which does the
+          * drawing itself, and is the method to override when deriving from
+          * ShapeDrawable for user-drawn objects.
+        */
+        virtual void drawImplementation(RenderInfo& renderInfo) const;
+
+        /* Not all virtual overloads of these methods are overridden in this class, so
+           bring the base class implementation in to avoid hiding the non-used ones. */
+        using Drawable::supports;
+        using Drawable::accept;
+
+        /** Return false, osg::ShapeDrawable does not support accept(AttributeFunctor&).*/
+        virtual bool supports(const AttributeFunctor&) const { return false; }
+
+        /** Return true, osg::ShapeDrawable does support accept(Drawable::ConstAttributeFunctor&).*/
+        virtual bool supports(const Drawable::ConstAttributeFunctor&) const { return true; }
+
+        /** Accept a Drawable::ConstAttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has.*/
+        virtual void accept(Drawable::ConstAttributeFunctor& af) const;
+
+        /** Return true, osg::ShapeDrawable does support accept(PrimitiveFunctor&) .*/
+        virtual bool supports(const PrimitiveFunctor&) const { return true; }
+
+        /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has.*/
+        virtual void accept(PrimitiveFunctor& pf) const;
+
+        virtual BoundingBox computeBound() const;
+
+    protected:
+
+        ShapeDrawable& operator = (const ShapeDrawable&) { return *this;}
+
+        virtual ~ShapeDrawable();
+
+        Vec4 _color;
+
+        ref_ptr<TessellationHints> _tessellationHints;
+
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeCallback
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeCallback (revision 5829)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/NodeCallback (revision 5829)
@@ -0,0 +1,98 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_NODECALLBACK
+#define OSG_NODECALLBACK 1
+
+#include <osg/Object>
+#include <osg/ref_ptr>
+
+namespace osg {
+
+class Node;
+class NodeVisitor;
+
+class OSG_EXPORT NodeCallback : public virtual Object {
+
+    public :
+    
+
+        NodeCallback(){}
+
+        NodeCallback(const NodeCallback& nc,const CopyOp&):
+            _nestedCallback(nc._nestedCallback) {}
+
+        
+        META_Object(osg,NodeCallback);
+        
+        
+        /** Callback method called by the NodeVisitor when visiting a node.*/
+        virtual void operator()(Node* node, NodeVisitor* nv)
+        { 
+            // note, callback is responsible for scenegraph traversal so
+            // they must call traverse(node,nv) to ensure that the
+            // scene graph subtree (and associated callbacks) are traversed.
+            traverse(node,nv);
+        }
+        
+        /** Call any nested callbacks and then traverse the scene graph. */
+        void traverse(Node* node,NodeVisitor* nv);
+        
+        void setNestedCallback(NodeCallback* nc) { _nestedCallback = nc; }
+        NodeCallback* getNestedCallback() { return _nestedCallback.get(); }
+        const NodeCallback* getNestedCallback() const { return _nestedCallback.get(); }
+        
+        inline void addNestedCallback(NodeCallback* nc)
+        {
+            if (nc)
+            {
+                if (_nestedCallback.valid())
+                {
+                    nc->addNestedCallback(_nestedCallback.get());
+                    _nestedCallback = nc;
+                }
+                else
+                {
+                    _nestedCallback = nc;
+                }
+            }
+        }
+        
+        inline void removeNestedCallback(NodeCallback* nc)
+        {
+            if (nc)
+            {
+                if (_nestedCallback==nc)
+                {
+                    _nestedCallback = _nestedCallback->getNestedCallback();
+                }
+                else if (_nestedCallback.valid())
+                {
+                    _nestedCallback->removeNestedCallback(nc);
+                }
+            }
+        }
+        
+    public:
+
+        ref_ptr<NodeCallback> _nestedCallback;
+        
+    protected:
+    
+        virtual ~NodeCallback() {}
+};
+
+} // namespace
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/StateAttribute
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/StateAttribute (revision 9599)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/StateAttribute (revision 9599)
@@ -0,0 +1,352 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_STATEATTRIBUTE
+#define OSG_STATEATTRIBUTE 1
+
+#include <osg/Export>
+#include <osg/Object>
+#include <osg/GL>
+
+#include <typeinfo>
+#include <utility>
+#include <vector>
+
+// define for the GL_EXT_secondary_color extension, GL_COLOR_SUM is OpenGL
+// mode to be used to enable and disable the second color.
+#ifndef GL_COLOR_SUM
+#define GL_COLOR_SUM    0x8458
+#endif
+
+namespace osg {
+
+
+// forward declare NodeVisitor, State & StateSet
+class NodeVisitor;
+class State;
+class StateSet;
+class Texture;
+
+/** META_StateAttribute macro define the standard clone, isSameKindAs,
+  * className and getType methods.
+  * Use when subclassing from Object to make it more convenient to define 
+  * the standard pure virtual methods which are required for all Object 
+  * subclasses.*/
+#define META_StateAttribute(library,name,type) \
+        virtual osg::Object* cloneType() const { return new name(); } \
+        virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \
+        virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const name *>(obj)!=NULL; } \
+        virtual const char* libraryName() const { return #library; } \
+        virtual const char* className() const { return #name; } \
+        virtual Type getType() const { return type; }
+
+/** COMPARE_StateAttribute_Types macro is a helper for implementing the StateAtribute::compare(..) method.*/
+#define COMPARE_StateAttribute_Types(TYPE,rhs_attribute) \
+            if (this==&rhs_attribute) return 0;\
+            const std::type_info* type_lhs = &typeid(*this);\
+            const std::type_info* type_rhs = &typeid(rhs_attribute);\
+            if (type_lhs->before(*type_rhs)) return -1;\
+            if (*type_lhs != *type_rhs) return 1;\
+            const TYPE& rhs = static_cast<const TYPE&>(rhs_attribute);
+
+
+/** COMPARE_StateAttribute_Parameter macro is a helper for implementing the StatateAtribute::compare(..) method.
+  * Macro assumes that variable rhs has been correctly defined by preceding code
+  * macro.*/
+#define COMPARE_StateAttribute_Parameter(parameter) \
+        if (parameter<rhs.parameter) return -1; \
+        if (rhs.parameter<parameter) return 1;
+
+
+/** Base class for state attributes.
+*/     
+class OSG_EXPORT StateAttribute : public Object
+{
+    public :
+    
+        /** GLMode is the value used in glEnable/glDisable(mode) */
+        typedef GLenum          GLMode;
+        /** GLModeValue is used to specify whether a mode is enabled (ON) or disabled (OFF).
+          * GLMoveValue is also used to specify the override behavior of modes from parent to children. 
+          * See enum Value description for more details.*/
+        typedef unsigned int    GLModeValue;
+        /** Override is used to specify the override behavior of StateAttributes
+          * from parent to children. 
+          * See enum Value description for more details.*/
+        typedef unsigned int    OverrideValue;
+
+        /** list values which can be used to set either GLModeValues or OverrideValues.
+          * When using in conjunction with GLModeValues, all Values have meaning. 
+          * When using in conjunction with StateAttribute OverrideValue only 
+          * OFF,OVERRIDE and INHERIT are meaningful.
+          * However, they are useful when using GLModeValue 
+          * and OverrideValue in conjunction with each other as when using
+          * StateSet::setAttributeAndModes(..).*/
+        enum Values
+        {
+            /** means that associated GLMode and Override is disabled.*/
+            OFF          = 0x0,
+            /** means that associated GLMode is enabled and Override is disabled.*/
+            ON           = 0x1,
+            /** Overriding of GLMode's or StateAttributes is enabled, so that state below it is overridden.*/
+            OVERRIDE     = 0x2,
+            /** Protecting of GLMode's or StateAttributes is enabled, so that state from above cannot override this and below state.*/
+            PROTECTED    = 0x4,            
+            /** means that GLMode or StateAttribute should be inherited from above.*/
+            INHERIT      = 0x8
+        };
+        
+        /** Type identifier to differentiate between different state types. */
+        // typedef unsigned int Type;
+
+        /** Values of StateAttribute::Type used to aid identification
+          * of different StateAttribute subclasses. Each subclass defines
+          * its own value in the virtual Type getType() method.  When 
+          * extending the osg's StateAttribute's simply define your
+          * own Type value which is unique, using the StateAttribute::Type
+          * enum as a guide of what values to use.  If your new subclass
+          * needs to override a standard StateAttriubte then simply use 
+          * that type's value. */
+        enum Type
+        {
+            TEXTURE,
+            
+            POLYGONMODE,
+            POLYGONOFFSET,
+            MATERIAL,
+            ALPHAFUNC,
+            ANTIALIAS,
+            COLORTABLE,
+            CULLFACE,
+            FOG,
+            FRONTFACE,
+            
+            LIGHT,
+
+            POINT,
+            LINEWIDTH,
+            LINESTIPPLE,
+            POLYGONSTIPPLE,
+            SHADEMODEL,
+            TEXENV,
+            TEXENVFILTER,
+            TEXGEN,
+            TEXMAT,
+            LIGHTMODEL,
+            BLENDFUNC,
+            BLENDEQUATION,
+            LOGICOP,
+            STENCIL,
+            COLORMASK,
+            DEPTH,
+            VIEWPORT,
+            SCISSOR,
+            BLENDCOLOR,
+            MULTISAMPLE,
+            CLIPPLANE,
+            COLORMATRIX,
+            VERTEXPROGRAM,
+            FRAGMENTPROGRAM,
+            POINTSPRITE,
+            PROGRAM,
+            CLAMPCOLOR,
+            HINT,
+
+            /// osgFX namespace
+            VALIDATOR,
+            VIEWMATRIXEXTRACTOR,
+            
+            /// osgNV namespace
+            OSGNV_PARAMETER_BLOCK,
+
+            // osgNVExt namespace
+            OSGNVEXT_TEXTURE_SHADER,
+            OSGNVEXT_VERTEX_PROGRAM,
+            OSGNVEXT_REGISTER_COMBINERS,
+
+            /// osgNVCg namespace
+            OSGNVCG_PROGRAM,
+
+            // osgNVSlang namespace
+            OSGNVSLANG_PROGRAM,
+
+            // osgNVParse
+            OSGNVPARSE_PROGRAM_PARSER
+        };
+        
+        /** Simple pairing between an attribute type and the member within that attribute type group.*/
+        typedef std::pair<Type,unsigned int> TypeMemberPair;
+
+        StateAttribute();
+        
+        StateAttribute(const StateAttribute& sa,const CopyOp& copyop=CopyOp::SHALLOW_COPY): 
+            Object(sa,copyop) {}
+        
+
+        /** Clone the type of an attribute, with Object* return type.
+            Must be defined by derived classes.*/
+        virtual Object* cloneType() const = 0;
+
+        /** Clone an attribute, with Object* return type.
+            Must be defined by derived classes.*/
+        virtual Object* clone(const CopyOp&) const = 0;
+
+        /** Return true if this and obj are of the same kind of object.*/
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const StateAttribute*>(obj)!=NULL; }
+
+        /** Return the name of the attribute's library.*/
+        virtual const char* libraryName() const { return "osg"; }
+
+        /** Return the name of the attribute's class type.*/
+        virtual const char* className() const { return "StateAttribute"; }
+        
+        
+        /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/
+        virtual Texture* asTexture() { return 0; }
+        
+        /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/
+        virtual const Texture* asTexture() const { return 0; }
+
+        
+        /** Return the Type identifier of the attribute's class type.*/
+        virtual Type getType() const = 0;
+
+        /** Return the member identifier within the attribute's class type. Used for light number/clip plane number etc.*/
+        virtual unsigned int getMember() const { return 0; }
+
+        /** Return the TypeMemberPair that uniquely identifies this type member.*/
+        inline TypeMemberPair getTypeMemberPair() const { return TypeMemberPair(getType(),getMember()); }
+
+        /** Return true if StateAttribute is a type which controls texturing and needs to be issued w.r.t to specific texture unit.*/
+        virtual bool isTextureAttribute() const { return false; }
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const = 0;
+        
+        bool operator <  (const StateAttribute& rhs) const { return compare(rhs)<0; }
+        bool operator == (const StateAttribute& rhs) const { return compare(rhs)==0; }
+        bool operator != (const StateAttribute& rhs) const { return compare(rhs)!=0; }
+
+        
+        /** A vector of osg::StateSet pointers which is used to store the parent(s) of this StateAttribute.*/
+        typedef std::vector<StateSet*> ParentList;
+
+        /** Get the parent list of this StateAttribute. */
+        inline const ParentList& getParents() const { return _parents; }
+
+        inline StateSet* getParent(unsigned int i)  { return _parents[i]; }
+        /**
+         * Get a single const parent of this StateAttribute.
+         * @param i index of the parent to get.
+         * @return the parent i.
+         */
+        inline const StateSet* getParent(unsigned int i) const  { return _parents[i]; }
+
+        /**
+         * Get the number of parents of this StateAttribute.
+         * @return the number of parents of this StateAttribute.
+         */
+        inline unsigned int getNumParents() const { return static_cast<unsigned int>(_parents.size()); }
+
+
+        struct ModeUsage
+        {
+            virtual ~ModeUsage() {}
+            virtual void usesMode(GLMode mode) = 0;
+            virtual void usesTextureMode(GLMode mode) = 0;
+        };
+
+        /** Return the modes associated with this StateAttribute.*/        
+        virtual bool getModeUsage(ModeUsage&) const
+        {
+            // default to no GLMode's associated with use of the StateAttribute.
+            return false;
+        }
+        
+        /** Check the modes associated with this StateAttribute are supported by current OpenGL drivers,
+          * and if not set the associated mode in osg::State to be black listed/invalid.
+          * Return true if all associated modes are valid.*/
+        virtual bool checkValidityOfAssociatedModes(osg::State&) const
+        {
+            // default to no black listed GLMode's associated with use of the StateAttribute.
+            return true;
+        }
+        
+        struct Callback : public virtual osg::Object
+        {
+            Callback() {}
+
+            Callback(const Callback&,const CopyOp&) {}
+
+            META_Object(osg,Callback);
+
+            /** do customized update code.*/
+            virtual void operator () (StateAttribute*, NodeVisitor*) {}
+        };
+
+        /** Set the UpdateCallback which allows users to attach customize the updating of an object during the update traversal.*/
+        void setUpdateCallback(Callback* uc);
+
+        /** Get the non const UpdateCallback.*/
+        Callback* getUpdateCallback() { return _updateCallback.get(); }
+
+        /** Get the const UpdateCallback.*/
+        const Callback* getUpdateCallback() const { return _updateCallback.get(); }
+
+
+        /** Set the EventCallback which allows users to attach customize the updating of an object during the Event traversal.*/
+        void setEventCallback(Callback* ec);
+
+        /** Get the non const EventCallback.*/
+        Callback* getEventCallback() { return _eventCallback.get(); }
+
+        /** Get the const EventCallback.*/
+        const Callback* getEventCallback() const { return _eventCallback.get(); }
+
+    
+        /** apply the OpenGL state attributes. 
+          * The render info for the current OpenGL context is passed
+          * in to allow the StateAttribute to obtain details on the
+          * the current context and state.
+          */
+        virtual void apply(State&) const {}
+
+        /** Default to nothing to compile - all state is applied immediately. */
+        virtual void compileGLObjects(State&) const {}
+
+        /** Resize any per context GLObject buffers to specified size. */
+        virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {}
+
+        /** Release OpenGL objects in specified graphics context if State
+            object is passed, otherwise release OpenGL objects for all graphics context if
+            State object pointer NULL.*/
+        virtual void releaseGLObjects(State* =0) const {}
+
+
+    protected:
+    
+        virtual ~StateAttribute() {}
+
+        void addParent(osg::StateSet* object);
+        void removeParent(osg::StateSet* object);
+
+        ParentList _parents;
+        friend class osg::StateSet;
+
+        ref_ptr<Callback>   _updateCallback;
+        ref_ptr<Callback>   _eventCallback;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Depth
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Depth (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Depth (revision 7648)
@@ -0,0 +1,112 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_DEPTH
+#define OSG_DEPTH 1
+
+#include <osg/StateAttribute>
+
+namespace osg {
+
+/** Encapsulate OpenGL glDepthFunc/Mask/Range functions.
+*/     
+class OSG_EXPORT Depth : public StateAttribute
+{
+    public :
+    
+    
+        enum Function
+        {
+            NEVER = GL_NEVER,
+            LESS = GL_LESS,
+            EQUAL = GL_EQUAL,
+            LEQUAL = GL_LEQUAL,
+            GREATER = GL_GREATER,
+            NOTEQUAL = GL_NOTEQUAL,
+            GEQUAL = GL_GEQUAL,
+            ALWAYS = GL_ALWAYS
+        };
+
+
+        Depth(Function func=LESS,double zNear=0.0, double zFar=1.0,bool writeMask=true);
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Depth(const Depth& dp,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(dp,copyop),
+            _func(dp._func),
+            _zNear(dp._zNear),
+            _zFar(dp._zFar),
+            _depthWriteMask(dp._depthWriteMask) {}
+        
+        
+        META_StateAttribute(osg, Depth, DEPTH);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Parameter macro's below.
+            COMPARE_StateAttribute_Types(Depth,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_func)
+            COMPARE_StateAttribute_Parameter(_depthWriteMask)
+            COMPARE_StateAttribute_Parameter(_zNear)
+            COMPARE_StateAttribute_Parameter(_zFar)
+
+            return 0; // passed all the above comparison macro's, must be equal.
+        }
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
+        {
+            usage.usesMode(GL_DEPTH_TEST);
+            return true;
+        }
+
+        inline void setFunction(Function func) { _func = func; }        
+        inline Function getFunction() const { return _func; }
+               
+
+        inline void setRange(double zNear, double zFar)
+        {
+            _zNear = zNear;
+            _zFar = zFar;
+        }
+
+        inline void setZNear(double zNear) { _zNear=zNear; }
+        inline double getZNear() const { return _zNear; }
+    
+        inline void setZFar(double zFar) { _zFar=zFar; }
+        inline double getZFar() const { return _zFar; }
+
+        inline void setWriteMask(bool mask) { _depthWriteMask = mask; }        
+        inline bool getWriteMask() const { return _depthWriteMask; }
+
+
+        virtual void apply(State& state) const;
+
+    protected:
+    
+        virtual ~Depth();
+
+        Function            _func;
+        
+        double              _zNear;
+        double              _zFar;
+
+        bool                _depthWriteMask;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ComputeBoundsVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ComputeBoundsVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/ComputeBoundsVisitor (revision 9377)
@@ -0,0 +1,61 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_COMPUTEBOUNDSVISITOR
+#define OSG_COMPUTEBOUNDSVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/BoundingBox>
+#include <osg/Polytope>
+
+namespace osg {
+
+class OSG_EXPORT ComputeBoundsVisitor : public osg::NodeVisitor
+{
+public:
+
+    ComputeBoundsVisitor(TraversalMode traversalMode = TRAVERSE_ALL_CHILDREN);
+    
+    META_NodeVisitor("osg","ComputeBoundsVisitor")
+
+    virtual void reset();
+    
+    osg::BoundingBox& getBoundingBox() { return _bb; }
+
+    void getPolytope(osg::Polytope& polytope, float margin=0.1) const;
+        
+    void getBase(osg::Polytope& polytope, float margin=0.1) const;
+    
+    void apply(osg::Node& node);
+    
+    void apply(osg::Transform& transform);
+    
+    void apply(osg::Geode& geode);
+    
+    inline void pushMatrix(osg::Matrix& matrix) { _matrixStack.push_back(matrix); }
+    
+    inline void popMatrix() { _matrixStack.pop_back(); }
+
+    void applyDrawable(osg::Drawable* drawable);
+    
+protected:
+    
+    typedef std::vector<osg::Matrix> MatrixStack;
+
+    MatrixStack         _matrixStack;
+    osg::BoundingBox    _bb;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexEnv
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexEnv (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/TexEnv (revision 5328)
@@ -0,0 +1,88 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_TEXENV
+#define OSG_TEXENV 1
+
+#include <osg/GL>
+#include <osg/StateAttribute>
+#include <osg/Vec4>
+
+namespace osg {
+
+/** TexEnv encapsulates the OpenGL glTexEnv (texture environment) state.
+*/
+class OSG_EXPORT TexEnv : public StateAttribute
+{
+    public :
+
+        enum Mode {
+            DECAL     = GL_DECAL,
+            MODULATE  = GL_MODULATE,
+            BLEND     = GL_BLEND,
+            REPLACE   = GL_REPLACE,
+            ADD       = GL_ADD
+        };
+
+        TexEnv(Mode mode=MODULATE);
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        TexEnv(const TexEnv& texenv,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(texenv,copyop),
+            _mode(texenv._mode),
+            _color(texenv._color) {}
+
+
+        META_StateAttribute(osg, TexEnv, TEXENV);
+
+        virtual bool isTextureAttribute() const { return true; }
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // Check for equal types, then create the rhs variable
+            // used by the COMPARE_StateAttribute_Paramter macros below.
+            COMPARE_StateAttribute_Types(TexEnv,sa)
+
+            // Compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_mode)
+            COMPARE_StateAttribute_Parameter(_color)
+
+            return 0; // Passed all the above comparison macros, so must be equal.
+        }
+
+
+        void setMode( Mode mode ) { _mode = mode; }
+        
+        Mode getMode() const { return _mode; }
+        
+        void setColor( const Vec4& color ) { _color = color; }
+        
+        Vec4& getColor() { return _color; }
+
+        const Vec4& getColor() const { return _color; }
+
+
+        virtual void apply(State& state) const;
+
+    protected :
+
+        virtual ~TexEnv( void );
+
+        Mode        _mode;
+        osg::Vec4   _color;
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CollectOccludersVisitor
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CollectOccludersVisitor (revision 9377)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CollectOccludersVisitor (revision 9377)
@@ -0,0 +1,109 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_COLLECTOCCLUDERSVISITOR
+#define OSG_COLLECTOCCLUDERSVISITOR 1
+
+#include <osg/NodeVisitor>
+#include <osg/CullStack>
+
+#include <set>
+
+namespace osg {
+
+class OSG_EXPORT CollectOccludersVisitor : public osg::NodeVisitor, public osg::CullStack
+{
+    public:
+
+
+        typedef std::set<ShadowVolumeOccluder> ShadowVolumeOccluderSet;
+
+        CollectOccludersVisitor();
+        virtual ~CollectOccludersVisitor();
+
+        META_NodeVisitor("osg","CollectOccludersVisitor")
+
+        virtual CollectOccludersVisitor* cloneType() const { return new CollectOccludersVisitor(); }
+
+        virtual void reset();
+
+        virtual float getDistanceToEyePoint(const Vec3& pos, bool withLODScale) const;
+        virtual float getDistanceToViewPoint(const Vec3& pos, bool withLODScale) const;
+        
+        virtual float getDistanceFromEyePoint(const Vec3& pos, bool withLODScale) const;
+
+        virtual void apply(osg::Node&);
+        virtual void apply(osg::Transform& node);
+        virtual void apply(osg::Projection& node);
+
+        virtual void apply(osg::Switch& node);
+        virtual void apply(osg::LOD& node);
+        virtual void apply(osg::OccluderNode& node);
+
+        /** Sets the minimum shadow occluder volume that an active occluder
+          * must have. vol is units relative the clip space volume where 1.0
+          * is the whole clip space. */
+        void setMinimumShadowOccluderVolume(float vol) { _minimumShadowOccluderVolume = vol; }
+        float getMinimumShadowOccluderVolume() const { return _minimumShadowOccluderVolume; }
+
+        /** Sets the maximum number of occluders to have active for culling
+          * purposes. */
+        void setMaximumNumberOfActiveOccluders(unsigned int num) { _maximumNumberOfActiveOccluders = num; }
+        unsigned int getMaximumNumberOfActiveOccluders() const { return _maximumNumberOfActiveOccluders; }
+
+        void setCreateDrawablesOnOccludeNodes(bool flag) { _createDrawables=flag; }
+        bool getCreateDrawablesOnOccludeNodes() const { return _createDrawables; }
+
+        void setCollectedOccluderSet(const ShadowVolumeOccluderSet& svol) { _occluderSet = svol; }
+        ShadowVolumeOccluderSet& getCollectedOccluderSet() { return _occluderSet; }
+        const ShadowVolumeOccluderSet& getCollectedOccluderSet() const { return _occluderSet; }
+
+        /** Removes occluded occluders for the collected occluders list, then
+          * discards all but MaximumNumberOfActiveOccluders of occluders,
+          * discarding the occluders with the lowest shadow occluder volume. */
+        void removeOccludedOccluders();
+
+
+    protected:
+
+        /** Prevents unwanted copy construction. */
+        //CollectOccludersVisitor(const CollectOccludersVisitor&):osg::NodeVisitor(),osg::CullStack() {}
+
+        /** Prevents unwanted copy operator. */
+        CollectOccludersVisitor& operator = (const CollectOccludersVisitor&) { return *this; }
+        
+        inline void handle_cull_callbacks_and_traverse(osg::Node& node)
+        {
+            /*osg::NodeCallback* callback = node.getCullCallback();
+            if (callback) (*callback)(&node,this);
+            else*/ if (node.getNumChildrenWithOccluderNodes()>0) traverse(node);
+        }
+
+        inline void handle_cull_callbacks_and_accept(osg::Node& node,osg::Node* acceptNode)
+        {
+            /*osg::NodeCallback* callback = node.getCullCallback();
+            if (callback) (*callback)(&node,this);
+            else*/ if (node.getNumChildrenWithOccluderNodes()>0) acceptNode->accept(*this);
+        }
+
+        float                       _minimumShadowOccluderVolume;
+        unsigned                    _maximumNumberOfActiveOccluders;
+        bool                        _createDrawables;
+        ShadowVolumeOccluderSet     _occluderSet;
+
+};
+
+}
+
+#endif
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Quat
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Quat (revision 5328)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Quat (revision 5328)
@@ -0,0 +1,393 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_QUAT
+#define OSG_QUAT 1
+
+#include <osg/Export>
+#include <osg/Vec3f>
+#include <osg/Vec4f>
+#include <osg/Vec3d>
+#include <osg/Vec4d>
+
+namespace osg {
+
+class Matrixf;
+class Matrixd;
+
+/** A quaternion class. It can be used to represent an orientation in 3D space.*/
+class OSG_EXPORT Quat
+{
+
+    public:
+
+        typedef double value_type;
+
+        value_type  _v[4];    // a four-vector
+
+        inline Quat() { _v[0]=0.0; _v[1]=0.0; _v[2]=0.0; _v[3]=1.0; }
+
+        inline Quat( value_type x, value_type y, value_type z, value_type w )
+        {
+            _v[0]=x;
+            _v[1]=y;
+            _v[2]=z;
+            _v[3]=w;
+        }
+
+        inline Quat( const Vec4f& v )
+        {
+            _v[0]=v.x();
+            _v[1]=v.y();
+            _v[2]=v.z();
+            _v[3]=v.w();
+        }
+
+        inline Quat( const Vec4d& v )
+        {
+            _v[0]=v.x();
+            _v[1]=v.y();
+            _v[2]=v.z();
+            _v[3]=v.w();
+        }
+
+        inline Quat( value_type angle, const Vec3f& axis)
+        {
+            makeRotate(angle,axis);
+        }
+        inline Quat( value_type angle, const Vec3d& axis)
+        {
+            makeRotate(angle,axis);
+        }
+
+        inline Quat( value_type angle1, const Vec3f& axis1, 
+                     value_type angle2, const Vec3f& axis2,
+                     value_type angle3, const Vec3f& axis3)
+        {
+            makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+        }
+
+        inline Quat( value_type angle1, const Vec3d& axis1, 
+                     value_type angle2, const Vec3d& axis2,
+                     value_type angle3, const Vec3d& axis3)
+        {
+            makeRotate(angle1,axis1,angle2,axis2,angle3,axis3);
+        }
+
+        inline Quat& operator = (const Quat& v) { _v[0]=v._v[0];  _v[1]=v._v[1]; _v[2]=v._v[2]; _v[3]=v._v[3]; return *this; }
+
+        inline bool operator == (const Quat& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; }
+
+        inline bool operator != (const Quat& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; }
+
+        inline bool operator <  (const Quat& v) const
+        {
+            if (_v[0]<v._v[0]) return true;
+            else if (_v[0]>v._v[0]) return false;
+            else if (_v[1]<v._v[1]) return true;
+            else if (_v[1]>v._v[1]) return false;
+            else if (_v[2]<v._v[2]) return true;
+            else if (_v[2]>v._v[2]) return false;
+            else return (_v[3]<v._v[3]);
+        }
+
+        /* ----------------------------------
+           Methods to access data members
+        ---------------------------------- */
+
+        inline Vec4d asVec4() const
+        {
+            return Vec4d(_v[0], _v[1], _v[2], _v[3]);
+        }
+
+        inline Vec3d asVec3() const
+        {
+            return Vec3d(_v[0], _v[1], _v[2]);
+        }
+
+        inline void set(value_type x, value_type y, value_type z, value_type w)
+        {
+            _v[0]=x;
+            _v[1]=y;
+            _v[2]=z;
+            _v[3]=w;
+        }
+        
+        inline void set(const osg::Vec4f& v)
+        {
+            _v[0]=v.x();
+            _v[1]=v.y();
+            _v[2]=v.z();
+            _v[3]=v.w();
+        }
+
+        inline void set(const osg::Vec4d& v)
+        {
+            _v[0]=v.x();
+            _v[1]=v.y();
+            _v[2]=v.z();
+            _v[3]=v.w();
+        }
+        
+        void set(const Matrixf& matrix);
+        
+        void set(const Matrixd& matrix);
+        
+        void get(Matrixf& matrix) const;
+
+        void get(Matrixd& matrix) const;
+        
+
+        inline value_type & operator [] (int i) { return _v[i]; }
+        inline value_type   operator [] (int i) const { return _v[i]; }
+
+        inline value_type & x() { return _v[0]; }
+        inline value_type & y() { return _v[1]; }
+        inline value_type & z() { return _v[2]; }
+        inline value_type & w() { return _v[3]; }
+
+        inline value_type x() const { return _v[0]; }
+        inline value_type y() const { return _v[1]; }
+        inline value_type z() const { return _v[2]; }
+        inline value_type w() const { return _v[3]; }
+
+        /** return true if the Quat represents a zero rotation, and therefore can be ignored in computations.*/
+        bool zeroRotation() const { return _v[0]==0.0 && _v[1]==0.0 && _v[2]==0.0 && _v[3]==1.0; } 
+
+
+         /* ------------------------------------------------------------- 
+                   BASIC ARITHMETIC METHODS            
+        Implemented in terms of Vec4s.  Some Vec4 operators, e.g.
+        operator* are not appropriate for quaternions (as
+        mathematical objects) so they are implemented differently.
+        Also define methods for conjugate and the multiplicative inverse.            
+        ------------------------------------------------------------- */
+        /// Multiply by scalar 
+        inline const Quat operator * (value_type rhs) const
+        {
+            return Quat(_v[0]*rhs, _v[1]*rhs, _v[2]*rhs, _v[3]*rhs);
+        }
+
+        /// Unary multiply by scalar 
+        inline Quat& operator *= (value_type rhs)
+        {
+            _v[0]*=rhs;
+            _v[1]*=rhs;
+            _v[2]*=rhs;
+            _v[3]*=rhs;
+            return *this;        // enable nesting
+        }
+
+        /// Binary multiply 
+        inline const Quat operator*(const Quat& rhs) const
+        {
+            return Quat( rhs._v[3]*_v[0] + rhs._v[0]*_v[3] + rhs._v[1]*_v[2] - rhs._v[2]*_v[1],
+                 rhs._v[3]*_v[1] - rhs._v[0]*_v[2] + rhs._v[1]*_v[3] + rhs._v[2]*_v[0],
+                 rhs._v[3]*_v[2] + rhs._v[0]*_v[1] - rhs._v[1]*_v[0] + rhs._v[2]*_v[3],
+                 rhs._v[3]*_v[3] - rhs._v[0]*_v[0] - rhs._v[1]*_v[1] - rhs._v[2]*_v[2] );
+        }
+
+        /// Unary multiply 
+        inline Quat& operator*=(const Quat& rhs)
+        {
+            value_type x = rhs._v[3]*_v[0] + rhs._v[0]*_v[3] + rhs._v[1]*_v[2] - rhs._v[2]*_v[1];
+            value_type y = rhs._v[3]*_v[1] - rhs._v[0]*_v[2] + rhs._v[1]*_v[3] + rhs._v[2]*_v[0];
+            value_type z = rhs._v[3]*_v[2] + rhs._v[0]*_v[1] - rhs._v[1]*_v[0] + rhs._v[2]*_v[3];
+            _v[3]   = rhs._v[3]*_v[3] - rhs._v[0]*_v[0] - rhs._v[1]*_v[1] - rhs._v[2]*_v[2];
+
+            _v[2] = z;
+            _v[1] = y;
+            _v[0] = x;
+
+            return (*this);            // enable nesting
+        }
+
+        /// Divide by scalar 
+        inline Quat operator / (value_type rhs) const
+        {
+            value_type div = 1.0/rhs;
+            return Quat(_v[0]*div, _v[1]*div, _v[2]*div, _v[3]*div);
+        }
+
+        /// Unary divide by scalar 
+        inline Quat& operator /= (value_type rhs)
+        {
+            value_type div = 1.0/rhs;
+            _v[0]*=div;
+            _v[1]*=div;
+            _v[2]*=div;
+            _v[3]*=div;
+            return *this;
+        }
+
+        /// Binary divide 
+        inline const Quat operator/(const Quat& denom) const
+        {
+            return ( (*this) * denom.inverse() );
+        }
+
+        /// Unary divide 
+        inline Quat& operator/=(const Quat& denom)
+        {
+            (*this) = (*this) * denom.inverse();
+            return (*this);            // enable nesting
+        }
+
+        /// Binary addition 
+        inline const Quat operator + (const Quat& rhs) const
+        {
+            return Quat(_v[0]+rhs._v[0], _v[1]+rhs._v[1],
+                _v[2]+rhs._v[2], _v[3]+rhs._v[3]);
+        }
+
+        /// Unary addition
+        inline Quat& operator += (const Quat& rhs)
+        {
+            _v[0] += rhs._v[0];
+            _v[1] += rhs._v[1];
+            _v[2] += rhs._v[2];
+            _v[3] += rhs._v[3];
+            return *this;            // enable nesting
+        }
+
+        /// Binary subtraction 
+        inline const Quat operator - (const Quat& rhs) const
+        {
+            return Quat(_v[0]-rhs._v[0], _v[1]-rhs._v[1],
+                _v[2]-rhs._v[2], _v[3]-rhs._v[3] );
+        }
+
+        /// Unary subtraction 
+        inline Quat& operator -= (const Quat& rhs)
+        {
+            _v[0]-=rhs._v[0];
+            _v[1]-=rhs._v[1];
+            _v[2]-=rhs._v[2];
+            _v[3]-=rhs._v[3];
+            return *this;            // enable nesting
+        }
+
+        /** Negation operator - returns the negative of the quaternion.
+        Basically just calls operator - () on the Vec4 */
+        inline const Quat operator - () const
+        {
+            return Quat (-_v[0], -_v[1], -_v[2], -_v[3]);
+        }
+
+        /// Length of the quaternion = sqrt( vec . vec )
+        value_type length() const
+        {
+            return sqrt( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] + _v[3]*_v[3]);
+        }
+
+        /// Length of the quaternion = vec . vec
+        value_type length2() const
+        {
+            return _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] + _v[3]*_v[3];
+        }
+
+        /// Conjugate 
+        inline Quat conj () const
+        { 
+             return Quat( -_v[0], -_v[1], -_v[2], _v[3] );
+        }
+
+        /// Multiplicative inverse method: q^(-1) = q^*/(q.q^*)
+        inline const Quat inverse () const
+        {
+             return conj() / length2();
+         }
+
+      /* -------------------------------------------------------- 
+               METHODS RELATED TO ROTATIONS
+        Set a quaternion which will perform a rotation of an
+        angle around the axis given by the vector (x,y,z).
+        Should be written to also accept an angle and a Vec3?
+
+        Define Spherical Linear interpolation method also
+
+        Not inlined - see the Quat.cpp file for implementation
+        -------------------------------------------------------- */
+        void makeRotate( value_type  angle, 
+                          value_type  x, value_type  y, value_type  z );
+        void makeRotate ( value_type  angle, const Vec3f& vec );
+        void makeRotate ( value_type  angle, const Vec3d& vec );
+
+        void makeRotate ( value_type  angle1, const Vec3f& axis1, 
+                          value_type  angle2, const Vec3f& axis2,
+                          value_type  angle3, const Vec3f& axis3);
+        void makeRotate ( value_type  angle1, const Vec3d& axis1, 
+                          value_type  angle2, const Vec3d& axis2,
+                          value_type  angle3, const Vec3d& axis3);
+
+        /** Make a rotation Quat which will rotate vec1 to vec2.
+            Generally take a dot product to get the angle between these
+            and then use a cross product to get the rotation axis
+            Watch out for the two special cases when the vectors
+            are co-incident or opposite in direction.*/
+        void makeRotate( const Vec3f& vec1, const Vec3f& vec2 );
+        /** Make a rotation Quat which will rotate vec1 to vec2.
+            Generally take a dot product to get the angle between these
+            and then use a cross product to get the rotation axis
+            Watch out for the two special cases of when the vectors
+            are co-incident or opposite in direction.*/
+        void makeRotate( const Vec3d& vec1, const Vec3d& vec2 );
+    
+        void makeRotate_original( const Vec3d& vec1, const Vec3d& vec2 );
+
+        /** Return the angle and vector components represented by the quaternion.*/
+        void getRotate ( value_type & angle, value_type & x, value_type & y, value_type & z ) const;
+
+        /** Return the angle and vector represented by the quaternion.*/
+        void getRotate ( value_type & angle, Vec3f& vec ) const;
+
+        /** Return the angle and vector represented by the quaternion.*/
+        void getRotate ( value_type & angle, Vec3d& vec ) const;
+
+        /** Spherical Linear Interpolation.
+        As t goes from 0 to 1, the Quat object goes from "from" to "to". */
+        void slerp   ( value_type  t, const Quat& from, const Quat& to);
+               
+        /** Rotate a vector by this quaternion.*/
+        Vec3f operator* (const Vec3f& v) const
+        {
+            // nVidia SDK implementation
+            Vec3f uv, uuv; 
+            Vec3f qvec(_v[0], _v[1], _v[2]);
+            uv = qvec ^ v;
+            uuv = qvec ^ uv; 
+            uv *= ( 2.0f * _v[3] ); 
+            uuv *= 2.0f; 
+            return v + uv + uuv;
+        }
+               
+        /** Rotate a vector by this quaternion.*/
+        Vec3d operator* (const Vec3d& v) const
+        {
+            // nVidia SDK implementation
+            Vec3d uv, uuv; 
+            Vec3d qvec(_v[0], _v[1], _v[2]);
+            uv = qvec ^ v;
+            uuv = qvec ^ uv; 
+            uv *= ( 2.0f * _v[3] ); 
+            uuv *= 2.0f; 
+            return v + uv + uuv;
+        }
+        
+    protected:
+    
+};    // end of class prototype
+
+}    // end of namespace
+
+#endif 
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullSettings
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullSettings (revision 8495)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/CullSettings (revision 8495)
@@ -0,0 +1,269 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_CULLSETTINGS
+#define OSG_CULLSETTINGS 1
+
+#include <iosfwd>
+#include <osg/Matrix>
+#include <osg/ClearNode>
+
+namespace osg {
+
+// forward declare
+class ArgumentParser;
+class ApplicationUsage;
+
+class OSG_EXPORT CullSettings
+{
+    public:
+
+        CullSettings()
+        {
+            setDefaults();
+            readEnvironmentalVariables();
+        }
+
+        CullSettings(ArgumentParser& arguments)
+        {
+            setDefaults();
+            readEnvironmentalVariables();
+            readCommandLine(arguments);
+        }
+
+        CullSettings(const CullSettings& cs);
+
+        virtual ~CullSettings() {}
+        
+        CullSettings& operator = (const CullSettings& settings)
+        {
+            if (this==&settings) return *this;
+            setCullSettings(settings);
+            return *this;
+        }
+
+
+        virtual void setDefaults();
+
+        
+        enum VariablesMask
+        {
+            COMPUTE_NEAR_FAR_MODE                   = 0x0001,
+            CULLING_MODE                            = 0x0002,
+            LOD_SCALE                               = 0x0004,
+            SMALL_FEATURE_CULLING_PIXEL_SIZE        = 0x0008,
+            CLAMP_PROJECTION_MATRIX_CALLBACK        = 0x0010,
+            NEAR_FAR_RATIO                          = 0x0020,
+            IMPOSTOR_ACTIVE                         = 0x0040,
+            DEPTH_SORT_IMPOSTOR_SPRITES             = 0x0080,
+            IMPOSTOR_PIXEL_ERROR_THRESHOLD          = 0x0100,
+            NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES    = 0x0200,
+            CULL_MASK                               = 0x0400,
+            CULL_MASK_LEFT                          = 0x0800,
+            CULL_MASK_RIGHT                         = 0x1000,
+            CLEAR_COLOR                             = 0x2000,
+            LIGHTING_MODE                           = 0x4000,
+            LIGHT                                   = 0x8000,
+            
+            NO_VARIABLES                            = 0x0000,
+            ALL_VARIABLES                           = 0xFFFF
+        };
+
+        /** Set the inheritance mask used in inheritCullSettings to control which variables get overwritten by the passed in CullSettings object.*/
+        void setInheritanceMask(unsigned int mask) { _inheritanceMask = mask; }
+
+        /** Get the inheritance mask used in inheritCullSettings to control which variables get overwritten by the passed in CullSettings object.*/
+        unsigned int getInheritanceMask() const { return _inheritanceMask; }
+        
+        /** Set the local cull settings values from specified CullSettings object.*/
+        void setCullSettings(const CullSettings& settings);
+
+        /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/
+        virtual void inheritCullSettings(const CullSettings& settings) { inheritCullSettings(settings, _inheritanceMask); }
+
+        /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/
+        virtual void inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask);
+
+        /** read the environmental variables.*/
+        void readEnvironmentalVariables();
+
+        /** read the commandline arguments.*/
+        void readCommandLine(ArgumentParser& arguments);
+
+
+        enum InheritanceMaskActionOnAttributeSetting
+        {
+            DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT,
+            DO_NOT_MODIFY_INHERITANCE_MASK
+        };
+        
+        void setInheritanceMaskActionOnAttributeSetting(InheritanceMaskActionOnAttributeSetting action) { _inheritanceMaskActionOnAttributeSetting = action; }
+        InheritanceMaskActionOnAttributeSetting getInheritanceMaskActionOnAttributeSetting() const { return _inheritanceMaskActionOnAttributeSetting; }
+
+        /** Apply the action, specified by the InheritanceMaskActionOnAttributeSetting, to apply to the inheritance bit mask.
+          * This method is called by CullSettings::set*() parameter methods to ensure that CullSettings inheritance mechanisms doesn't overwrite the local parameter settings.*/
+        inline void applyMaskAction(unsigned int maskBit)
+        {
+            if (_inheritanceMaskActionOnAttributeSetting==DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT)
+            {
+                _inheritanceMask = _inheritanceMask & (~maskBit);
+            }
+        }
+
+
+        /** Switch the creation of Impostors on or off.
+          * Setting active to false forces the CullVisitor to use the Impostor
+          * LOD children for rendering. Setting active to true forces the
+          * CullVisitor to create the appropriate pre-rendering stages which
+          * render to the ImpostorSprite's texture.*/
+        void setImpostorsActive(bool active) { _impostorActive = active; applyMaskAction(IMPOSTOR_ACTIVE); }
+
+        /** Get whether impostors are active or not. */
+        bool getImpostorsActive() const { return _impostorActive; }
+
+        /** Set the impostor error threshold.
+          * Used in calculation of whether impostors remain valid.*/
+        void setImpostorPixelErrorThreshold(float numPixels) { _impostorPixelErrorThreshold=numPixels;  applyMaskAction(IMPOSTOR_PIXEL_ERROR_THRESHOLD); }
+
+        /** Get the impostor error threshold.*/
+        float getImpostorPixelErrorThreshold() const { return _impostorPixelErrorThreshold; }
+
+        /** Set whether ImpostorSprite's should be placed in a depth sorted bin for rendering.*/
+        void setDepthSortImpostorSprites(bool doDepthSort) { _depthSortImpostorSprites = doDepthSort; applyMaskAction(DEPTH_SORT_IMPOSTOR_SPRITES); }
+
+        /** Get whether ImpostorSprite's are depth sorted bin for rendering.*/
+        bool getDepthSortImpostorSprites() const { return _depthSortImpostorSprites; }
+
+        /** Set the number of frames that an ImpostorSprite is kept whilst not being beyond,
+          * before being recycled.*/
+        void setNumberOfFrameToKeepImpostorSprites(int numFrames) { _numFramesToKeepImpostorSprites = numFrames; applyMaskAction(NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES); }
+
+        /** Get the number of frames that an ImpostorSprite is kept whilst not being beyond,
+          * before being recycled.*/
+        int getNumberOfFrameToKeepImpostorSprites() const { return _numFramesToKeepImpostorSprites; }
+
+        enum ComputeNearFarMode
+        {
+            DO_NOT_COMPUTE_NEAR_FAR = 0,
+            COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES,
+            COMPUTE_NEAR_FAR_USING_PRIMITIVES
+        };
+
+        void setComputeNearFarMode(ComputeNearFarMode cnfm) { _computeNearFar=cnfm; applyMaskAction(COMPUTE_NEAR_FAR_MODE); } 
+        ComputeNearFarMode getComputeNearFarMode() const { return _computeNearFar;} 
+
+        void setNearFarRatio(double ratio) { _nearFarRatio = ratio; applyMaskAction(NEAR_FAR_RATIO); }
+        double getNearFarRatio() const { return _nearFarRatio; }
+
+        enum CullingModeValues
+        {
+            NO_CULLING                  = 0x0,
+            VIEW_FRUSTUM_SIDES_CULLING  = 0x1,
+            NEAR_PLANE_CULLING          = 0x2,
+            FAR_PLANE_CULLING           = 0x4,
+            VIEW_FRUSTUM_CULLING        = VIEW_FRUSTUM_SIDES_CULLING|
+                                          NEAR_PLANE_CULLING|
+                                          FAR_PLANE_CULLING,
+            SMALL_FEATURE_CULLING       = 0x8,
+            SHADOW_OCCLUSION_CULLING    = 0x10,
+            CLUSTER_CULLING             = 0x20,
+            DEFAULT_CULLING             = VIEW_FRUSTUM_SIDES_CULLING|
+                                          SMALL_FEATURE_CULLING|
+                                          SHADOW_OCCLUSION_CULLING|
+                                          CLUSTER_CULLING,
+            ENABLE_ALL_CULLING          = VIEW_FRUSTUM_CULLING|
+                                          SMALL_FEATURE_CULLING|
+                                          SHADOW_OCCLUSION_CULLING|
+                                          CLUSTER_CULLING
+        };
+        
+        typedef unsigned int CullingMode;
+
+        /** Set the culling mode for the CullVisitor to use.*/
+        void setCullingMode(CullingMode mode) { _cullingMode = mode; applyMaskAction(CULLING_MODE); }
+        
+        /** Returns the current CullingMode.*/
+        CullingMode getCullingMode() const { return _cullingMode; }
+
+
+        void setCullMask(osg::Node::NodeMask nm) { _cullMask = nm; applyMaskAction(CULL_MASK); }
+        osg::Node::NodeMask getCullMask() const { return _cullMask; }
+
+        void setCullMaskLeft(osg::Node::NodeMask nm) { _cullMaskLeft = nm; applyMaskAction(CULL_MASK_LEFT); }
+        osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; }
+
+        void setCullMaskRight(osg::Node::NodeMask nm) { _cullMaskRight = nm; applyMaskAction(CULL_MASK_RIGHT); }
+        osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; }
+
+        /** Set the LOD bias for the CullVisitor to use.*/
+        void setLODScale(float scale) { _LODScale = scale; applyMaskAction(LOD_SCALE); }
+        
+        /** Get the LOD bias.*/
+        float getLODScale() const { return _LODScale; }
+
+        /** Set the Small Feature Culling Pixel Size.*/
+        void setSmallFeatureCullingPixelSize(float value) { _smallFeatureCullingPixelSize=value; applyMaskAction(SMALL_FEATURE_CULLING_PIXEL_SIZE); }
+
+        /** Get the Small Feature Culling Pixel Size.*/
+        float getSmallFeatureCullingPixelSize() const { return _smallFeatureCullingPixelSize; }
+
+
+
+        /** Callback for overriding the CullVisitor's default clamping of the projection matrix to computed near and far values.
+          * Note, both Matrixf and Matrixd versions of clampProjectionMatrixImplementation must be implemented as the CullVisitor
+          * can target either Matrix data type, configured at compile time.*/
+        struct ClampProjectionMatrixCallback : public osg::Referenced
+        {
+            virtual bool clampProjectionMatrixImplementation(osg::Matrixf& projection, double& znear, double& zfar) const = 0;
+            virtual bool clampProjectionMatrixImplementation(osg::Matrixd& projection, double& znear, double& zfar) const = 0;
+        };
+        
+        /** set the ClampProjectionMatrixCallback.*/
+        void setClampProjectionMatrixCallback(ClampProjectionMatrixCallback* cpmc) { _clampProjectionMatrixCallback = cpmc; applyMaskAction(CLAMP_PROJECTION_MATRIX_CALLBACK); }
+        /** get the non const ClampProjectionMatrixCallback.*/
+        ClampProjectionMatrixCallback* getClampProjectionMatrixCallback() { return _clampProjectionMatrixCallback.get(); }
+        /** get the const ClampProjectionMatrixCallback.*/
+        const ClampProjectionMatrixCallback* getClampProjectionMatrixCallback() const { return _clampProjectionMatrixCallback.get(); }
+
+
+        /** Write out internal settings of CullSettings. */
+        void write(std::ostream& out);
+
+    protected:
+
+        unsigned int                                _inheritanceMask;
+        InheritanceMaskActionOnAttributeSetting     _inheritanceMaskActionOnAttributeSetting;
+
+        ComputeNearFarMode                          _computeNearFar;
+        CullingMode                                 _cullingMode;
+        float                                       _LODScale;
+        float                                       _smallFeatureCullingPixelSize;
+
+        ref_ptr<ClampProjectionMatrixCallback>      _clampProjectionMatrixCallback;
+        double                                      _nearFarRatio;
+        bool                                        _impostorActive;
+        bool                                        _depthSortImpostorSprites;
+        float                                       _impostorPixelErrorThreshold;
+        int                                         _numFramesToKeepImpostorSprites;    
+
+        Node::NodeMask                              _cullMask;
+        Node::NodeMask                              _cullMaskLeft;
+        Node::NodeMask                              _cullMaskRight;
+ 
+
+};
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Image
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Image (revision 9643)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Image (revision 9643)
@@ -0,0 +1,379 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_IMAGE
+#define OSG_IMAGE 1
+
+#include <osg/BufferObject>
+#include <osg/Vec2>
+#include <osg/Vec3>
+#include <osg/Vec4>
+#include <osg/FrameStamp>
+
+#include <string>
+#include <vector>
+
+#ifndef GL_VERSION_1_2
+    // 1.2 definitions...
+    #define GL_BGR                          0x80E0
+    #define GL_BGRA                         0x80E1
+    #define GL_UNSIGNED_BYTE_3_3_2          0x8032
+    #define GL_UNSIGNED_BYTE_2_3_3_REV      0x8362
+    #define GL_UNSIGNED_SHORT_5_6_5         0x8363
+    #define GL_UNSIGNED_SHORT_5_6_5_REV     0x8364
+    #define GL_UNSIGNED_SHORT_4_4_4_4       0x8033
+    #define GL_UNSIGNED_SHORT_4_4_4_4_REV   0x8365
+    #define GL_UNSIGNED_SHORT_5_5_5_1       0x8034
+    #define GL_UNSIGNED_SHORT_1_5_5_5_REV   0x8366
+    #define GL_UNSIGNED_INT_8_8_8_8         0x8035
+    #define GL_UNSIGNED_INT_8_8_8_8_REV     0x8367
+    #define GL_UNSIGNED_INT_10_10_10_2      0x8036
+    #define GL_UNSIGNED_INT_2_10_10_10_REV  0x8368
+#endif
+
+#ifndef GL_COMPRESSED_ALPHA
+    #define GL_COMPRESSED_ALPHA             0x84E9
+    #define GL_COMPRESSED_LUMINANCE         0x84EA
+    #define GL_COMPRESSED_LUMINANCE_ALPHA   0x84EB
+    #define GL_COMPRESSED_INTENSITY         0x84EC
+    #define GL_COMPRESSED_RGB               0x84ED
+    #define GL_COMPRESSED_RGBA              0x84EE
+#endif
+
+
+#ifndef GL_ABGR_EXT
+#define GL_ABGR_EXT                         0x8000
+#endif
+
+namespace osg {
+
+// forward declare
+class NodeVisitor;
+
+/** Image class for encapsulating the storage texture image data. */
+class OSG_EXPORT Image : public Object
+{
+
+    public :
+
+        Image();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Image(const Image& image,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
+
+        virtual Object* cloneType() const { return new Image(); }
+        virtual Object* clone(const CopyOp& copyop) const { return new Image(*this,copyop); }
+        virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Image*>(obj)!=0; }
+        virtual const char* libraryName() const { return "osg"; }
+        virtual const char* className() const { return "Image"; }
+
+        /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const Image& rhs) const;
+
+        void setFileName(const std::string& fileName);
+        inline const std::string& getFileName() const { return _fileName; }
+        
+        enum WriteHint {
+            NO_PREFERENCE,
+            STORE_INLINE,
+            EXTERNAL_FILE
+        };
+        
+        void setWriteHint(WriteHint writeHint) { _writeHint = writeHint; }
+        WriteHint getWriteHint() const { return _writeHint; }
+        
+        enum AllocationMode {
+            NO_DELETE,
+            USE_NEW_DELETE,
+            USE_MALLOC_FREE
+        };
+        
+        /** Set the method used for deleting data once it goes out of scope. */
+        void setAllocationMode(AllocationMode mode) { _allocationMode = mode; }
+
+        /** Get the method used for deleting data once it goes out of scope. */
+        AllocationMode getAllocationMode() const { return _allocationMode; }
+
+
+        /** Allocate a pixel block of specified size and type. */
+        void allocateImage(int s,int t,int r,
+                           GLenum pixelFormat,GLenum type,
+                           int packing=1);
+        
+        
+        /** Set the image dimensions, format and data. */
+        void setImage(int s,int t,int r,
+                      GLint internalTextureformat,
+                      GLenum pixelFormat,GLenum type,
+                      unsigned char* data,
+                      AllocationMode mode,
+                      int packing=1);
+            
+        /** Read pixels from current frame buffer at specified position and size, using glReadPixels.
+          * Create memory for storage if required, reuse existing pixel coords if possible.
+        */
+        void readPixels(int x,int y,int width,int height,
+                        GLenum pixelFormat,GLenum type);
+            
+
+        /** Read the contents of the current bound texture, handling compressed pixelFormats if present.
+          * Create memory for storage if required, reuse existing pixel coords if possible.
+        */
+        void readImageFromCurrentTexture(unsigned int contextID, bool copyMipMapsIfAvailable, GLenum type = GL_UNSIGNED_BYTE);
+
+
+        /** Scale image to specified size. */
+        void scaleImage(int s,int t,int r) { scaleImage(s,t,r, getDataType()); }
+
+        /** Scale image to specified size and with specified data type. */
+        void scaleImage(int s,int t,int r, GLenum newDataType);
+
+        /** Copy a source Image into a subpart of this Image at specified position.
+          * Typically used to copy to an already allocated image, such as creating
+          * a 3D image from a stack 2D images.
+          * If this Image is empty then image data is created to
+          * accomodate the source image in its offset position.
+          * If source is NULL then no operation happens, this Image is left unchanged.
+        */
+        void copySubImage(int s_offset, int t_offset, int r_offset, const osg::Image* source);
+
+
+        enum Origin 
+        {
+            BOTTOM_LEFT,
+            TOP_LEFT
+        };
+        
+        /** Set the origin of the image.
+          * The default value is BOTTOM_LEFT and is consistent with OpenGL.
+          * TOP_LEFT is used for imagery that follows standard Imagery convention, such as movies,
+          * and hasn't been flipped yet.  For such images one much flip the t axis of the tex coords.
+          * to handle this origin position. */
+        void setOrigin(Origin origin) { _origin = origin; }
+        
+        /** Get the origin of the image.*/
+        Origin getOrigin() const { return _origin; }
+        
+
+        /** Width of image. */
+        inline int s() const { return _s; }
+
+        /** Height of image. */
+        inline int t() const { return _t; }
+        
+        /** Depth of image. */
+        inline int r() const { return _r; }
+        
+        void setInternalTextureFormat(GLint internalFormat);
+        inline GLint getInternalTextureFormat() const { return _internalTextureFormat; }
+        
+        void setPixelFormat(GLenum pixelFormat);
+        inline GLenum getPixelFormat() const { return _pixelFormat; }
+        
+        void setDataType(GLenum dataType);
+        inline GLenum getDataType() const { return _dataType; }        
+        
+        void setPacking(unsigned int packing) { _packing = packing; }
+        inline unsigned int getPacking() const { return _packing; }
+        
+        /** Return the number of bits required for each pixel. */
+        inline unsigned int getPixelSizeInBits() const { return computePixelSizeInBits(_pixelFormat,_dataType); }
+
+        /** Return the number of bytes each row of pixels occupies once it has been packed. */
+        inline unsigned int getRowSizeInBytes() const { return computeRowWidthInBytes(_s,_pixelFormat,_dataType,_packing); }
+
+        /** Return the number of bytes each image (_s*_t) of pixels occupies. */
+        inline unsigned int getImageSizeInBytes() const { return getRowSizeInBytes()*_t; }
+        
+        /** Return the number of bytes the whole row/image/volume of pixels occupies. */
+        inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; }
+
+        /** Return the number of bytes the whole row/image/volume of pixels occupies, including all mip maps if included. */
+        unsigned int getTotalSizeInBytesIncludingMipmaps() const;
+
+        /** Return true if the Image represent a valid and usable imagery.*/
+        bool valid() const { return _s!=0 && _t!=0 && _r!=0 && _data!=0 && _dataType!=0; }
+
+        /** Raw image data. */
+        inline unsigned char* data() { return _data; }
+        
+        /** Raw const image data. */
+        inline const unsigned char* data() const { return _data; }
+
+
+        inline unsigned char* data(int column, int row=0,int image=0)
+        {
+            if (!_data) return NULL;
+            return _data+(column*getPixelSizeInBits())/8+row*getRowSizeInBytes()+image*getImageSizeInBytes();
+        }
+        
+        inline const unsigned char* data(int column, int row=0,int image=0) const
+        {
+            if (!_data) return NULL;
+            return _data+(column*getPixelSizeInBits())/8+row*getRowSizeInBytes()+image*getImageSizeInBytes();
+        }
+
+        /** Get the color value for specified texcoord.*/
+        Vec4 getColor(unsigned int s,unsigned t=0,unsigned r=0) const;
+
+        /** Get the color value for specified texcoord.*/
+        Vec4 getColor(const Vec2& texcoord) const { return getColor(Vec3(texcoord.x(),texcoord.y(),0.0f)); }
+
+        /** Get the color value for specified texcoord.*/
+        Vec4 getColor(const Vec3& texcoord) const;
+
+
+        /** Flip the image horizontally. */
+        void flipHorizontal();
+        
+        /** Flip the image vertically. */
+        void flipVertical();
+
+
+        /** Ensure image dimensions are a power of two.
+          * Mipmapped textures require the image dimensions to be
+          * power of two and are within the maxiumum texture size for
+          * the host machine.
+        */
+        void ensureValidSizeForTexturing(GLint maxTextureSize);
+      
+        /** Dirty the image, which increments the modified count, to force osg::Texture to reload the image. */
+        inline void dirty() { ++_modifiedCount; if (_bufferObject.valid()) _bufferObject->dirty(); }      
+      
+        /** Set the modified count value. Used by osg::Texture when using texture subloading. */
+        inline void setModifiedCount(unsigned int value) { _modifiedCount=value; }
+
+        /** Get modified count value. Used by osg::Texture when using texture subloading. */
+        inline unsigned int getModifiedCount() const { return _modifiedCount; }
+
+
+        static bool isPackedType(GLenum type);
+        static GLenum computePixelFormat(GLenum pixelFormat);
+        static GLenum computeFormatDataType(GLenum pixelFormat);
+        static unsigned int computeNumComponents(GLenum pixelFormat);
+        static unsigned int computePixelSizeInBits(GLenum pixelFormat,GLenum type);
+        static unsigned int computeRowWidthInBytes(int width,GLenum pixelFormat,GLenum type,int packing);
+        static int computeNearestPowerOfTwo(int s,float bias=0.5f);
+        static int computeNumberOfMipmapLevels(int s,int t = 1, int r = 1);
+                
+        /** Precomputed mipmaps stuff. */
+        typedef std::vector< unsigned int > MipmapDataType;
+
+        inline bool isMipmap() const {return !_mipmapData.empty();};
+
+        unsigned int getNumMipmapLevels() const
+        {
+            return static_cast<unsigned int>(_mipmapData.size())+1;
+        };
+
+        /** Send offsets into data. It is assumed that first mipmap offset (index 0) is 0.*/
+        inline void setMipmapLevels(const MipmapDataType& mipmapDataVector) { _mipmapData = mipmapDataVector; }
+        
+        inline const MipmapDataType& getMipmapLevels() const { return _mipmapData; }
+
+        inline unsigned int getMipmapOffset(unsigned int mipmapLevel) const
+        {
+            if(mipmapLevel == 0)
+                return 0;
+            else if (mipmapLevel < getNumMipmapLevels())
+               return _mipmapData[mipmapLevel-1];
+            return 0;
+        };
+        
+        inline unsigned char* getMipmapData(unsigned int mipmapLevel)
+        {
+           return _data+getMipmapOffset(mipmapLevel);
+        }
+
+        inline const unsigned char* getMipmapData(unsigned int mipmapLevel) const
+        {
+           return _data+getMipmapOffset(mipmapLevel);
+        }
+
+        /*inline const unsigned char* getMipmapData(unsigned int row, unsigned int column, unsigned int mipmapLevel) const
+        {
+           if (!_data) return NULL;
+           return getMipmapData(mipmapLevel) + (column*getPixelSizeInBits())/8+row*getRowSizeInBytes();
+        }*/
+
+        /** Return true if this image is translucent - i.e. it has alpha values that are less 1.0 (when normalized). */
+        bool isImageTranslucent() const;
+
+        /** Set the optional PixelBufferObject used to map the image memory efficiently to graphics memory. */ 
+        void setPixelBufferObject(PixelBufferObject* buffer) { _bufferObject = buffer; if (_bufferObject.valid()) _bufferObject->setImage(this); }
+
+        /** Get the PixelBufferObject.*/ 
+        PixelBufferObject* getPixelBufferObject() { return _bufferObject.get(); }
+
+        /** Get the const PixelBufferObject.*/ 
+        const PixelBufferObject* getPixelBufferObject() const { return _bufferObject.get(); }
+       
+        virtual void update(NodeVisitor* /*nv*/) {}        
+
+        /** method for sending pointer events to images that are acting as front ends to interactive surfaces such as a vnc or browser window.  Return true if handled. */
+        virtual bool sendPointerEvent(int /*x*/, int /*y*/, int /*buttonMask*/) { return false; }
+
+        /** method for sending key events to images that are acting as front ends to interactive surfaces such as a vnc or browser window.  Return true if handled.*/
+        virtual bool sendKeyEvent(int /*key*/, bool /*keyDown*/) { return false; }
+
+        /** method for passing frame information to the custom Image classes, to be called only when objects associated with imagery are not culled.*/
+        virtual void setFrameLastRendered(const osg::FrameStamp* /*frameStamp*/) {}
+
+    protected :
+
+        virtual ~Image();
+
+        Image& operator = (const Image&) { return *this; }
+
+        std::string _fileName;
+        WriteHint   _writeHint;
+
+
+        Origin _origin;
+
+        int _s, _t, _r;
+        GLint _internalTextureFormat;
+        GLenum _pixelFormat;
+        GLenum _dataType;
+        unsigned int _packing;
+
+        AllocationMode _allocationMode;
+        unsigned char* _data;
+        
+        void deallocateData();
+        
+        void setData(unsigned char* data,AllocationMode allocationMode);
+
+        unsigned int _modifiedCount;
+
+        MipmapDataType _mipmapData;
+        
+        ref_ptr<PixelBufferObject> _bufferObject;
+};
+
+class Geode;
+
+/** Convenience function to be used by image loaders to generate a valid geode
+  * to return for readNode().
+  * Use the image's s and t values to scale the dimensions of the image.
+*/
+extern OSG_EXPORT Geode* createGeodeForImage(Image* image);
+/** Convenience function to be used by image loaders to generate a valid geode
+  * to return for readNode().
+  * Use the specified s and t values to scale the dimensions of the image.
+*/
+extern OSG_EXPORT Geode* createGeodeForImage(Image* image,float s,float t);
+
+}
+
+#endif                                            // __SG_IMAGE_H
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLExtensions
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLExtensions (revision 9469)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/GLExtensions (revision 9469)
@@ -0,0 +1,163 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_GLEXTENSIONS
+#define OSG_GLEXTENSIONS 1
+
+#include <osg/Export>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+
+
+namespace osg {
+
+/** Return floating-point OpenGL version number.
+  * Note: Must only be called within a valid OpenGL context,
+  * undefined behavior may occur otherwise.
+*/
+extern OSG_EXPORT float getGLVersionNumber();
+
+/** Return true if "extension" is contained in "extensionString".
+*/
+extern OSG_EXPORT bool isExtensionInExtensionString(const char *extension, const char *extensionString);
+
+/** Return true if OpenGL "extension" is supported.
+  * Note: Must only be called within a valid OpenGL context,
+  * undefined behavior may occur otherwise.
+*/
+extern OSG_EXPORT bool isGLExtensionSupported(unsigned int contextID, const char *extension);
+
+/** Return true if OpenGL "extension" or minimum OpenGL version number is supported.
+  * Note: Must only be called within a valid OpenGL context,
+  * undefined behavior may occur otherwise.
+*/
+extern OSG_EXPORT bool isGLExtensionOrVersionSupported(unsigned int contextID, const char *extension, float requiredGlVersion);
+
+/** Return the address of the specified OpenGL function.
+  * Return NULL if function not supported by OpenGL library.
+  * Note, glGLExtensionFuncPtr is declared inline so that the code
+  * is compiled locally to the calling code.  This should get by Windows'
+  * dumb implementation of having different GL function ptr's for each
+  * library when linked to it. 
+*/
+extern OSG_EXPORT void* getGLExtensionFuncPtr(const char *funcName);
+
+/** Set a list of extensions to disable for different OpenGL renderers. This allows
+  * OSG applications to work around OpenGL drivers' bugs which are due to problematic extension support.
+  * The format of the string is:
+  * "GLRendererString : ExtensionName, ExtensionName; GLRenderString2 : ExtensionName;"
+  * An example of is : "SUN_XVR1000:GL_EXT_texture_filter_anisotropic"
+  * The default setting of GLExtensionDisableString is obtained from the OSG_GL_EXTENSION_DISABLE
+  * environmental variable.
+*/
+extern OSG_EXPORT void setGLExtensionDisableString(const std::string& disableString);
+
+/** Get the list of extensions that are disabled for various OpenGL renderers. */
+extern OSG_EXPORT std::string& getGLExtensionDisableString();
+
+/** Return the address of the specified OpenGL function. If not found then
+  * check a second function name, if this fails then return NULL as function is
+  * not supported by OpenGL library. This is used for checking something
+  * like glActiveTexture (which is in OGL1.3) or glActiveTextureARB.
+*/
+inline void* getGLExtensionFuncPtr(const char *funcName,const char *fallbackFuncName)
+{
+    void* ptr = getGLExtensionFuncPtr(funcName);
+    if (ptr) return ptr;
+    return getGLExtensionFuncPtr(fallbackFuncName);
+}
+
+/** Return the address of the specified OpenGL function. If not found then
+  * check a second function name, if this fails then return NULL as function is
+  * not supported by OpenGL library. This is used for checking something
+  * like glActiveTexture (which is in OGL1.3) or glActiveTextureARB.
+*/
+inline void* getGLExtensionFuncPtr(const char *funcName1, const char *funcName2, const char *funcName3)
+{
+    void* ptr = getGLExtensionFuncPtr(funcName1);
+    if (ptr) return ptr;
+
+    ptr = getGLExtensionFuncPtr(funcName2);
+    if (ptr) return ptr;
+
+    return getGLExtensionFuncPtr(funcName3);
+}
+
+template<typename T, typename R>
+T convertPointerType(R src)
+{
+    T dest;
+    memcpy(&dest, &src, sizeof(src));
+    return dest;
+}
+
+template<typename T>
+bool setGLExtensionFuncPtr(T& t, const char* str1)
+{
+    void* data = osg::getGLExtensionFuncPtr(str1);
+    if (data)
+    {
+        memcpy(&t, &data, sizeof(T));
+        return true;        
+    }
+    else
+    {
+        t = 0;
+        return false;        
+    }
+}
+
+template<typename T>
+bool setGLExtensionFuncPtr(T& t, const char* str1, const char* str2)
+{
+    void* data = osg::getGLExtensionFuncPtr(str1,str2);
+    if (data)
+    {
+        memcpy(&t, &data, sizeof(T));
+        return true;        
+    }
+    else
+    {
+        t = 0;
+        return false;        
+    }
+}
+
+template<typename T>
+bool setGLExtensionFuncPtr(T& t, const char* str1, const char* str2, const char* str3)
+{
+    void* data = osg::getGLExtensionFuncPtr(str1,str2,str3);
+    if (data)
+    {
+        memcpy(&t, &data, sizeof(T));
+        return true;        
+    }
+    else
+    {
+        t = 0;
+        return false;        
+    }
+}
+
+
+/** Return true if OpenGL "extension" is supported.
+  * Note: Must only be called within a valid OpenGL context,
+  * undefined behavior may occur otherwise.
+*/
+extern OSG_EXPORT bool isGLUExtensionSupported(unsigned int contextID, const char *extension);
+
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/LineWidth
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/LineWidth (revision 4021)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/LineWidth (revision 4021)
@@ -0,0 +1,64 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_LINEWIDTH
+#define OSG_LINEWIDTH 1
+
+#include <osg/StateAttribute>
+
+namespace osg {
+
+/** LineWidth - encapsulates the OpenGL glLineWidth for setting the width of lines in pixels. */
+class OSG_EXPORT LineWidth : public StateAttribute
+{
+    public :
+
+        LineWidth(float width=1.0f);
+
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        LineWidth(const LineWidth& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY) :
+            StateAttribute(lw,copyop),
+            _width(lw._width) {}
+            
+        META_StateAttribute(osg, LineWidth, LINEWIDTH);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check if the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Parameter macros below.
+            COMPARE_StateAttribute_Types(LineWidth,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_width)
+
+            return 0; // passed all the above comparison macros, must be equal.
+        }
+
+        void setWidth(float width);
+        
+        inline float getWidth() const { return _width; }
+
+        virtual void apply(State& state) const;
+
+    protected :
+
+        virtual ~LineWidth();
+
+        float       _width;
+
+};
+
+}
+
+#endif
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Multisample
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Multisample (revision 7648)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Multisample (revision 7648)
@@ -0,0 +1,158 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_MULTISAMPLE
+#define OSG_MULTISAMPLE 1
+
+
+#include <osg/GL>
+#include <osg/StateAttribute>
+#include <osg/ref_ptr>
+
+
+#ifndef GL_ARB_multisample
+#define GL_MULTISAMPLE_ARB                0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB   0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_ARB        0x809F
+#define GL_SAMPLE_COVERAGE_ARB            0x80A0
+#define GL_SAMPLE_BUFFERS_ARB             0x80A8
+#define GL_SAMPLES_ARB                    0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE_ARB      0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT_ARB     0x80AB
+#define GL_MULTISAMPLE_BIT_ARB            0x20000000
+#endif
+#ifndef GL_NV_multisample_filter_hint
+#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534
+#endif
+
+
+namespace osg {
+
+/** Multisample - encapsulates the OpenGL Multisample state.*/
+class OSG_EXPORT Multisample : public StateAttribute
+{
+    public :
+
+        enum Mode
+        {
+            FASTEST = GL_FASTEST, 
+            NICEST = GL_NICEST,
+            DONT_CARE = GL_DONT_CARE 
+        };
+
+        Multisample();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy.*/
+        Multisample(const Multisample& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(trans,copyop),
+            _coverage(trans._coverage),
+            _invert(trans._invert),
+            _mode(trans._mode) {}
+
+        META_StateAttribute(osg, Multisample,MULTISAMPLE);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Parameter macro's below.
+            COMPARE_StateAttribute_Types(Multisample,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_coverage)
+            COMPARE_StateAttribute_Parameter(_invert)
+            COMPARE_StateAttribute_Parameter(_mode)
+
+            return 0; // passed all the above comparison macros, must be equal.
+        }
+
+        void setSampleCoverage(float coverage, bool invert) 
+        {
+            _coverage = coverage; 
+            _invert = invert;
+        }
+        inline void setCoverage(float coverage) { _coverage=coverage; }
+        inline float getCoverage() const { return _coverage; }
+    
+        inline void setInvert(bool invert) { _invert=invert; }
+        inline bool getInvert() const { return _invert; }
+
+        inline void setHint(Mode mode) { _mode = mode; }
+        inline Mode getHint() const { return _mode; }
+
+        virtual void apply(State& state) const;
+
+
+        /** Extensions class which encapsulates the querying of extensions and
+          * associated function pointers, and provide convenience wrappers to 
+          * check for the extensions or use the associated functions.*/        
+        class OSG_EXPORT Extensions : public osg::Referenced
+        {
+            public:
+                Extensions(unsigned int contextID);
+
+                Extensions(const Extensions& rhs);
+                
+                void lowestCommonDenominator(const Extensions& rhs);
+                
+                void setupGLExtensions(unsigned int contextID);
+
+                void setMultisampleSupported(bool flag) { _isMultisampleSupported=flag; }
+                void setMultisampleFilterHintSupported(bool flag) { _isMultisampleFilterHintSupported=flag; }
+                bool isMultisampleSupported() const { return _isMultisampleSupported; }
+                bool isMultisampleFilterHintSupported() const { return _isMultisampleFilterHintSupported; }
+                
+                void glSampleCoverage(GLclampf value, GLboolean invert) const;
+
+            protected:
+
+                ~Extensions() {}
+                
+                bool    _isMultisampleSupported;
+                bool    _isMultisampleFilterHintSupported;
+                
+                typedef void (APIENTRY * GLSampleCoverageProc) (GLclampf value, GLboolean invert);
+                GLSampleCoverageProc _glSampleCoverage;
+
+        };
+        
+        /** Function to call to get the extension of a specified context.
+          * If the Extension object for that context has not yet been created 
+          * and the 'createIfNotInitalized' flag been set to false then returns NULL.
+          * If 'createIfNotInitalized' is true then the Extensions object is 
+          * automatically created.  However, in this case the extension object will
+          * only be created with the graphics context associated with ContextID..*/
+        static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
+
+        /** setExtensions allows users to override the extensions across graphics contexts.
+          * Typically used when you have different extensions supported across graphics pipes
+          * but need to ensure that they all use the same low common denominator extensions.*/
+        static void setExtensions(unsigned int contextID,Extensions* extensions);
+
+
+
+    protected :
+
+        virtual ~Multisample();
+
+        float _coverage;
+        bool _invert;
+        Mode _mode;
+};
+
+}
+
+#endif
+
+
+
Index: /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Material
===================================================================
--- /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Material (revision 6311)
+++ /OpenSceneGraph/branches/OpenSceneGraph-2.8.2/include/osg/Material (revision 6311)
@@ -0,0 +1,196 @@
+/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield 
+ *
+ * This library is open source and may be redistributed and/or modified under  
+ * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
+ * (at your option) any later version.  The full license is in LICENSE file
+ * included with this distribution, and on the openscenegraph.org website.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ * OpenSceneGraph Public License for more details.
+*/
+
+#ifndef OSG_MATERIAL
+#define OSG_MATERIAL 1
+
+#include <osg/Vec4>
+#include <osg/StateAttribute>
+
+namespace osg {
+/** Material - encapsulates OpenGL glMaterial state.*/
+class OSG_EXPORT Material : public StateAttribute
+{
+    public :
+
+        Material();
+        
+        /** Copy constructor using CopyOp to manage deep vs shallow copy. */
+        Material(const Material& mat,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
+            StateAttribute(mat,copyop),
+            _colorMode(mat._colorMode),
+            _ambientFrontAndBack(mat._ambientFrontAndBack),
+            _ambientFront(mat._ambientFront),
+            _ambientBack(mat._ambientBack),
+            _diffuseFrontAndBack(mat._diffuseFrontAndBack),
+            _diffuseFront(mat._diffuseFront),
+            _diffuseBack(mat._diffuseBack),
+            _specularFrontAndBack(mat._specularFrontAndBack),
+            _specularFront(mat._specularFront),
+            _specularBack(mat._specularBack),
+            _emissionFrontAndBack(mat._emissionFrontAndBack),
+            _emissionFront(mat._emissionFront),
+            _emissionBack(mat._emissionBack),
+            _shininessFrontAndBack(mat._shininessFrontAndBack),
+            _shininessFront(mat._shininessFront),
+            _shininessBack(mat._shininessBack) {}
+
+        META_StateAttribute(osg, Material, MATERIAL);
+        
+        /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
+        virtual int compare(const StateAttribute& sa) const
+        {
+            // check the types are equal and then create the rhs variable
+            // used by the COMPARE_StateAttribute_Parameter macros below.
+            COMPARE_StateAttribute_Types(Material,sa)
+
+            // compare each parameter in turn against the rhs.
+            COMPARE_StateAttribute_Parameter(_colorMode)
+            COMPARE_StateAttribute_Parameter(_ambientFrontAndBack)
+            COMPARE_StateAttribute_Parameter(_ambientFront)
+            COMPARE_StateAttribute_Parameter(_ambientBack)
+            COMPARE_StateAttribute_Parameter(_diffuseFrontAndBack)
+            COMPARE_StateAttribute_Parameter(_diffuseFront)
+            COMPARE_StateAttribute_Parameter(_diffuseBack)
+            COMPARE_StateAttribute_Parameter(_specularFrontAndBack)
+            COMPARE_StateAttribute_Parameter(_specularFront)
+            COMPARE_StateAttribute_Parameter(_specularBack)
+            COMPARE_StateAttribute_Parameter(_emissionFrontAndBack)
+            COMPARE_StateAttribute_Parameter(_emissionFront)
+            COMPARE_StateAttribute_Parameter(_emissionBack)
+            COMPARE_StateAttribute_Parameter(_shininessFrontAndBack)
+            COMPARE_StateAttribute_Parameter(_shininessFront)
+            COMPARE_StateAttribute_Parameter(_shininessBack)
+
+            return 0; // passed all the above comparison macros, must be equal.
+        }
+
+        Material& operator = (const Material& rhs);
+
+        virtual bool getModeUsage(StateAttribute::ModeUsage& /*usage*/) const
+        {
+            // note, since Material does it's own glEnable/glDisable of GL_COLOR_MATERIAL
+            // we shouldn't declare usage of that mode, so commenting out the below usage.
+            // usage.usesMode(GL_COLOR_MATERIAL);
+            return true;
+        }
+
+        virtual void apply(State& state) const;
+
+        enum Face {
+            FRONT           = GL_FRONT,
+            BACK            = GL_BACK,
+            FRONT_AND_BACK  = GL_FRONT_AND_BACK
+        };
+
+        enum ColorMode {
+            AMBIENT = GL_AMBIENT,
+            DIFFUSE = GL_DIFFUSE,
+            SPECULAR = GL_SPECULAR,
+            EMISSION = GL_EMISSION,
+            AMBIENT_AND_DIFFUSE = GL_AMBIENT_AND_DIFFUSE,
+            OFF            
+        };
+
+        inline void setColorMode(ColorMode mode) { _colorMode = mode; }
+        inline ColorMode getColorMode() const { return _colorMode; }
+
+        void setAmbient( Face face, const Vec4& ambient );
+        const Vec4& getAmbient(Face face) const;
+        inline bool getAmbientFrontAndBack() const { return _ambientFrontAndBack; }
+
+        void setDiffuse( Face face, const Vec4& diffuse );
+        const Vec4& getDiffuse(Face face) const;
+        inline bool getDiffuseFrontAndBack() const { return _diffuseFrontAndBack; }
+
+        /** Set specular value of specified face(s) of the material, 
+          * valid specular[0..3] range is 0.0 to 1.0.
+        */
+        void setSpecular( Face face, const Vec4& specular );
+        
+        /** Get the specular value for specified face. */
+        const Vec4& getSpecular(Face face) const;
+        
+        /** Return whether specular values are equal for front and back faces
+          * or not.
+        */
+        inline bool getSpecularFrontAndBack() const { return _specularFrontAndBack; }
+
+        /** Set emission value of specified face(s) of the material, 
+          * valid emission[0..3] range is 0.0 to 1.0.
+        */
+        void setEmission( Face face, const Vec4& emission );
+        
+        /** Get the emission value for specified face. */
+        const Vec4& getEmission(Face face) const;
+        
+        /** Return whether emission values are equal for front and back faces
+          * or not.
+        */
+        inline bool getEmissionFrontAndBack() const { return _emissionFrontAndBack; }
+
+        /** Set shininess of specified face(s) of the material.
+          * valid shininess range is 0.0 to 128.0.
+        */
+        void setShininess(Face face, float shininess );
+        
+        /** Get the shininess value for specified face. */
+        float getShininess(Face face) const;
+        
+        /** Return whether shininess values are equal for front and back faces
+          * or not.
+        */
+        inline bool getShininessFrontAndBack() const { return _shininessFrontAndBack; }
+        
+        /** Set the alpha value of ambient, diffuse, specular and emission
+          * colors of specified face, to 1-transparency.
+          * Valid transparency range is 0.0 to 1.0.
+        */
+        void setTransparency(Face face,float trans);
+
+        /** Set the alpha value of 