Skip to content
State 101 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/* -*-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_STATE
#define OSG_STATE 1

#include <osg/Export>
#include <osg/StateSet>
#include <osg/Matrix>
#include <osg/Uniform>
#include <osg/BufferObject>
#include <osg/Observer>
#include <osg/Timer>

#include <osg/ShaderComposer>
#include <osg/FrameStamp>
#include <osg/DisplaySettings>
#include <osg/Polytope>
#include <osg/Viewport>
#include <osg/GLBeginEndAdapter>
#include <osg/ArrayDispatchers>
#include <osg/GraphicsCostEstimator>

#include <iosfwd>
#include <vector>
#include <map>
#include <set>
#include <string>

#ifndef GL_FOG_COORDINATE_ARRAY
    #ifdef GL_FOG_COORDINATE_ARRAY_EXT
        #define GL_FOG_COORDINATE_ARRAY GL_FOG_COORDINATE_ARRAY_EXT
    #else
        #define GL_FOG_COORDINATE_ARRAY 0x8457
    #endif
#endif

#ifndef GL_SECONDARY_COLOR_ARRAY
    #ifdef GL_SECONDARY_COLOR_ARRAY_EXT
        #define GL_SECONDARY_COLOR_ARRAY GL_SECONDARY_COLOR_ARRAY_EXT
    #else
        #define GL_SECONDARY_COLOR_ARRAY 0x845E
    #endif
#endif

#if !defined(GL_EXT_timer_query) && !defined(OSG_GL3_AVAILABLE)
    #ifdef _WIN32
        typedef          __int64 GLint64EXT;
        typedef unsigned __int64 GLuint64EXT;
    #else
        typedef long long int GLint64EXT;
        typedef unsigned long long int GLuint64EXT;
    #endif
#endif

namespace osg {

/** macro for use with osg::StateAttribute::apply methods for detecting and
  * reporting OpenGL error messages.*/
#define OSG_GL_DEBUG(message) \
    if (state.getFineGrainedErrorDetection()) \
    { \
        GLenum errorNo = glGetError(); \
        if (errorNo!=GL_NO_ERROR) \
        { \
            osg::notify(WARN)<<"Warning: detected OpenGL error '"<<gluErrorString(errorNo)<<" "<<message<<endl; \
        }\
    }


// forward declare GraphicsContext, View and State
class GraphicsContext;

class VertexAttribAlias
{
    public:
        VertexAttribAlias():
            _location(0) {}

        VertexAttribAlias(const VertexAttribAlias& rhs):
            _location(rhs._location),
            _glName(rhs._glName),
            _osgName(rhs._osgName),
            _declaration(rhs._declaration) {}

        VertexAttribAlias(GLuint location, const std::string glName, const std::string osgName, const std::string& declaration):
            _location(location),
            _glName(glName),
            _osgName(osgName),
            _declaration(declaration) {}

        GLuint      _location;
        std::string _glName;
        std::string _osgName;
        std::string _declaration;
};


/** Encapsulates the current applied OpenGL modes, attributes and vertex arrays settings,
  * implements lazy state updating and provides accessors for querying the current state.
  * The venerable Red Book says that "OpenGL is a state machine", and this class
  * represents the OpenGL state in OSG. Furthermore, \c State also has other
  * important features:
  * - It works as a stack of states (see \c pushStateSet() and
  *   \c popStateSet()). Manipulating this stack of OpenGL states manually is
  *   seldom needed, since OSG does this in the most common situations.
  * - It implements lazy state updating. This means that, if one requests a
  *   state change and that particular state is already in the requested state,
  *   no OpenGL call will be made. This ensures that the OpenGL pipeline is not
  *   stalled by unnecessary state changes.
  * - It allows to query the current OpenGL state without calls to \c glGet*(),
  *   which typically stall the graphics pipeline (see, for instance,
  *   \c captureCurrentState() and \c getModelViewMatrix()).
  */
class OSG_EXPORT State : public Referenced, public Observer
{
    public :

