VBO.h 17.2 KB
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
/*
 *	(c) LSIIT, UMR CNRS/UdS
 *	Authors: F. Larue.
 *
 *	See licence.txt for additional information.
 */


#ifndef __GPU__VBO_H__
#define __GPU__VBO_H__




#include "InstantiatedObject.h"
#include "assert.h"
#include <vector>
#include "Shader.h"




namespace GPU
{
    class VBO;

    class VBOBuffer
    {
    private:
        static const GLuint DISABLE_FLAG = 1 << (8*sizeof(GLuint) - 1);

        GLuint      m_BufferId;
        GLenum      m_BufferType;
        GLsizei     m_BufferSize;
        GLenum      m_Type;
        GLsizei     m_TypeSize;

    protected:
        inline bool Alloc()
        {
41
            gpuAssert( glGenBuffersARB( 1, &m_BufferId ) );
42 43 44 45 46
            return (m_BufferId != 0);
        }
        inline bool Destroy()
        {
            m_BufferId &= ~DISABLE_FLAG;
47
            gpuAssert( glDeleteBuffersARB( 1, &m_BufferId ) );
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
            m_BufferId = 0;
            return true;
        }

    public:
        inline      VBOBuffer( GLenum bufferType ) :
            m_BufferId( 0 ),
            m_BufferType( bufferType ),
            m_BufferSize( 0 ),
            m_Type( GL_NONE ),
            m_TypeSize( 0 )
        {
            assert( bufferType == GL_ARRAY_BUFFER  ||  bufferType == GL_ELEMENT_ARRAY_BUFFER );
            Alloc();
        }
        virtual     ~VBOBuffer() { Destroy(); }

        inline void     SetType( GLenum type )                      { m_Type = type; }
        inline GLenum   Type() const                                { return m_Type; }
        inline GLsizei  BufferSize() const                          { return m_BufferSize; }
        inline GLsizei  TypeSize() const                            { return m_TypeSize; }

        inline void Bind()
        {
            if( IsEnabled()  &&  m_BufferId )
73
                gpuAssert( glBindBufferARB( m_BufferType, m_BufferId ) );
74 75 76 77 78 79 80 81 82 83 84
        }
        inline void Unbind()    {}

        template <typename T>
        inline bool LoadData( GLenum usage, T *buffer, GLsizei count )
        {
            if( m_BufferId & ~DISABLE_FLAG )
            {
                m_BufferSize = count;
                m_TypeSize = sizeof(T);

85 86
                gpuAssert( glBindBufferARB( m_BufferType, m_BufferId & ~DISABLE_FLAG ) );
                gpuAssert( glBufferDataARB( m_BufferType, count*m_TypeSize, buffer, usage ) );
87 88
                bool ok = (glGetError() == GL_NO_ERROR);

89
                gpuAssert( glBindBufferARB( m_BufferType, 0 ) );
90

91 92
                //if( !ok )
                //    Destroy();
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

                return ok;
            }
            return false;
        }

        template <typename T>
        inline bool LoadData( GLenum usage, const std::vector<T> &buffer )
        {
            return LoadData( usage, &buffer[0], (GLsizei) buffer.size() );
        }

        inline bool     IsEnabled() const                               { return !IsDisabled(); }
        inline bool     IsDisabled() const                              { return (m_BufferId & DISABLE_FLAG) != 0; }
        inline void     Enable()                                        { m_BufferId &= ~DISABLE_FLAG; }
        inline void     Disable()                                       { m_BufferId |=  DISABLE_FLAG; }
    };


    class VBOAttribBuffer : public VBOBuffer
    {
        GLint       m_Location;
        GLint       m_Dimension;
        GLboolean   m_Normalized;

    public:
        inline VBOAttribBuffer() :
            VBOBuffer( GL_ARRAY_BUFFER ),
            m_Location( -1 ),
            m_Dimension( 0 ),
            m_Normalized( GL_FALSE )
        {}
125 126 127 128 129 130 131
        inline VBOAttribBuffer( GLint dimension, GLenum type, bool normalized = false ) :
            VBOBuffer( GL_ARRAY_BUFFER ),
            m_Dimension( dimension ),
            m_Normalized( normalized )
        {
            SetType( type );
        }
132 133 134 135 136 137 138 139 140 141 142 143 144

