source: trunk/src/gl/gl_device.cc @ 392

Last change on this file since 392 was 392, checked in by epyon, 10 years ago
  • massive shift towards nova STL
  • include cleanups


File size: 13.8 KB
Line 
1// Copyright (C) 2012-2014 ChaosForge Ltd
2// This file is part of NV Libraries.
3// For conditions of distribution and use, see copyright notice in nv.hh
4
5#include "nv/gl/gl_device.hh"
6
7#include "nv/gl/gl_window.hh"
8#include "nv/core/logging.hh"
9#include "nv/lib/sdl_image.hh"
10#include "nv/gl/gl_enum.hh"
11#include "nv/lib/gl.hh"
12
13using namespace nv;
14
15gl_device::gl_device()
16{
17        m_shader_header  = "#version 120\n";
18        for ( auto& i : get_uniform_factory() )
19                m_shader_header += "uniform "+datatype_to_glsl_type( i.second->get_datatype() )+" "+ i.first.to_string() +";\n";
20        for ( auto& i : get_link_uniform_factory() )
21                m_shader_header += "uniform sampler2D "+i.first.to_string() +";\n";
22}
23
24program gl_device::create_program( string_ref vs_source, string_ref fs_source )
25{
26        program result = m_programs.create();
27        gl_program_info* info = m_programs.get( result );
28
29        info->m_attribute_map   = new attribute_map;
30        info->m_engine_uniforms = new engine_uniform_list;
31        info->m_uniform_map     = new uniform_map;
32
33        info->glid = glCreateProgram();
34        compile( info, vs_source, fs_source );
35        prepare_program( result );
36        return result;
37}
38
39// this is a temporary function that will be removed once we find a way to
40// pass binary file data around
41image_data* gl_device::create_image_data( string_ref filename )
42{
43        load_sdl_image_library();
44        SDL_Surface* image = IMG_Load( filename.data() );
45        if (!image)
46        {
47                NV_LOG_ERROR( "Image file ", filename, " not found!" );
48                return nullptr;
49        }
50        // TODO: BGR vs RGB, single channel
51        assert( image->format->BytesPerPixel > 2 );
52        image_format format(image->format->BytesPerPixel == 3 ? RGB : RGBA, UBYTE );
53        image_data* data = new image_data( format, glm::ivec2( image->w, image->h ), (nv::uint8*)image->pixels );
54        return data;
55}
56
57// this is a temporary function that will be removed once we find a way to
58// pass binary file data around
59image_data* gl_device::create_image_data( const uint8* data, uint32 size )
60{
61        load_sdl_image_library();
62        SDL_Surface* image = IMG_LoadTyped_RW( SDL_RWFromMem( (void*)data, (int)size ), 1, "png" );
63        if ( !image )
64        {
65                NV_LOG_ERROR( "Image binary data cannot be loaded found!" );
66                return nullptr;
67        }
68        // TODO: BGR vs RGB, single channel
69        assert( image->format->BytesPerPixel > 2 );
70        image_format format( image->format->BytesPerPixel == 3 ? RGB : RGBA, UBYTE );
71        image_data* idata = new image_data( format, glm::ivec2( image->w, image->h ), ( nv::uint8* )image->pixels );
72        return idata;
73}
74
75
76gl_device::~gl_device()
77{
78        while ( m_textures.size() > 0 )
79                release( m_textures.get_handle(0) );
80        while ( m_buffers.size() > 0 )
81                release( m_buffers.get_handle(0) );
82        while ( m_programs.size() > 0 )
83                release( m_programs.get_handle(0) );
84}
85
86nv::texture nv::gl_device::create_texture( texture_type type, ivec2 size, image_format aformat, sampler asampler, void* data /*= nullptr */ )
87{
88        unsigned glid = 0;
89        unsigned gl_type = texture_type_to_enum( type );
90        glGenTextures( 1, &glid );
91
92        glBindTexture( gl_type, glid );
93
94        // Detect if mipmapping was requested
95        if ( gl_type == GL_TEXTURE_2D && asampler.filter_min != sampler::LINEAR && asampler.filter_min != sampler::NEAREST )
96        {
97                // TODO: This should not be done if we use framebuffers!
98                glTexParameteri( gl_type, GL_GENERATE_MIPMAP, GL_TRUE);
99        }
100
101        if ( asampler.filter_max != sampler::NEAREST )
102        {
103                asampler.filter_max = sampler::LINEAR;
104        }
105
106        glTexParameteri( gl_type, GL_TEXTURE_MIN_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_min ) );
107        glTexParameteri( gl_type, GL_TEXTURE_MAG_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_max ) );
108        glTexParameteri( gl_type, GL_TEXTURE_WRAP_S, (int)nv::sampler_wrap_to_enum( asampler.wrap_s) );
109        glTexParameteri( gl_type, GL_TEXTURE_WRAP_T, (int)nv::sampler_wrap_to_enum( asampler.wrap_t) );
110
111        glTexImage2D( gl_type, 0, (GLint)nv::image_format_to_internal_enum(aformat.format), size.x, size.y, 0, nv::image_format_to_enum(aformat.format), nv::datatype_to_gl_enum(aformat.type), data );
112
113        glBindTexture( gl_type, 0 );
114
115        texture result = m_textures.create();
116        gl_texture_info* info = m_textures.get( result );
117        info->type     = type;
118        info->format   = aformat;
119        info->tsampler = asampler;
120        info->size     = size;
121        info->glid     = glid;
122        return result;
123}
124
125void nv::gl_device::release( texture t )
126{
127        gl_texture_info* info = m_textures.get( t );
128        if ( info )
129        {
130                if ( info->glid != 0 )
131                {
132                        glDeleteTextures( 1, &(info->glid) );
133                }
134                m_textures.destroy( t );
135        }
136}
137
138void nv::gl_device::release( buffer b )
139{
140        gl_buffer_info* info = m_buffers.get( b );
141        if ( info )
142        {
143                if ( info->glid != 0 )
144                {
145                        glDeleteBuffers( 1, &(info->glid) );
146                }
147                m_buffers.destroy( b );
148        }
149}
150
151const texture_info* nv::gl_device::get_texture_info( texture t ) const
152{
153        return m_textures.get( t );
154}
155
156nv::buffer nv::gl_device::create_buffer( buffer_type type, buffer_hint hint, size_t size, const void* source /*= nullptr */ )
157{
158        unsigned glid   = 0;
159        unsigned glenum = buffer_type_to_enum( type );
160        glGenBuffers( 1, &glid );
161
162        glBindBuffer( glenum, glid );
163        glBufferData( glenum, (GLsizeiptr)size, source, buffer_hint_to_enum( hint ) );
164        glBindBuffer( glenum, 0 );
165
166        buffer result = m_buffers.create();
167        gl_buffer_info* info = m_buffers.get( result );
168        info->type = type;
169        info->hint = hint;
170        info->size = size;
171        info->glid = glid;
172        return result;
173}
174
175const buffer_info* nv::gl_device::get_buffer_info( buffer t ) const
176{
177        return m_buffers.get( t );
178}
179
180void nv::gl_device::release( program p )
181{
182        gl_program_info* info = m_programs.get( p );
183        if ( info )
184        {
185                for ( auto& i : *info->m_uniform_map )
186                        delete i.second;
187
188                glDetachShader( info->glid, info->glidv );
189                glDetachShader( info->glid, info->glidf );
190                glDeleteShader( info->glidv );
191                glDeleteShader( info->glidf );
192                glDeleteProgram( info->glid );
193
194                delete info->m_attribute_map;
195                delete info->m_engine_uniforms;
196                delete info->m_uniform_map;
197
198                m_programs.destroy( p );
199        }
200}
201
202void nv::gl_device::prepare_program( program p )
203{
204        gl_program_info* info = m_programs.get( p );
205        if ( info )
206        {
207                auto& map  = get_uniform_factory();
208                auto& lmap = get_link_uniform_factory();
209
210                for ( auto& i : *info->m_uniform_map )
211                {
212                        auto j = lmap.find( i.first );
213                        if ( j != lmap.end() )
214                        {
215                                j->second->set( i.second );
216                        }                       
217
218                        auto k = map.find( i.first );
219                        if ( k != map.end() )
220                        {
221                                info->m_engine_uniforms->push_back( k->second->create( i.second ) );
222                        }                               
223                }
224        }
225}
226
227uniform_base* nv::gl_device::get_uniform( program p, const std::string& name, bool fatal /*= true */ ) const
228{
229        const gl_program_info* info = m_programs.get( p );
230        {
231                nv::uniform_map::const_iterator i = info->m_uniform_map->find( name );
232                if ( i != info->m_uniform_map->end() )
233                {
234                        return i->second;
235                }
236                if ( fatal )
237                {
238                        NV_LOG_ERROR( "Uniform '", name, "' not found in program!" );
239                        NV_THROW( runtime_error, ( "Uniform '"+name+"' not found!" ) );
240                }
241        }
242        return nullptr;
243}
244
245int nv::gl_device::get_attribute_location( program p, const std::string& name, bool fatal /*= true */ ) const
246{
247        const gl_program_info* info = m_programs.get( p );
248        if ( info )
249        {
250                attribute_map::const_iterator i = info->m_attribute_map->find( name );
251                if ( i != info->m_attribute_map->end() )
252                {
253                        return i->second.location;
254                }
255                if ( fatal )
256                {
257                        NV_LOG_ERROR( "Attribute '", name, "' not found in program!" );
258                        NV_THROW( runtime_error, ( "Attribute '"+ name + "' not found!" ) );
259                }
260        }
261        return -1;
262}
263
264bool nv::gl_device::compile( gl_program_info* p, string_ref vertex_program, string_ref fragment_program )
265{
266        if (!compile( GL_VERTEX_SHADER,   vertex_program, p->glidv ))   { return false; }
267        if (!compile( GL_FRAGMENT_SHADER, fragment_program, p->glidf )) { return false; }
268
269        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::POSITION   ), "nv_position"  );
270        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TEXCOORD   ), "nv_texcoord"  );
271        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::NORMAL     ), "nv_normal"    );
272        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::COLOR      ), "nv_color"     );
273        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TANGENT    ), "nv_tangent"   );
274        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEINDEX  ), "nv_boneindex" );
275        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEWEIGHT ), "nv_boneweight");
276
277        glAttachShader( p->glid, p->glidf );
278        glAttachShader( p->glid, p->glidv );
279        glLinkProgram( p->glid );
280
281        const uint32 buffer_size = 2048;
282        char buffer[ buffer_size ] = { 0 };
283        int length;
284        int status;
285
286        glGetProgramiv( p->glid, GL_LINK_STATUS, &status );
287        glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
288
289        NV_LOG_INFO( "Program #", p->glid, (status == GL_FALSE ? " failed to compile!" : " compiled successfully.") );
290
291        if ( length > 0 )
292        {
293                NV_LOG_INFO( "Program #", p->glid, " log: ", buffer );
294        }
295
296        if ( status == GL_FALSE )
297        {
298                return false;
299        }
300
301        glValidateProgram( p->glid );
302        glGetProgramiv( p->glid, GL_VALIDATE_STATUS, &status );
303
304        if ( status == GL_FALSE )
305        {
306                glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
307                NV_LOG_ERROR( "Program #", p->glid, " validation error : ", buffer );
308                return false;
309        }
310        load_attributes( p );
311        load_uniforms( p );
312        return true;
313}
314
315void nv::gl_device::update_uniforms( gl_program_info* p )
316{
317        for ( auto& i : *p->m_uniform_map )
318        {
319                uniform_base* ubase = i.second;
320                if ( ubase->is_dirty() )
321                {
322                        int uloc = ubase->get_location();
323                        switch( ubase->get_type() )
324                        {
325                        case FLOAT          : glUniform1fv( uloc, ubase->get_length(), ((uniform< enum_to_type< FLOAT >::type >*)( ubase ))->get_value() ); break;
326                        case INT            : glUniform1iv( uloc, ubase->get_length(), ((uniform< enum_to_type< INT >::type >*)( ubase ))->get_value() ); break;
327                        case FLOAT_VECTOR_2 : glUniform2fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_2 >::type >*)( ubase ))->get_value()); break;
328                        case FLOAT_VECTOR_3 : glUniform3fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_3 >::type >*)( ubase ))->get_value()); break;
329                        case FLOAT_VECTOR_4 : glUniform4fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_4 >::type >*)( ubase ))->get_value()); break;
330                        case INT_VECTOR_2   : glUniform2iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_2 >::type >*)( ubase ))->get_value()); break;
331                        case INT_VECTOR_3   : glUniform3iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_3 >::type >*)( ubase ))->get_value()); break;
332                        case INT_VECTOR_4   : glUniform4iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_4 >::type >*)( ubase ))->get_value()); break;
333                        case FLOAT_MATRIX_2 : glUniformMatrix2fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_2 >::type >*)( ubase ))->get_value()); break;
334                        case FLOAT_MATRIX_3 : glUniformMatrix3fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_3 >::type >*)( ubase ))->get_value()); break;
335                        case FLOAT_MATRIX_4 : glUniformMatrix4fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_4 >::type >*)( ubase ))->get_value()); break;
336                        default : break; // error?
337                        }
338                        ubase->clean();
339                }
340        }
341}
342
343void nv::gl_device::load_attributes( gl_program_info* p )
344{
345        int params;
346        glGetProgramiv( p->glid, GL_ACTIVE_ATTRIBUTES, &params );
347
348        for ( unsigned i = 0; i < (unsigned)params; ++i )
349        {
350                int attr_nlen;
351                int attr_len;
352                unsigned attr_type;
353                char name_buffer[128];
354
355                glGetActiveAttrib( p->glid, i, 128, &attr_nlen, &attr_len, &attr_type, name_buffer );
356
357                std::string name( name_buffer, size_t( attr_nlen ) );
358
359                // skip built-ins
360                if ( name.substr(0,3) == "gl_" ) continue;
361
362                int attr_loc = glGetAttribLocation( p->glid, name.c_str() );
363
364                attribute& attr = (*p->m_attribute_map)[ name ];
365                attr.name     = name;
366                attr.location = attr_loc;
367                attr.type     = gl_enum_to_datatype( attr_type );
368                attr.length   = attr_len;
369        }
370}
371
372void nv::gl_device::load_uniforms( gl_program_info* p )
373{
374        int params;
375        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORMS, &params );
376
377        for ( unsigned i = 0; i < size_t(params); ++i )
378        {
379                int uni_nlen;
380                int uni_len;
381                unsigned uni_type;
382                char name_buffer[128];
383
384                glGetActiveUniform( p->glid, i, 128, &uni_nlen, &uni_len, &uni_type, name_buffer );
385
386                std::string name( name_buffer, size_t( uni_nlen ) );
387
388                // skip built-ins
389                if ( name.substr(0,3) == "gl_" ) continue;
390
391                int uni_loc = glGetUniformLocation( p->glid, name.c_str() );
392                datatype utype = gl_enum_to_datatype( uni_type );
393
394                // check for array
395                std::string::size_type arrchar = name.find( '[' );
396                if ( arrchar != std::string::npos )
397                {
398                        name = name.substr( 0, arrchar );
399                }
400
401                uniform_base* u = uniform_base::create( utype, name, uni_loc, uni_len );
402                NV_ASSERT( u, "Unknown uniform type!" );
403                (*p->m_uniform_map)[ name ] = u;
404        }
405}
406
407bool nv::gl_device::compile( uint32 sh_type, string_ref shader_code, unsigned& glid )
408{
409        glid = glCreateShader( sh_type );
410
411        const char* pc = shader_code.data();
412        int l = (int)shader_code.length();
413
414        glShaderSource( glid, 1, &pc, &l );
415        glCompileShader( glid );
416
417        const uint32 buffer_size = 1024;
418        char buffer[ buffer_size ] = { 0 };
419        int length;
420        int compile_ok = GL_FALSE;
421        glGetShaderiv(glid, GL_COMPILE_STATUS, &compile_ok);
422        glGetShaderInfoLog( glid, buffer_size, &length, buffer );
423
424        if ( length > 0 )
425        {
426                if ( compile_ok == 0 )
427                {
428                        NV_LOG_ERROR( "Shader #", glid, " error: ", buffer );
429                }
430                else
431                {
432                        NV_LOG_INFO( "Shader #", glid, " compiled successfully: ", buffer );
433                }
434        }
435        else
436        {
437                NV_LOG_INFO( "Shader #", glid, " compiled successfully." );
438        }
439        return compile_ok != 0;
440
441}
442
Note: See TracBrowser for help on using the repository browser.