        State();


        /** Set the graphics context associated with that owns this State object.*/
        void setGraphicsContext(GraphicsContext* context) { _graphicsContext = context; }

        /** Get the graphics context associated with that owns this State object.*/
        GraphicsContext* getGraphicsContext() { return _graphicsContext; }

        /** Get the const graphics context associated with that owns this State object.*/
        const GraphicsContext* getGraphicsContext() const { return _graphicsContext; }


        /** Set the current OpenGL context uniqueID.
         *  The ContextID is used by classes like osg::StateAttribute's and osg::Drawable's to
         *  help manage seperate OpenGL objects, such as display lists, vertex buffer objects
         *  and texture object for each graphics context. The ContextID simply acts as an index 
         *  into arrays that these classes maintain for the purpose of storing GL object handles.
         * 
         *  Note, osgViewer::GraphicsWindow will automatically set up the ContextID for you,
         *  so you will rearely need to set this yourself.
         * 
         *  The exception is when creating your own graphics context, where you should set
         *  the ContextID uniquely for each graphics context.
         * 
         *  Typical settings for ContextID are 0,1,2,3... up to the maximum
         *  number of graphics contexts you have set up. By default contextID is 0.
         */
        inline void setContextID(unsigned int contextID) { _contextID=contextID; }

        /** Get the current OpenGL context unique ID.*/
        inline unsigned int getContextID() const { return _contextID; }


        /* Set whether shader composition is enabled.*/
        void setShaderCompositionEnabled(bool flag) { _shaderCompositionEnabled = flag; }

        /* Get whether shader composition is enabled.*/
        bool getShaderCompositionEnabled() const { return _shaderCompositionEnabled; }

        /** Set the ShaderComposor object that implements shader composition.*/
        void setShaderComposer(ShaderComposer* sc) { _shaderComposer = sc; }

        /** Get the ShaderComposor object.*/
        ShaderComposer* getShaderComposer() { return _shaderComposer.get(); }

        /** Get the const ShaderComposor object.*/
        const ShaderComposer* getShaderComposer() const { return _shaderComposer.get(); }

        /** Get the unform list in which to inject any uniforms that StateAttribute::apply(State&) methods provide.*/
        StateSet::UniformList& getCurrentShaderCompositionUniformList() { return _currentShaderCompositionUniformList; }

        /** Convinience method for StateAttribute:::apply(State&) methods to pass on their uniforms to osg::State so it can apply them at the appropriate point.*/
        void applyShaderCompositionUniform(const osg::Uniform* uniform, StateAttribute::OverrideValue value=StateAttribute::ON)
        {
            StateSet::RefUniformPair& up = _currentShaderCompositionUniformList[uniform->getName()];
            up.first = const_cast<Uniform*>(uniform);
            up.second = value;
        }


        /** Push stateset onto state stack.*/
        void pushStateSet(const StateSet* dstate);

        /** Pop stateset off state stack.*/
        void popStateSet();

        /** pop all statesets off state stack, ensuring it is empty ready for the next frame.
          * Note, to return OpenGL to default state, one should do any state.popAllStatSets(); state.apply().*/
        void popAllStateSets();

        /** Insert stateset onto state stack.*/
        void insertStateSet(unsigned int pos,const StateSet* dstate);

        /** Pop stateset off state stack.*/
        void removeStateSet(unsigned int pos);

        /** Get the number of StateSet's on the StateSet stack.*/
        unsigned int getStateSetStackSize() { return static_cast<unsigned int>(_stateStateStack.size()); }

        /** Pop StateSet's for the StateSet stack till its size equals the specified size.*/
        void popStateSetStackToSize(unsigned int size) { while (_stateStateStack.size()>size) popStateSet(); }

        typedef std::vector<const StateSet*> StateSetStack;

        /** Get the StateSet stack.*/
        StateSetStack& getStateSetStack() { return _stateStateStack; }


        /** Copy the modes and attributes which capture the current state.*/
        void captureCurrentState(StateSet& stateset) const;

