// Copyright (C) 2012-2014 ChaosForge Ltd // This file is part of NV Libraries. // For conditions of distribution and use, see copyright notice in nv.hh #include "nv/gl/gl_device.hh" #include "nv/gl/gl_window.hh" #include "nv/core/logging.hh" #include "nv/lib/sdl.hh" #include "nv/lib/sdl_image.hh" #include "nv/gl/gl_enum.hh" #include "nv/lib/gl.hh" using namespace nv; window* gl_device::create_window( uint16 width, uint16 height, bool fullscreen ) { return new gl_window( this, width, height, fullscreen ); } window* nv::gl_device::adopt_window( void* sys_w_handle, void* sys_dc ) { return new gl_window( this, sys_w_handle, sys_dc ); } gl_device::gl_device() { nv::load_sdl_library(); m_info = NULL; if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) { NV_LOG( LOG_CRITICAL, "Video initialization failed: " << SDL_GetError( ) ); return; // TODO: Error report } #if NV_SDL_VERSION == NV_SDL_12 m_info = SDL_GetVideoInfo( ); if ( !m_info ) { NV_LOG( LOG_CRITICAL, "Video query failed: " << SDL_GetError( ) ); return; // TODO: Error report } #endif m_shader_header = "#version 120\n"; for ( auto& i : get_uniform_factory() ) m_shader_header += "uniform "+datatype_to_glsl_type( i.second->get_datatype() )+" "+i.first+";\n"; for ( auto& i : get_link_uniform_factory() ) m_shader_header += "uniform sampler2D "+i.first+";\n"; } program gl_device::create_program( const string& vs_source, const string& fs_source ) { program result = m_programs.create(); gl_program_info* info = m_programs.get( result ); info->glid = glCreateProgram(); compile( info, vs_source, fs_source ); prepare_program( result ); return result; } // this is a temporary function that will be removed once we find a way to // pass binary file data around image_data* nv::gl_device::create_image_data( const std::string& filename ) { load_sdl_image_library(); SDL_Surface* image = IMG_Load( filename.c_str() ); if (!image) { NV_LOG( LOG_ERROR, "Image file " << filename.c_str() << " not found!" ); return nullptr; } // TODO: BGR vs RGB, single channel assert( image->format->BytesPerPixel > 2 ); image_format format(image->format->BytesPerPixel == 3 ? RGB : RGBA, UBYTE ); image_data* data = new image_data( format, glm::ivec2( image->w, image->h ), (nv::uint8*)image->pixels ); return data; } uint32 gl_device::get_ticks() { return SDL_GetTicks(); } void gl_device::delay( uint32 ms ) { return SDL_Delay( ms ); } gl_device::~gl_device() { while ( m_textures.size() > 0 ) release( m_textures.get_handle(0) ); while ( m_buffers.size() > 0 ) release( m_buffers.get_handle(0) ); while ( m_programs.size() > 0 ) release( m_programs.get_handle(0) ); SDL_Quit(); } nv::texture nv::gl_device::create_texture( ivec2 size, image_format aformat, sampler asampler, void* data /*= nullptr */ ) { unsigned glid = 0; glGenTextures( 1, &glid ); glBindTexture( GL_TEXTURE_2D, glid ); // Detect if mipmapping was requested if (( asampler.filter_min != sampler::LINEAR && asampler.filter_min != sampler::NEAREST ) || ( asampler.filter_max != sampler::LINEAR && asampler.filter_max != sampler::NEAREST )) { glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); } glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_min ) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_max ) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (int)nv::sampler_wrap_to_enum( asampler.wrap_s) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (int)nv::sampler_wrap_to_enum( asampler.wrap_t) ); if (data) { 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 ); } glBindTexture( GL_TEXTURE_2D, 0 ); texture result = m_textures.create(); gl_texture_info* info = m_textures.get( result ); info->format = aformat; info->sampler = asampler; info->size = size; info->glid = glid; return result; } void nv::gl_device::release( texture t ) { gl_texture_info* info = m_textures.get( t ); if ( info ) { if ( info->glid != 0 ) { glDeleteTextures( 1, &(info->glid) ); } m_textures.destroy( t ); } } void nv::gl_device::release( buffer b ) { gl_buffer_info* info = m_buffers.get( b ); if ( info ) { if ( info->glid != 0 ) { glDeleteBuffers( 1, &(info->glid) ); } m_buffers.destroy( b ); } } const texture_info* nv::gl_device::get_texture_info( texture t ) const { return m_textures.get( t ); } nv::buffer nv::gl_device::create_buffer( buffer_type type, buffer_hint hint, size_t size, const void* source /*= nullptr */ ) { unsigned glid = 0; unsigned glenum = buffer_type_to_enum( type ); glGenBuffers( 1, &glid ); glBindBuffer( glenum, glid ); glBufferData( glenum, (GLsizeiptr)size, source, buffer_hint_to_enum( hint ) ); glBindBuffer( glenum, 0 ); buffer result = m_buffers.create(); gl_buffer_info* info = m_buffers.get( result ); info->type = type; info->hint = hint; info->size = size; info->glid = glid; return result; } const buffer_info* nv::gl_device::get_buffer_info( buffer t ) const { return m_buffers.get( t ); } void nv::gl_device::release( program p ) { gl_program_info* info = m_programs.get( p ); if ( info ) { for ( auto& i : info->m_uniform_map ) delete i.second; glDetachShader( info->glid, info->glidv ); glDetachShader( info->glid, info->glidf ); glDeleteShader( info->glidv ); glDeleteShader( info->glidf ); glDeleteProgram( info->glid ); m_programs.destroy( p ); } } void nv::gl_device::prepare_program( program p ) { gl_program_info* info = m_programs.get( p ); if ( info ) { auto& map = get_uniform_factory(); auto& lmap = get_link_uniform_factory(); for ( auto& i : info->m_uniform_map ) { auto j = lmap.find( i.first ); if ( j != lmap.end() ) { j->second->set( i.second ); } auto k = map.find( i.first ); if ( k != map.end() ) { info->m_engine_uniforms.push_back( k->second->create( i.second ) ); } } } } uniform_base* nv::gl_device::get_uniform( program p, const string& name, bool fatal /*= true */ ) const { const gl_program_info* info = m_programs.get( p ); { uniform_map::const_iterator i = info->m_uniform_map.find( name ); if ( i != info->m_uniform_map.end() ) { return i->second; } if ( fatal ) { NV_LOG( LOG_ERROR, "Uniform '" << name << "' not found in program!" ); NV_THROW( runtime_error, ( "Uniform '"+name+"' not found!" ) ); } } return nullptr; } int nv::gl_device::get_attribute_location( program p, const string& name, bool fatal /*= true */ ) const { const gl_program_info* info = m_programs.get( p ); if ( info ) { attribute_map::const_iterator i = info->m_attribute_map.find( name ); if ( i != info->m_attribute_map.end() ) { return i->second.location; } if ( fatal ) { NV_LOG( LOG_ERROR, "Attribute '" << name << "' not found in program!" ); NV_THROW( runtime_error, ( "Attribute '"+name+"' not found!" ) ); } } return -1; } bool nv::gl_device::compile( gl_program_info* p, const string& vertex_program, const string& fragment_program ) { if (!compile( GL_VERTEX_SHADER, vertex_program, p->glidv )) { return false; } if (!compile( GL_FRAGMENT_SHADER, fragment_program, p->glidf )) { return false; } glBindAttribLocation( p->glid, static_cast( slot::POSITION ), "nv_position" ); glBindAttribLocation( p->glid, static_cast( slot::TEXCOORD ), "nv_texcoord" ); glBindAttribLocation( p->glid, static_cast( slot::NORMAL ), "nv_normal" ); glBindAttribLocation( p->glid, static_cast( slot::COLOR ), "nv_color" ); glBindAttribLocation( p->glid, static_cast( slot::TANGENT ), "nv_tangent" ); glBindAttribLocation( p->glid, static_cast( slot::BONEINDEX ), "nv_boneindex" ); glBindAttribLocation( p->glid, static_cast( slot::BONEWEIGHT ), "nv_boneweight"); glAttachShader( p->glid, p->glidf ); glAttachShader( p->glid, p->glidv ); glLinkProgram( p->glid ); const uint32 buffer_size = 2048; char buffer[ buffer_size ] = { 0 }; int length; int status; glGetProgramiv( p->glid, GL_LINK_STATUS, &status ); glGetProgramInfoLog( p->glid, buffer_size, &length, buffer ); NV_LOG( LOG_INFO, "Program #" << p->glid << (status == GL_FALSE ? " failed to compile!" : " compiled successfully.") ); if ( length > 0 ) { NV_LOG( LOG_INFO, "Program #" << p->glid << " log: " << buffer ); } if ( status == GL_FALSE ) { return false; } glValidateProgram( p->glid ); glGetProgramiv( p->glid, GL_VALIDATE_STATUS, &status ); if ( status == GL_FALSE ) { glGetProgramInfoLog( p->glid, buffer_size, &length, buffer ); NV_LOG( LOG_ERROR, "Program #" << p->glid << " validation error : " << buffer ); return false; } load_attributes( p ); load_uniforms( p ); return true; } void nv::gl_device::update_uniforms( gl_program_info* p ) { for ( uniform_map::iterator i = p->m_uniform_map.begin(); i != p->m_uniform_map.end(); ++i ) { uniform_base* ubase = i->second; if ( ubase->is_dirty() ) { int uloc = ubase->get_location(); switch( ubase->get_type() ) { case FLOAT : glUniform1fv( uloc, ubase->get_length(), ((uniform< enum_to_type< FLOAT >::type >*)( ubase ))->get_value() ); break; case INT : glUniform1iv( uloc, ubase->get_length(), ((uniform< enum_to_type< INT >::type >*)( ubase ))->get_value() ); break; case FLOAT_VECTOR_2 : glUniform2fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_2 >::type >*)( ubase ))->get_value()); break; case FLOAT_VECTOR_3 : glUniform3fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_3 >::type >*)( ubase ))->get_value()); break; case FLOAT_VECTOR_4 : glUniform4fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_4 >::type >*)( ubase ))->get_value()); break; case INT_VECTOR_2 : glUniform2iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_2 >::type >*)( ubase ))->get_value()); break; case INT_VECTOR_3 : glUniform3iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_3 >::type >*)( ubase ))->get_value()); break; case INT_VECTOR_4 : glUniform4iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_4 >::type >*)( ubase ))->get_value()); break; case FLOAT_MATRIX_2 : glUniformMatrix2fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_2 >::type >*)( ubase ))->get_value()); break; case FLOAT_MATRIX_3 : glUniformMatrix3fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_3 >::type >*)( ubase ))->get_value()); break; case FLOAT_MATRIX_4 : glUniformMatrix4fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_4 >::type >*)( ubase ))->get_value()); break; default : break; // error? } ubase->clean(); } } } void nv::gl_device::load_attributes( gl_program_info* p ) { int params; glGetProgramiv( p->glid, GL_ACTIVE_ATTRIBUTES, ¶ms ); for ( unsigned i = 0; i < (unsigned)params; ++i ) { int attr_nlen; int attr_len; unsigned attr_type; char name_buffer[128]; glGetActiveAttrib( p->glid, i, 128, &attr_nlen, &attr_len, &attr_type, name_buffer ); string name( name_buffer, size_t(attr_nlen) ); // skip built-ins if ( name.substr(0,3) == "gl_" ) continue; int attr_loc = glGetAttribLocation( p->glid, name.c_str() ); attribute& attr = p->m_attribute_map[ name ]; attr.name = name; attr.location = attr_loc; attr.type = gl_enum_to_datatype( attr_type ); attr.length = attr_len; } } void nv::gl_device::load_uniforms( gl_program_info* p ) { int params; glGetProgramiv( p->glid, GL_ACTIVE_UNIFORMS, ¶ms ); for ( unsigned i = 0; i < size_t(params); ++i ) { int uni_nlen; int uni_len; unsigned uni_type; char name_buffer[128]; glGetActiveUniform( p->glid, i, 128, &uni_nlen, &uni_len, &uni_type, name_buffer ); string name( name_buffer, size_t(uni_nlen) ); // skip built-ins if ( name.substr(0,3) == "gl_" ) continue; int uni_loc = glGetUniformLocation( p->glid, name.c_str() ); datatype utype = gl_enum_to_datatype( uni_type ); // check for array string::size_type arrchar = name.find('['); if ( arrchar != string::npos ) { name = name.substr( 0, arrchar ); } uniform_base* u = uniform_base::create( utype, name, uni_loc, uni_len ); NV_ASSERT( u, "Unknown uniform type!" ); p->m_uniform_map[ name ] = u; } } bool nv::gl_device::compile( uint32 sh_type, const std::string& shader_code, unsigned& glid ) { glid = glCreateShader( sh_type ); const char* pc = shader_code.c_str(); glShaderSource( glid, 1, &pc, 0 ); glCompileShader( glid ); const uint32 buffer_size = 1024; char buffer[ buffer_size ] = { 0 }; int length; int compile_ok = GL_FALSE; glGetShaderiv(glid, GL_COMPILE_STATUS, &compile_ok); glGetShaderInfoLog( glid, buffer_size, &length, buffer ); if ( length > 0 ) { if ( compile_ok == 0 ) { NV_LOG( LOG_ERROR, "Shader #" << glid << " error: " << buffer ); } else { NV_LOG( LOG_INFO, "Shader #" << glid << " compiled successfully: " << buffer ); } } else { NV_LOG( LOG_INFO, "Shader #" << glid << " compiled successfully." ); } return compile_ok != 0; }