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

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