        /** reset the state object to an empty stack.*/
        void reset();


        inline const Viewport* getCurrentViewport() const
        {
            return static_cast<const Viewport*>(getLastAppliedAttribute(osg::StateAttribute::VIEWPORT));
        }


        void setInitialViewMatrix(const osg::RefMatrix* matrix);

        inline const osg::Matrix& getInitialViewMatrix() const { return *_initialViewMatrix; }
        inline const osg::Matrix& getInitialInverseViewMatrix() const { return _initialInverseViewMatrix; }

        void applyProjectionMatrix(const osg::RefMatrix* matrix);

        inline const osg::Matrix& getProjectionMatrix() const { return *_projection; }

        void applyModelViewMatrix(const osg::RefMatrix* matrix);
        void applyModelViewMatrix(const osg::Matrix&);

        const osg::Matrix& getModelViewMatrix() const { return *_modelView; }

        void setUseModelViewAndProjectionUniforms(bool flag) { _useModelViewAndProjectionUniforms = flag; }
        bool getUseModelViewAndProjectionUniforms() const { return _useModelViewAndProjectionUniforms; }

        void updateModelViewAndProjectionMatrixUniforms();

        void applyModelViewAndProjectionUniformsIfRequired();

        osg::Uniform* getModelViewMatrixUniform() { return _modelViewMatrixUniform.get(); }
        osg::Uniform* getProjectionMatrixUniform() { return _projectionMatrixUniform.get(); }
        osg::Uniform* getModelViewProjectionMatrixUniform() { return _modelViewProjectionMatrixUniform.get(); }
        osg::Uniform* getNormalMatrixUniform() { return _normalMatrixUniform.get(); }


        Polytope getViewFrustum() const;


        void setUseVertexAttributeAliasing(bool flag) { _useVertexAttributeAliasing = flag; }
        bool getUseVertexAttributeAliasing() const { return _useVertexAttributeAliasing ; }

        typedef std::vector<VertexAttribAlias> VertexAttribAliasList;

        const VertexAttribAlias& getVertexAlias() { return _vertexAlias; }
        const VertexAttribAlias& getNormalAlias() { return _normalAlias; }
        const VertexAttribAlias& getColorAlias() { return _colorAlias; }
        const VertexAttribAlias& getSecondaryColorAlias() { return _secondaryColorAlias; }
        const VertexAttribAlias& getFogCoordAlias() { return _fogCoordAlias; }
        const VertexAttribAliasList& getTexCoordAliasList() { return _texCoordAliasList; }


        const Program::AttribBindingList&  getAttributeBindingList() { return _attributeBindingList; }

        bool convertVertexShaderSourceToOsgBuiltIns(std::string& source) const;


        /** Apply stateset.*/
        void apply(const StateSet* dstate);

        /** Updates the OpenGL state so that it matches the \c StateSet at the
          * top of the stack of <tt>StateSet</tt>s maintained internally by a
          * \c State.
         */
        void apply();

        /** Apply any shader composed state.*/
        void applyShaderComposition();

        /** Set whether a particular OpenGL mode is valid in the current graphics context.
          * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/
        inline void setModeValidity(StateAttribute::GLMode mode,bool valid)
        {
            ModeStack& ms = _modeMap[mode];
            ms.valid = valid;
        }

        /** Get whether a particular OpenGL mode is valid in the current graphics context.
          * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/
        inline bool getModeValidity(StateAttribute::GLMode mode)
        {
            ModeStack& ms = _modeMap[mode];
            return ms.valid;
        }

        inline void setGlobalDefaultModeValue(StateAttribute::GLMode mode,bool enabled)
        {
            ModeStack& ms = _modeMap[mode];
            ms.global_default_value = enabled;
        }

        inline bool getGlobalDefaultModeValue(StateAttribute::GLMode mode)
        {
            return _modeMap[mode].global_default_value;
        }


        /** Apply an OpenGL mode if required. This is a wrapper around
          * \c glEnable() and \c glDisable(), that just actually calls these
          * functions if the \c enabled flag is different than the current
          * state.
          * @return \c true if the state was actually changed. \c false
          *         otherwise. Notice that a \c false return does not indicate
          *         an error, it just means that the mode was already set to the
          *         same value as the \c enabled parameter.
        */
        inline bool applyMode(StateAttribute::GLMode mode,bool enabled)
        {
            ModeStack& ms = _modeMap[mode];
            ms.changed = true;
            return applyMode(mode,enabled,ms);
        }

