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

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