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

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