        inline void     SetDimension( GLint dim )                   { m_Dimension= dim; }
        inline GLint    Dimension() const                           { return m_Dimension; }
        inline void     SetNormalized( bool normalized )            { m_Normalized = normalized?  GL_TRUE : GL_FALSE; }
        inline bool     IsNormalized() const                        { return m_Normalized == GL_TRUE; }
        inline void     SetLocation( GLint location )               { m_Location = location; }
        inline GLint    Location() const                            { return m_Location; }

        inline void Bind()
        {
            if( this->IsEnabled()  &&  m_Location >= 0 )
            {
                VBOBuffer::Bind();
145 146
                gpuAssert( glEnableVertexAttribArrayARB( m_Location ) );
                gpuAssert( glVertexAttribPointerARB( m_Location, m_Dimension, Type(), m_Normalized, 0, 0 ) );
147 148 149 150 151 152
            }
        }
        inline void Unbind()
        {
            if( this->IsEnabled()  &&  m_Location >= 0 )
            {
153
                gpuAssert( glDisableVertexAttribArrayARB( m_Location ) );
154 155 156 157 158 159 160 161 162 163
                VBOBuffer::Unbind();
            }
        }
    };


    class VBOIndexBuffer : public VBOBuffer
    {
        friend class GPU::VBO;

164 165 166 167 168 169 170
    public:
        inline VBOIndexBuffer() : VBOBuffer( GL_ELEMENT_ARRAY_BUFFER ) {}
        inline VBOIndexBuffer( GLenum type ) : VBOBuffer( GL_ELEMENT_ARRAY_BUFFER )
        {
            SetType( type );
        }

171 172
        inline void DrawElements( GLenum mode, GLint first, GLsizei count )
        {
173
            gpuAssert( glDrawElements(	mode, count, Type(), (char*)NULL + first*TypeSize() ) ); // All this mess to avoid cast compilation warnings...
174 175 176 177
        }