        inline void setGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode,bool enabled)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            ms.global_default_value = enabled;
        }

        inline bool getGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            return ms.global_default_value;
        }

        inline bool applyTextureMode(unsigned int unit, StateAttribute::GLMode mode,bool enabled)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            ms.changed = true;
            return applyModeOnTexUnit(unit,mode,enabled,ms);
        }

        inline void setGlobalDefaultAttribute(const StateAttribute* attribute)
        {
            AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()];
            as.global_default_attribute = attribute;
        }

        inline const StateAttribute* getGlobalDefaultAttribute(StateAttribute::Type type, unsigned int member=0)
        {
            AttributeStack& as = _attributeMap[StateAttribute::TypeMemberPair(type,member)];
            return as.global_default_attribute.get();
        }

        /** Apply an attribute if required. */
        inline bool applyAttribute(const StateAttribute* attribute)
        {
            AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()];
            as.changed = true;
            return applyAttribute(attribute,as);
        }

        inline void setGlobalDefaultTextureAttribute(unsigned int unit, const StateAttribute* attribute)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[attribute->getTypeMemberPair()];
            as.global_default_attribute = attribute;
        }

        inline const StateAttribute* getGlobalDefaultTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member = 0)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[StateAttribute::TypeMemberPair(type,member)];
            return as.global_default_attribute.get();
        }


        inline bool applyTextureAttribute(unsigned int unit, const StateAttribute* attribute)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[attribute->getTypeMemberPair()];
            as.changed = true;
            return applyAttributeOnTexUnit(unit,attribute,as);
        }

        /** Mode has been set externally, update state to reflect this setting.*/
        void haveAppliedMode(StateAttribute::GLMode mode,StateAttribute::GLModeValue value);

        /** Mode has been set externally, therefore dirty the associated mode in osg::State
          * so it is applied on next call to osg::State::apply(..)*/
        void haveAppliedMode(StateAttribute::GLMode mode);

        /** Attribute has been applied externally, update state to reflect this setting.*/
        void haveAppliedAttribute(const StateAttribute* attribute);

        /** Attribute has been applied externally, 
          * and therefore this attribute type has been dirtied 
          * and will need to be re-applied on next osg::State.apply(..).
          * note, if you have an osg::StateAttribute which you have applied externally
          * then use the have_applied(attribute) method as this will cause the osg::State to
          * track the current state more accurately and enable lazy state updating such
          * that only changed state will be applied.*/
        void haveAppliedAttribute(StateAttribute::Type type, unsigned int member=0);

        /** Get whether the current specified mode is enabled (true) or disabled (false).*/
        bool getLastAppliedMode(StateAttribute::GLMode mode) const;

        /** Get the current specified attribute, return NULL if one has not yet been applied.*/
        const StateAttribute* getLastAppliedAttribute(StateAttribute::Type type, unsigned int member=0) const;

        /** texture Mode has been set externally, update state to reflect this setting.*/
        void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode,StateAttribute::GLModeValue value);

        /** texture Mode has been set externally, therefore dirty the associated mode in osg::State
          * so it is applied on next call to osg::State::apply(..)*/
        void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode);

        /** texture Attribute has been applied externally, update state to reflect this setting.*/
        void haveAppliedTextureAttribute(unsigned int unit, const StateAttribute* attribute);

        /** texture Attribute has been applied externally,
          * and therefore this attribute type has been dirtied
          * and will need to be re-applied on next osg::State.apply(..).
          * note, if you have an osg::StateAttribute which you have applied externally
          * then use the have_applied(attribute) method as this will the osg::State to
          * track the current state more accurately and enable lazy state updating such
          * that only changed state will be applied.*/
        void haveAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0);

        /** Get whether the current specified texture mode is enabled (true) or disabled (false).*/
        bool getLastAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode) const;

        /** Get the current specified texture attribute, return NULL if one has not yet been applied.*/
        const StateAttribute* getLastAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0) const;


        /** Dirty the modes previously applied in osg::State.*/
        void dirtyAllModes();

        /** Dirty the modes attributes previously applied in osg::State.*/
        void dirtyAllAttributes();

        /** disable the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/
        void disableAllVertexArrays();

        /** dirty the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/
        void dirtyAllVertexArrays();


        void setCurrentVertexBufferObject(osg::GLBufferObject* vbo) { _currentVBO = vbo; }
        const GLBufferObject* getCurrentVertexBufferObject() { return _currentVBO; }
        inline void bindVertexBufferObject(osg::GLBufferObject* vbo)
        {
            if (vbo == _currentVBO) return;
            if (vbo->isDirty()) vbo->compileBuffer();
            else vbo->bindBuffer();
            _currentVBO = vbo;
        }

        inline void unbindVertexBufferObject()
        {
            if (!_currentVBO) return;
            _glBindBuffer(GL_ARRAY_BUFFER_ARB,0);
            _currentVBO = 0;
        }

        void setCurrentElementBufferObject(osg::GLBufferObject* ebo) { _currentEBO = ebo; }
        const GLBufferObject* getCurrentElementBufferObject() { return _currentEBO; }

        inline void bindElementBufferObject(osg::GLBufferObject* ebo)
        {
            if (ebo == _currentEBO) return;
            if (ebo->isDirty()) ebo->compileBuffer();
            else ebo->bindBuffer();
            _currentEBO = ebo;
        }

        inline void unbindElementBufferObject()
        {
            if (!_currentEBO) return;
            _glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0);
            _currentEBO = 0;
        }

        void setCurrentPixelBufferObject(osg::GLBufferObject* pbo) { _currentPBO = pbo; }
        const GLBufferObject* getCurrentPixelBufferObject() { return _currentPBO; }

        inline void bindPixelBufferObject(osg::GLBufferObject* pbo)
        {
            if (pbo == _currentPBO) return;

            if (pbo->isDirty()) pbo->compileBuffer();
            else pbo->bindBuffer();

            _currentPBO = pbo;
        }

        inline void unbindPixelBufferObject()
        {
            if (!_currentPBO) return;

            _glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB,0);
            _currentPBO = 0;
        }

        typedef std::vector<GLushort> IndicesGLushort;
        IndicesGLushort _quadIndicesGLushort[4];

        typedef std::vector<GLuint> IndicesGLuint;
        IndicesGLuint _quadIndicesGLuint[4];

        void drawQuads(GLint first, GLsizei count, GLsizei primCount=0);

        inline void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
        {
            if (primcount>=1 && _glDrawArraysInstanced!=0) _glDrawArraysInstanced(mode, first, count, primcount);
            else glDrawArrays(mode, first, count);
        }

        inline void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount )
        {
            if (primcount>=1 && _glDrawElementsInstanced!=0) _glDrawElementsInstanced(mode, count, type, indices, primcount);
            else glDrawElements(mode, count, type, indices);
        }


        inline void Vertex(float x, float y, float z, float w=1.0f)
        {
        #if defined(OSG_GL_VERTEX_FUNCS_AVAILABLE) && !defined(OSG_GLES1_AVAILABLE)
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _vertexAlias._location, x,y,z,w);
            else glVertex4f(x,y,z,w);
        #else
            _glVertexAttrib4f( _vertexAlias._location, x,y,z,w);
        #endif
        }

        inline void Color(float r, float g, float b, float a=1.0f)
        {
        #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _colorAlias._location, r,g,b,a);
            else glColor4f(r,g,b,a);
        #else
            _glVertexAttrib4f( _colorAlias._location, r,g,b,a);
        #endif
        }

        void Normal(float x, float y, float z)
        {
        #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0);
            else glNormal3f(x,y,z);
        #else
            _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0);
        #endif
        }

        void TexCoord(float x, float y=0.0f, float z=0.0f, float w=1.0f)
        {
        #if !defined(OSG_GLES1_AVAILABLE)
            #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
                if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w);
                else glTexCoord4f(x,y,z,w);
            #else
                _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w);
            #endif
        #endif
        }

        void MultiTexCoord(unsigned int unit, float x, float y=0.0f, float z=0.0f, float w=1.0f)
        {
        #if !defined(OSG_GLES1_AVAILABLE)
            #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
                if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w);
                else _glMultiTexCoord4f(GL_TEXTURE0+unit,x,y,z,w);
            #else
                _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w);
            #endif
        #endif
        }

        void VerteAttrib(unsigned int location, float x, float y=0.0f, float z=0.0f, float w=0.0f)
        {
            _glVertexAttrib4f( location, x,y,z,w);
        }


        /** Mark all the vertex attributes as being disabled but leave the disabling till a later call to applyDisablingOfVertexAttributes.*/
        void lazyDisablingOfVertexAttributes();

        /** Disable all the vertex attributes that have been marked as to be disabled.*/
        void applyDisablingOfVertexAttributes();

        /** Wrapper around glInterleavedArrays(..).
          * also resets the internal array points and modes within osg::State to keep the other
          * vertex array operations consistent. */
        void setInterleavedArrays( GLenum format, GLsizei stride, const GLvoid* pointer);

        /** Set the vertex pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setVertexPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setVertexPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setVertexPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_VERTEX_ARRAY);glVertexPointer(..);
          * note, only updates values that change.*/
        inline void setVertexPointer( GLint size, GLenum type,
                                      GLsizei stride, const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_vertexAlias._location, size, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_vertexArray._enabled || _vertexArray._dirty)
                {
                    _vertexArray._enabled = true;
                    glEnableClientState(GL_VERTEX_ARRAY);
                }
                //if (_vertexArray._pointer!=ptr || _vertexArray._dirty)
                {
                    _vertexArray._pointer=ptr;
                    glVertexPointer( size, type, stride, ptr );
                }
                _vertexArray._lazy_disable = false;
                _vertexArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_vertexAlias._location, size, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_VERTEX_ARRAY).
          * note, only updates values that change.*/
        inline void disableVertexPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_vertexAlias._location);
            }
            else
            {
                if (_vertexArray._enabled || _vertexArray._dirty)
                {
                    _vertexArray._lazy_disable = false;
                    _vertexArray._enabled = false;
                    _vertexArray._dirty = false;
                    glDisableClientState(GL_VERTEX_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_vertexAlias._location);
        #endif
        }

        inline void dirtyVertexPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_vertexAlias._location);
            }
            else
            {
                _vertexArray._pointer = 0;
                _vertexArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_vertexAlias._location);
        #endif
        }


        /** Set the normal pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setNormalPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setNormalPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setNormalPointer(array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_NORMAL_ARRAY);glNormalPointer(..);
          * note, only updates values that change.*/
        inline void setNormalPointer( GLenum type, GLsizei stride,
                                      const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_normalAlias._location, 3, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_normalArray._enabled || _normalArray._dirty)
                {
                    _normalArray._enabled = true;
                    glEnableClientState(GL_NORMAL_ARRAY);
                }
                //if (_normalArray._pointer!=ptr || _normalArray._dirty)
                {
                    _normalArray._pointer=ptr;
                    glNormalPointer( type, stride, ptr );
                }
                _normalArray._lazy_disable = false;
                _normalArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_normalAlias._location, 3, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_NORMAL_ARRAY);
          * note, only updates values that change.*/
        inline void disableNormalPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_normalAlias._location);
            }
            else
            {
                if (_normalArray._enabled || _normalArray._dirty)
                {
                    _normalArray._lazy_disable = false;
                    _normalArray._enabled = false;
                    _normalArray._dirty = false;
                    glDisableClientState(GL_NORMAL_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_normalAlias._location);
        #endif
        }

        inline void dirtyNormalPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_normalAlias._location);
            }
            else
            {
                _normalArray._pointer = 0;
                _normalArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_normalAlias._location);
        #endif
        }

        /** Set the color pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setColorPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }


        /** wrapper around glEnableClientState(GL_COLOR_ARRAY);glColorPointer(..);
          * note, only updates values that change.*/
        inline void setColorPointer( GLint size, GLenum type,
                                     GLsizei stride, const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_colorAlias._location, size, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_colorArray._enabled || _colorArray._dirty)
                {
                    _colorArray._enabled = true;
                    glEnableClientState(GL_COLOR_ARRAY);
                }
                //if (_colorArray._pointer!=ptr || _colorArray._dirty)
                {
                    _colorArray._pointer=ptr;
                    glColorPointer( size, type, stride, ptr );
                }
                _colorArray._lazy_disable = false;
                _colorArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_colorAlias._location, size, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_COLOR_ARRAY);
          * note, only updates values that change.*/
        inline void disableColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_colorAlias._location);
            }
            else
            {
                if (_colorArray._enabled || _colorArray._dirty)
                {
                    _colorArray._lazy_disable = false;
                    _colorArray._enabled = false;
                    _colorArray._dirty = false;
                    glDisableClientState(GL_COLOR_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_colorAlias._location);
        #endif
        }

        inline void dirtyColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_colorAlias._location);
            }
            else
            {
                _colorArray._pointer = 0;
                _colorArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_colorAlias._location);
        #endif
        }


        inline bool isSecondaryColorSupported() const { return _isSecondaryColorSupportResolved?_isSecondaryColorSupported:computeSecondaryColorSupported(); }


        /** Set the secondary color pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setSecondaryColorPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_SECONDARY_COLOR_ARRAY);glSecondayColorPointer(..);
          * note, only updates values that change.*/
        void setSecondaryColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr );

        /** wrapper around glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
          * note, only updates values that change.*/
        inline void disableSecondaryColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_secondaryColorAlias._location);
            }
            else
            {
                if (_secondaryColorArray._enabled || _secondaryColorArray._dirty)
                {
                    _secondaryColorArray._lazy_disable = false;
                    _secondaryColorArray._enabled = false;
                    _secondaryColorArray._dirty = false;
                    if (isSecondaryColorSupported()) glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_secondaryColorAlias._location);
        #endif
        }

        inline void dirtySecondaryColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_secondaryColorAlias._location);
            }
            else
            {
                _secondaryColorArray._pointer = 0;
                _secondaryColorArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_secondaryColorAlias._location);
        #endif
        }

        inline bool isFogCoordSupported() const { return _isFogCoordSupportResolved?_isFogCoordSupported:computeFogCoordSupported(); }


        /** Set the fog coord pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setFogCoordPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setFogCoordPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setFogCoordPointer(array->getDataType(),0,array->getDataPointer());
                }
            }
        }


        /** wrapper around glEnableClientState(GL_FOG_COORDINATE_ARRAY);glFogCoordPointer(..);
          * note, only updates values that change.*/
        void setFogCoordPointer( GLenum type, GLsizei stride, const GLvoid *ptr );

        /** wrapper around glDisableClientState(GL_FOG_COORDINATE_ARRAY);
          * note, only updates values that change.*/
        inline void disableFogCoordPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_fogCoordAlias._location);
            }
            else
            {
                if (_fogArray._enabled || _fogArray._dirty)
                {
                    _fogArray._lazy_disable = false;
                    _fogArray._enabled = false;
                    _fogArray._dirty = false;
                    if (isFogCoordSupported()) glDisableClientState(GL_FOG_COORDINATE_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_fogCoordAlias._location);
        #endif