        inline void DrawElements( GLenum mode )
        {
178
            gpuAssert( glDrawElements(	mode, BufferSize(), Type(), NULL ) );
179 180 181 182
        }
    };


Frédéric Larue's avatar
Frédéric Larue committed
183
    class VBO
184 185 186 187 188
    {
        using AttribMap         = std::map< std::string, VBOAttribBuffer >;
        using AttribBindingMap  = std::map< VBOAttribBuffer*, GLint >;

    protected:
Frédéric Larue's avatar
Frédéric Larue committed
189 190
        GLint               m_PrimitiveType;

191 192 193 194 195 196 197
        AttribMap           m_Attrib;
        VBOIndexBuffer      *m_Indices;

        Shader              *m_Shader;
        AttribBindingMap    m_AttribBinding;

    public:
Frédéric Larue's avatar
Frédéric Larue committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        inline      VBO() : 
            m_PrimitiveType( GL_NONE ),
            m_Indices( NULL ),
            m_Shader( NULL )                {}
        inline      ~VBO()                  { Release(); }

        inline void Release()
        {
            m_Attrib.clear();
            RemoveIndices();
            SetShader( NULL );
        }

        inline void     SetPrimitiveType( GLint ptype )     { m_PrimitiveType = ptype; }
        inline GLint    GetPrimitiveType() const            { return m_PrimitiveType; }
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

        inline VBOAttribBuffer* AddAttrib( const std::string &name, GLint dimension, GLenum type, bool normalized = false )
        {
            if( m_Attrib.find(name) == m_Attrib.end() )
            {
                VBOAttribBuffer &attrib = m_Attrib[name];
                attrib.SetDimension( dimension );
                attrib.SetType( type );
                attrib.SetNormalized( normalized );
                return &attrib;
            }
            return NULL;
        }
        inline void RemoveAttrib( const std::string &name )
        {
            auto foundAttrib = m_Attrib.find(name);
            if( foundAttrib != m_Attrib.end() )
                m_Attrib.erase( foundAttrib );
        }
Frédéric Larue's avatar
Frédéric Larue committed
232 233 234 235
        inline void RemoveAllAttrib()
        {
            m_Attrib.clear();
        }
236 237 238 239 240
        inline VBOAttribBuffer* Attrib( const std::string &name )
        {
            auto foundAttrib = m_Attrib.find(name);
            return foundAttrib!=m_Attrib.end()?  &foundAttrib->second  :  NULL;
        }
Frédéric Larue's avatar
Frédéric Larue committed
241 242 243 244 245 246 247 248
        inline bool HasAttrib() const
        {
            return !m_Attrib.empty();
        }
        inline bool HasAttrib( const std::string &name ) const
        {
            return m_Attrib.find(name) != m_Attrib.end();
        }
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
        inline void EnableAllAttributes()
        {
            for( auto &a : m_Attrib )
                a.second.Enable();
        }
        inline void DisableAllAttributes()
        {
            for( auto &a : m_Attrib )
                a.second.Disable();
        }

        inline VBOIndexBuffer* AddIndices( GLenum type )
        {
            m_Indices = new VBOIndexBuffer();
            m_Indices->SetType( type );
            return m_Indices;
        }
        inline void RemoveIndices()
        {
            if( m_Indices )
            {
                delete m_Indices;
                m_Indices = NULL;
            }
        }
        inline VBOIndexBuffer* Indices()            { return m_Indices; }


        inline void SetShader( Shader *shader )     { m_Shader = shader; ClearShaderAttribBindings(); }
        inline GPU::Shader* Shader()                { return m_Shader; }
        inline const GPU::Shader* Shader() const    { return m_Shader; }

        inline void SetShaderAttribBinding( const std::string& shaderAttribName, const std::string vboAttribName )
        {
            SetShaderAttribBinding( shaderAttribName, Attrib(vboAttribName) );
        }

        inline void SetShaderAttribBinding( const std::string& shaderAttribName, VBOAttribBuffer *vboAttrib )
        {
            assert( m_Shader != NULL );
            assert( m_Shader->IsCreated() );
            assert( vboAttrib != NULL );

            GLint loc = m_Shader->AttribLoc( shaderAttribName );
            if( loc >= 0 )
                m_AttribBinding[vboAttrib] = loc;
        }

        inline void RemoveShaderAttribBinding( const std::string vboAttribName )
        {
            RemoveShaderAttribBinding( Attrib(vboAttribName) );
        }

        inline void RemoveShaderAttribBinding( VBOAttribBuffer *vboAttrib )
        {
            m_AttribBinding.erase( vboAttrib );
        }

        inline void ClearShaderAttribBindings()
        {
            m_AttribBinding.clear();
        }

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
        inline void Bind()
        {
            if( m_Shader )
                m_Shader->Bind();

            for( auto a=m_AttribBinding.begin(); a!=m_AttribBinding.end(); ++a )
            {
                a->first->SetLocation( a->second );
                a->first->Bind();
            }

            if( m_Indices )
                m_Indices->Bind();
        }
        inline void Unbind()
        {
            if( m_Shader )
                m_Shader->Unbind();

            for( auto a=m_AttribBinding.begin(); a!=m_AttribBinding.end(); ++a )
                a->first->Unbind();

            gpuAssert( glBindBufferARB( GL_ARRAY_BUFFER, 0 ) );
            gpuAssert( glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 ) );
        }

338 339 340 341 342
        inline void DrawArrays()
        {
            assert( m_PrimitiveType != GL_NONE );
            DrawArrays( m_PrimitiveType, 0, m_Attrib.begin()->second.BufferSize() );
        }
Frédéric Larue's avatar
Frédéric Larue committed
343
        inline void DrawArrays( GLenum mode )   { DrawArrays( mode, 0, m_Attrib.begin()->second.BufferSize() ); }
344 345 346
        inline void DrawArrays( GLenum mode, GLint first, GLsizei count )
        {
            Bind();
347
            gpuAssert( glDrawArrays( mode, first, count ) );
348 349 350
            Unbind();
        }

351 352 353 354 355
        inline void DrawElements()
        {
            assert( m_PrimitiveType != GL_NONE );
            DrawElements( (GLenum) m_PrimitiveType );
        }
Frédéric Larue's avatar
Frédéric Larue committed
356
        inline void DrawElements( GLenum mode )
357
        {
Frédéric Larue's avatar
Frédéric Larue committed
358
            assert( m_Indices );
359
            Bind();
Frédéric Larue's avatar
Frédéric Larue committed
360
            m_Indices->DrawElements( mode );
361 362 363 364 365 366 367 368 369 370
            Unbind();
        }
        inline void DrawElements( GLenum mode, GLint first, GLsizei count )
        {
            assert( m_Indices );
            Bind();
            m_Indices->DrawElements( mode, first, count );
            Unbind();
        }

Frédéric Larue's avatar
Frédéric Larue committed
371
        inline void Draw()
372 373 374 375 376
        {
            assert( m_PrimitiveType != GL_NONE );
            Draw( (GLenum) m_PrimitiveType );
        }
        inline void Draw( GLenum mode )
377
        {
Frédéric Larue's avatar
Frédéric Larue committed
378
            if( Indices() )
379
                DrawElements( mode );
Frédéric Larue's avatar
Frédéric Larue committed
380
            else
381
                DrawArrays( mode );
Frédéric Larue's avatar
Frédéric Larue committed
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
        }
    };


    class VBOBuilder
    {
        struct Vec3
        {
            float v[3];
            inline Vec3() {}
            inline Vec3( float x, float y, float z )
            {
                v[0] = x;
                v[1] = y;
                v[2] = z;
            }
        };

        struct Vec4
        {
            float v[4];
            inline Vec4() {}
            inline Vec4( float x, float y, float z, float w )
            {
                v[0] = x;
                v[1] = y;
                v[2] = z;
                v[3] = w;
            }
        };


        VBO& m_VBO;

        std::string m_VertexAttribName;
        std::string m_TexCoordAttribName;
        std::string m_NormalAttribName;
        std::string m_ColorAttribName;

        std::vector<Vec4> m_Vertices;
        std::vector<Vec4> m_TexCoords;
        std::vector<Vec3> m_Normals;
        std::vector<Vec4> m_Colors;

        Vec4 m_CurrentTexCoords;
        Vec3 m_CurrentNormal;
        Vec4 m_CurrentColor;

        bool m_TexCoordsDefined;
        bool m_NormalsDefined;
        bool m_ColorsDefined;

        GLint m_PrimitiveType;
        GLenum m_Usage;

    public:
        inline VBOBuilder( VBO& vbo, GLenum usage ) :
            m_VBO( vbo ),
            m_Usage( usage ),
            m_TexCoordsDefined( false ),
            m_NormalsDefined( false ),
443 444 445 446
            m_ColorsDefined( false ),
            m_CurrentTexCoords( 0.0f, 0.0f, 0.0f, 1.0f ),
            m_CurrentNormal( 0.0f, 0.0f, 0.0f ),
            m_CurrentColor( 0.0f, 0.0f, 0.0f, 1.0f )
Frédéric Larue's avatar
Frédéric Larue committed
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
        {}

        inline void SetVertexAttribName  ( const std::string &name )    { m_VertexAttribName   = name; }
        inline void SetTexCoordAttribName( const std::string &name )    { m_TexCoordAttribName = name; }
        inline void SetNormalAttribName  ( const std::string &name )    { m_NormalAttribName   = name; }
        inline void SetColorAttribName   ( const std::string &name )    { m_ColorAttribName    = name; }

        inline void Begin( GLint prim )
        {
            m_PrimitiveType = prim;
        }
        inline void End()
        {
            assert( !m_VertexAttribName.empty() );

            m_VBO.AddAttrib( m_VertexAttribName, 4, GL_FLOAT )->LoadData( m_Usage, m_Vertices );

            if( m_TexCoordsDefined  &&  !m_TexCoordAttribName.empty() )
                m_VBO.AddAttrib( m_TexCoordAttribName, 4, GL_FLOAT )->LoadData( m_Usage, m_TexCoords );

            if( m_NormalsDefined  &&  !m_NormalAttribName.empty() )
                m_VBO.AddAttrib( m_NormalAttribName, 3, GL_FLOAT )->LoadData( m_Usage, m_Normals );

            if( m_ColorsDefined  &&  !m_ColorAttribName.empty() )
                m_VBO.AddAttrib( m_ColorAttribName, 4, GL_FLOAT )->LoadData( m_Usage, m_Colors );


            if( m_PrimitiveType == GL_QUADS )
            {
                std::vector<GLuint> indices;
                indices.reserve( 6 * m_Vertices.size() / 4 );

                for( unsigned int i=0; i<m_Vertices.size(); i+=4 )
                {
                    indices.push_back( i+0 );
                    indices.push_back( i+3 );
                    indices.push_back( i+1 );

                    indices.push_back( i+3 );
                    indices.push_back( i+2 );
                    indices.push_back( i+1 );
                }

                m_VBO.AddIndices( GL_UNSIGNED_INT )->LoadData( m_Usage, indices );

                m_PrimitiveType = GL_TRIANGLES;
            }
            else if( m_PrimitiveType == GL_QUAD_STRIP )
                m_PrimitiveType = GL_TRIANGLE_STRIP;

            m_VBO.SetPrimitiveType( m_PrimitiveType );

            m_Vertices  = std::vector<Vec4>();
            m_TexCoords = std::vector<Vec4>();
            m_Normals   = std::vector<Vec3>();
            m_Colors    = std::vector<Vec4>();
        }
        inline void TexCoord( GLfloat x )                                   { TexCoord( x, 0.0f, 0.0f, 1.0f ); }
        inline void TexCoord( GLfloat x, GLfloat y )                        { TexCoord( x,    y, 0.0f, 1.0f ); }
        inline void TexCoord( GLfloat x, GLfloat y, GLfloat z )             { TexCoord( x,    y,    z, 1.0f ); }
        inline void TexCoord( GLfloat x, GLfloat y, GLfloat z, GLfloat w )
        {
            m_TexCoordsDefined = true;
            m_CurrentTexCoords = Vec4( x, y, z, w );
        }
        inline void Normal( GLfloat x, GLfloat y, GLfloat z )
        {
            m_NormalsDefined = true;
            m_CurrentNormal = Vec3( x, y, z );
        }
        inline void Color( GLfloat x, GLfloat y, GLfloat z )                { Color( x, y, z, 1.0f ); }
        inline void Color( GLfloat x, GLfloat y, GLfloat z, GLfloat w )
        {
            m_ColorsDefined = true;
            m_CurrentColor = Vec4( x, y, z, w );
        }
        inline void Vertex( GLfloat x )                                     { Vertex( x, 0.0f, 0.0f, 1.0f ); }
        inline void Vertex( GLfloat x, GLfloat y )                          { Vertex( x,    y, 0.0f, 1.0f ); }
        inline void Vertex( GLfloat x, GLfloat y, GLfloat z )               { Vertex( x,    y,    z, 1.0f ); }
        inline void Vertex( GLfloat x, GLfloat y, GLfloat z, GLfloat w )
        {
            m_Vertices .push_back( Vec4(x,y,z,w) );
            m_TexCoords.push_back( m_CurrentTexCoords );
            m_Normals  .push_back( m_CurrentNormal    );
            m_Colors   .push_back( m_CurrentColor     );
532 533 534 535 536 537 538 539
        }
    };
}; // namespace GPU




#endif /*__GPU__VBO_H__*/