source: trunk/src/gl/gl_context.cc @ 538

Last change on this file since 538 was 535, checked in by epyon, 8 years ago
  • unified pixel_format instead of image_format
File size: 36.3 KB
Line 
1// Copyright (C) 2012-2017 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_context.hh"
8
9#include "nv/gl/gl_enum.hh"
10#include "nv/lib/gl.hh"
11#include "nv/gl/gl_device.hh"
12#include "nv/core/logger.hh"
13
14using namespace nv;
15
16nv::vertex_array nv::gl_context::create_vertex_array( const vertex_array_desc& desc )
17{
18        vertex_array result = m_vertex_arrays.create();
19        gl_vertex_array_info* info = m_vertex_arrays.get( result );
20
21        glGenVertexArrays( 1, &info->glid );
22        info->count       = desc.count;
23        info->index       = desc.index;
24        info->index_owner = desc.index_owner;
25        info->index_type  = desc.index_type;
26
27        for ( uint32 i = 0; i < desc.count; ++i )
28                info->attr[i] = desc.attr[i];
29
30        glBindVertexArray( info->glid );
31
32        for ( uint32 i = 0; i < info->count; ++i )
33        {
34                const vertex_buffer_attribute& vba = info->attr[i];
35                uint32 location = static_cast<uint32>( vba.location );
36                glEnableVertexAttribArray( location );
37                const gl_buffer_info* vinfo = static_cast<const gl_buffer_info*>( m_device->get_buffer_info( vba.vbuffer ) );
38                if ( vinfo && vinfo->type == VERTEX_BUFFER )
39                        glBindBuffer( GL_ARRAY_BUFFER, vinfo->glid );
40                else
41                {
42                        // TODO: report error
43                }
44
45                glVertexAttribPointer(
46                        location,
47                        static_cast<GLint>( vba.components ),
48                        nv::datatype_to_gl_enum( vba.dtype ),
49                        GL_FALSE,
50                        static_cast<GLsizei>( vba.stride ),
51                        reinterpret_cast<void*>( vba.offset )
52                        );
53        }
54        glBindBuffer( GL_ARRAY_BUFFER, 0 );
55
56        if ( info->index.is_valid() )
57        {
58                const gl_buffer_info* iinfo = static_cast<const gl_buffer_info*>( m_device->get_buffer_info( info->index ) );
59                if ( iinfo && iinfo->type == INDEX_BUFFER )
60                {
61                        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, iinfo->glid );
62                }
63                else
64                {
65                        // TODO: report error
66                }
67        }
68        glBindVertexArray( 0 );
69
70        if ( info->index.is_valid() )
71        {
72                glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
73        }
74
75//      for ( uint32 i = 0; i < info->count; ++i )
76//      {
77//              glDisableVertexAttribArray( static_cast<uint32>( info->attr[i].location ) );
78//      }
79
80
81        return result;
82}
83
84nv::framebuffer nv::gl_context::create_framebuffer( uint32 temp_samples )
85{
86        unsigned glid   = 0;
87        glGenFramebuffers( 1, &glid );
88        framebuffer result = m_framebuffers.create();
89        gl_framebuffer_info* info = m_framebuffers.get( result );
90        info->glid = glid;
91        info->depth_rb_glid = 0;
92        info->color_attachment_count = 0;
93        info->sample_count = temp_samples;
94        return result;
95}
96
97void nv::gl_context::release( vertex_array va )
98{
99        gl_vertex_array_info* info = m_vertex_arrays.get( va );
100        if ( info )
101        {
102                for ( uint32 i = 0; i < info->count; ++i )
103                {
104                        if ( info->attr[i].owner )
105                                release( info->attr[i].vbuffer );
106                }
107                if ( info->index.is_valid() && info->index_owner) release( info->index );
108                glDeleteVertexArrays( 1, &info->glid );
109                m_vertex_arrays.destroy( va );
110        }
111}
112
113void nv::gl_context::release( framebuffer f )
114{
115        gl_framebuffer_info* info = m_framebuffers.get( f );
116        if ( info )
117        {
118                // TODO: release textures?
119                glBindFramebuffer( GL_FRAMEBUFFER, 0 );
120                glBindRenderbuffer( GL_RENDERBUFFER, 0 );
121                if ( info->depth_rb_glid == 0 )
122                        glDeleteRenderbuffers( 1, &info->depth_rb_glid );
123                glDeleteFramebuffers( 1, &info->glid );
124                m_framebuffers.destroy( f );
125        }
126}
127
128nv::image_data* nv::gl_context::dump_image( pixel_format format, image_data* reuse )
129{
130        NV_ASSERT_ALWAYS( format == nv::RGB8 || format == nv::RGBA8, "Bad format passed to dump" );
131        glPixelStorei( GL_PACK_ALIGNMENT, 1 );
132        image_data* result = reuse;
133        datatype type = get_pixel_format_info( format ).type;
134        if ( !result ) result = new image_data( format, ivec2( m_viewport.z, m_viewport.w ) );
135        glReadPixels( 0, 0, m_viewport.z, m_viewport.w, format == nv::RGB8 ? GL_RGB : GL_RGBA, datatype_to_gl_enum( type ), const_cast< uint8* >( result->get_data() ) );
136        return result;
137}
138
139
140const framebuffer_info* nv::gl_context::get_framebuffer_info( framebuffer f ) const
141{
142        return m_framebuffers.get( f );
143}
144
145void nv::gl_context::attach( framebuffer f, output_slot slot, texture t, int layer /* = -1*/ )
146{
147        // TODO: framebuffer variable, so no re-binding?
148        // TODO: support 1d, 3d textures, cubemaps or layers?
149        // TODO: support GL_READ_FRAMEBUFFER?
150        const gl_framebuffer_info* info  = m_framebuffers.get( f );
151        const gl_texture_info*     tinfo = static_cast< const gl_texture_info* >( m_device->get_texture_info( t ) );
152        if ( info )
153        {
154                glBindFramebuffer( GL_FRAMEBUFFER, info->glid );
155                unsigned gl_type = texture_type_to_enum( tinfo->type );
156                unsigned tglid = tinfo ? tinfo->glid : 0;
157
158                if ( layer >= 0 )
159                {
160                        glFramebufferTextureLayer( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + unsigned( slot ), tglid, 0, layer );
161                }
162                else
163                {
164                        glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + unsigned( slot ), gl_type, tglid, 0 );
165                }
166
167        }
168}
169
170void nv::gl_context::attach( framebuffer f, texture depth, int layer /*= -1*/ )
171{
172        // TODO: framebuffer variable, so no re-binding?
173        // TODO: support GL_READ_FRAMEBUFFER?
174        const gl_framebuffer_info* info  = m_framebuffers.get( f );
175        const gl_texture_info*     tinfo = static_cast< const gl_texture_info* >( m_device->get_texture_info( depth ) );
176        if ( info )
177        {
178                glBindFramebuffer( GL_FRAMEBUFFER, info->glid );
179                unsigned gl_type = texture_type_to_enum( tinfo->type );
180                unsigned glid = ( tinfo ? tinfo->glid : 0 );
181                if ( layer >= 0 )
182                {
183                        glFramebufferTextureLayer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, glid, 0, layer );
184                }
185                else
186                {
187                        glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gl_type, glid, 0 );
188                }
189        }
190
191}
192
193void nv::gl_context::attach( framebuffer f, ivec2 size )
194{
195        // TODO: framebuffer variable, so no re-binding?
196        // TODO: support GL_READ_FRAMEBUFFER?
197        gl_framebuffer_info* info  = m_framebuffers.get( f );
198        if ( info )
199        {
200                glBindFramebuffer( GL_FRAMEBUFFER, info->glid );
201                if ( info->depth_rb_glid )
202                        glDeleteRenderbuffers( 1, &(info->depth_rb_glid) );
203                glGenRenderbuffers( 1, &(info->depth_rb_glid) );
204                glBindRenderbuffer( GL_RENDERBUFFER, info->depth_rb_glid );
205                if ( info->sample_count > 1 )
206                        glRenderbufferStorageMultisample( GL_RENDERBUFFER, info->sample_count, GL_DEPTH_COMPONENT16, size.x, size.y );
207                else
208                        glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, size.x, size.y );
209                glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, info->depth_rb_glid );
210                glBindRenderbuffer( GL_RENDERBUFFER, 0 );
211        }
212
213}
214
215void nv::gl_context::attach_depth( framebuffer source, framebuffer target )
216{
217        gl_framebuffer_info* sinfo = m_framebuffers.get( source );
218        gl_framebuffer_info* tinfo = m_framebuffers.get( target );
219
220        if ( sinfo && tinfo )
221        {
222                glBindFramebuffer( GL_FRAMEBUFFER, tinfo->glid );
223                // TODO: do we need to bind the renderbuffer at all?
224                glBindRenderbuffer( GL_RENDERBUFFER, sinfo->depth_rb_glid );
225                glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, sinfo->depth_rb_glid );
226                glBindRenderbuffer( GL_RENDERBUFFER, 0 );
227                glBindRenderbuffer( GL_FRAMEBUFFER, 0 );
228        }
229
230}
231
232
233void nv::gl_context::blit( framebuffer f, buffer_mask mask, ivec2 src1, ivec2 src2, ivec2 dst1, ivec2 dst2 )
234{
235        gl_framebuffer_info* info  = m_framebuffers.get( f );
236        if ( info )
237        {
238                glBindFramebuffer( GL_FRAMEBUFFER, info->glid );
239                unsigned filter = mask == buffer_mask::COLOR_BUFFER ? GL_LINEAR : GL_NEAREST;
240                glBlitFramebuffer( src1.x, src1.y, src2.x, src2.y, dst1.x, dst1.y, dst2.x, dst2.y, clear_state_buffers_to_mask( mask ), filter );
241        }
242}
243
244
245void nv::gl_context::blit( framebuffer from, framebuffer to, buffer_mask mask, ivec2 src1, ivec2 src2, ivec2 dst1, ivec2 dst2 )
246{
247        gl_framebuffer_info* finfo = m_framebuffers.get( from );
248        gl_framebuffer_info* tinfo = m_framebuffers.get( to );
249        if ( finfo )
250        {
251                glBindFramebuffer( GL_READ_FRAMEBUFFER, finfo->glid );
252                glBindFramebuffer( GL_DRAW_FRAMEBUFFER, tinfo ? tinfo->glid : 0 );
253                unsigned filter = mask == buffer_mask::COLOR_BUFFER ? GL_LINEAR : GL_NEAREST;
254                glBlitFramebuffer( src1.x, src1.y, src2.x, src2.y, dst1.x, dst1.y, dst2.x, dst2.y, clear_state_buffers_to_mask( mask ), filter );
255                glBindFramebuffer( GL_READ_FRAMEBUFFER, 0 );
256                if ( tinfo ) glBindFramebuffer( GL_DRAW_FRAMEBUFFER, 0 );
257        }
258}
259
260bool nv::gl_context::check( framebuffer_slot ft )
261{
262        glDrawBuffer( 0 );
263        glReadBuffer( 0 );
264
265        unsigned result = glCheckFramebufferStatus( framebuffer_slot_to_enum(ft) );
266        if ( result == GL_FRAMEBUFFER_COMPLETE ) return true;
267        switch ( result )
268        {
269        case GL_FRAMEBUFFER_UNDEFINED                     : NV_LOG_ERROR( "gl_context::check : Framebuffer undefined!" ); break;
270        case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE        : NV_LOG_ERROR( "gl_context::check : Incomplete multisample!" ); break;
271        case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS      : NV_LOG_ERROR( "gl_context::check : Incomplete layer targets!" ); break;
272        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT         : NV_LOG_ERROR( "gl_context::check : Framebuffer incomplete attachment!" ); break;
273        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : NV_LOG_ERROR( "gl_context::check : Framebuffer missing attachment!" ); break;
274//              case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS         : NV_LOG_ERROR( "gl_context::check : Framebuffer incomplete dimensions!" ); break;
275//              case GL_FRAMEBUFFER_INCOMPLETE_FORMATS            : NV_LOG_ERROR( "gl_context::check : Framebuffer incomplete formats!" ); break;
276        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER        : NV_LOG_ERROR( "gl_context::check : Framebuffer incomplete draw buffer!" ); break;
277        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER        : NV_LOG_ERROR( "gl_context::check : Framebuffer incomplete read buffer!" ); break;
278        case GL_FRAMEBUFFER_UNSUPPORTED                   : NV_LOG_ERROR( "gl_context::check : Framebuffer format combination unsupported!" ); break;
279        default: NV_LOG_ERROR( "gl_context::check : Unknown Framebuffer error! (", result, ")" ); break;
280        }
281        glDrawBuffer( GL_BACK );
282        glReadBuffer( GL_BACK );
283        return false;
284}
285
286void nv::gl_context::bind( framebuffer f, framebuffer_slot ft /*= FRAMEBUFFER_BOTH */ )
287{
288        const gl_framebuffer_info* info = m_framebuffers.get( f );
289        if ( info )
290        {
291                glBindFramebuffer( framebuffer_slot_to_enum(ft), info->glid );
292        }
293        else
294        {
295                glBindFramebuffer( framebuffer_slot_to_enum(ft), 0 );
296        }
297}
298
299
300void nv::gl_context::bind( buffer b, texture t )
301{
302        const gl_buffer_info*  binfo = static_cast< const gl_buffer_info* >( m_device->get_buffer_info( b ) );
303        const gl_texture_info* tinfo = static_cast< const gl_texture_info* >( m_device->get_texture_info( t ) );
304        NV_ASSERT( binfo && tinfo, "Bad buffer or texture passed to create_texture" );
305        if ( binfo && tinfo )
306        {
307                NV_ASSERT_ALWAYS( binfo->type == TEXTURE_BUFFER && tinfo->type == TEXTURE_1D_BUFFER, "bad texture or buffer type!" );
308                bind( t, TEXTURE_0 );
309                glTexBuffer( GL_TEXTURE_BUFFER, image_format_to_internal_enum( tinfo->format ), binfo->glid );
310        }
311}
312
313void nv::gl_context::bind( buffer b, uint32 index, uint32 offset /*= 0*/, uint32 size /*= 0 */ )
314{
315        const gl_buffer_info* info = static_cast< const gl_buffer_info* >( m_device->get_buffer_info( b ) );
316        if ( info )
317        {
318                if ( size == 0 )
319                        glBindBufferBase( buffer_type_to_enum( info->type ), index, info->glid );
320                else
321                        glBindBufferRange( buffer_type_to_enum( info->type ), index, info->glid, static_cast<GLintptr>( offset ), static_cast<GLsizeiptr>( size ) );
322        }
323}
324
325void gl_context::bind( texture t, texture_slot slot )
326{
327        if ( m_bound_textures[ slot ] != t )
328        {
329                const gl_texture_info* info = static_cast< const gl_texture_info* >( m_device->get_texture_info( t ) );
330                if ( info )
331                {
332                        set_active_texture( slot );
333                        glBindTexture( texture_type_to_enum( info->type ), info->glid );
334                        m_bound_textures[slot] = t;
335                }
336        }
337}
338
339void nv::gl_context::bind( program p )
340{
341        gl_device* gdevice    = static_cast<gl_device*>( m_device );
342        gl_program_info* info = gdevice->m_programs.get( p );
343        if ( info )
344        {
345                if ( m_bound_program != p )
346                        glUseProgram( info->glid );
347                gdevice->update_uniforms( info );
348                if ( !info->validated )
349                {
350                        validate_program( p );
351                }
352                m_bound_program = p;
353        }
354}
355
356bool nv::gl_context::validate_program( program p )
357{
358        gl_device* gdevice = static_cast<gl_device*>( m_device );
359        gl_program_info* info = gdevice->m_programs.get( p );
360        if ( info )
361        {
362                info->validated = true;
363                const uint32 buffer_size = 1024;
364                char buffer[buffer_size] = { 0 };
365                int length;
366                int status;
367                glValidateProgram( info->glid );
368                glGetProgramiv( info->glid, GL_VALIDATE_STATUS, &status );
369
370                if ( status == GL_FALSE )
371                {
372                        glGetProgramInfoLog( info->glid, buffer_size, &length, buffer );
373                        NV_LOG_ERROR( "Program #", info->glid, " validation error : ", buffer );
374                        return false;
375                }
376                return true;
377        }
378        return false;
379}
380
381
382// void nv::gl_context::bind( buffer b )
383// {
384//      const gl_buffer_info* info = static_cast< const gl_buffer_info* >( m_device->get_buffer_info( b ) );
385//      if ( info )
386//      {
387//              glBindBuffer( buffer_type_to_enum( info->type ), info->glid );
388//      }
389// }
390
391void nv::gl_context::bind( vertex_array va )
392{
393        gl_vertex_array_info* info = m_vertex_arrays.get( va );
394        if ( info )
395        {
396                glBindVertexArray( info->glid );
397        }
398}
399
400void nv::gl_context::unbind( program )
401{
402        if ( m_bound_program )
403                glUseProgram( 0 );
404        m_bound_program = program();
405}
406
407void nv::gl_context::set_active_texture( texture_slot slot )
408{
409        if ( slot != m_active_slot )
410        {
411                glActiveTexture( GL_TEXTURE0 + static_cast<GLenum>( slot ) );
412                m_active_slot = slot;
413        }
414}
415
416// void nv::gl_context::unbind( buffer b )
417// {
418//      const gl_buffer_info* info = static_cast< const gl_buffer_info* >( m_device->get_buffer_info( b ) );
419//      if ( info )
420//      {
421//              glBindBuffer( buffer_type_to_enum( info->type ), 0 );
422//      }
423// }
424
425void nv::gl_context::unbind( vertex_array va )
426{
427        const vertex_array_info* info = m_vertex_arrays.get( va );
428        if ( info )
429        {
430                glBindVertexArray( 0 );
431        }
432}
433
434void nv::gl_context::unbind( framebuffer f )
435{
436        // this way we are sure that the extension is loaded
437        const gl_framebuffer_info* info = m_framebuffers.get( f );
438        if ( info )
439        {
440                glBindFramebuffer( GL_FRAMEBUFFER, 0 );
441        }
442        glDrawBuffer( GL_BACK );
443        glReadBuffer( GL_BACK );
444}
445
446void nv::gl_context::update( texture t, const void* data )
447{
448        const gl_texture_info* info = static_cast< const gl_texture_info* >( m_device->get_texture_info( t ) );
449        NV_ASSERT_ALWAYS( info->type != TEXTURE_1D_BUFFER, "Buffer texture passed to update!" );
450        NV_ASSERT_ALWAYS( info->type != TEXTURE_2D_MULTISAMPLE, "Multisample texture passed to update!" );
451        if ( info )
452        {
453                pixel_format format  = info->format;
454                datatype     type    = get_pixel_format_info( format ).type;
455                ivec3        size    = info->size;
456                unsigned     gl_type = texture_type_to_enum( info->type );
457
458                bind( t, texture_slot::TEXTURE_0 );
459                if ( info->type == TEXTURE_3D || info->type == TEXTURE_2D_ARRAY )
460//                      glTexImage3D( gl_type, 0, static_cast<GLint>( nv::image_format_to_internal_enum( format ) ), size.x, size.y, size.z, 0, nv::image_format_to_enum( format ), nv::datatype_to_gl_enum( type ), data );
461                        glTexSubImage3D( gl_type, 0, 0, 0, 0, size.x, size.y, size.z, nv::image_format_to_enum( format ), nv::datatype_to_gl_enum( type ), data );
462                else
463//                      glTexImage2D( gl_type, 0, static_cast<GLint>( nv::image_format_to_internal_enum(format) ), size.x, size.y, 0, nv::image_format_to_enum(format), nv::datatype_to_gl_enum(type), data );
464                        glTexSubImage2D( gl_type, 0, 0, 0, size.x, size.y, nv::image_format_to_enum( format ), nv::datatype_to_gl_enum( type ), data );
465        }
466}
467
468void* nv::gl_context::map_buffer( buffer b, buffer_access ba, uint32 offset, uint32 length )
469{
470        const gl_buffer_info* info = static_cast<const gl_buffer_info*>( m_device->get_buffer_info( b ) );
471        unsigned int glenum = buffer_type_to_enum( info->type );
472        glBindBuffer( glenum, info->glid );
473        void* result = glMapBufferRange( glenum, GLintptr( offset ), GLsizeiptr( length ), buffer_access_to_bitfield( ba ) );
474        if ( result == nullptr )
475        {
476                while ( GLenum err = glGetError() )
477                switch ( err )
478                {
479                case GL_INVALID_VALUE     : NV_LOG_ERROR( "map_buffer failed : GL_INVALID_VALUE" ) break;
480                case GL_INVALID_OPERATION : NV_LOG_ERROR( "map_buffer failed : GL_INVALID_OPERATION " ) break;
481                case GL_OUT_OF_MEMORY     : NV_LOG_ERROR( "map_buffer failed : GL_OUT_OF_MEMORY " ) break;
482                default:
483                        break;
484                }
485        }
486        return result;
487}
488
489void nv::gl_context::unmap_buffer( buffer b )
490{
491        const gl_buffer_info* info = static_cast<const gl_buffer_info*>( m_device->get_buffer_info( b ) );
492        glUnmapBuffer( buffer_type_to_enum( info->type ) );
493}
494
495// void nv::gl_context::update( buffer b, uint32 index, const void* data, uint32 offset, uint32 size )
496// {
497//      const gl_buffer_info* info = static_cast<const gl_buffer_info*>( m_device->get_buffer_info( b ) );
498//      if ( info )
499//      {
500//              GLenum glenum = buffer_type_to_enum( info->type );
501//              if ( size == 0 )
502//                      glBindBufferBase( glenum, index, info->glid );
503//              else
504//                      glBindBufferRange( glenum, index, info->glid, offset, size );
505//              glBufferSubData( glenum, GLintptr( offset ), GLsizeiptr( size ), data );
506//      }
507// }
508
509void gl_context::update( buffer b, const void* data, nv::uint32 offset, nv::uint32 size )
510{
511        const gl_buffer_info* info = static_cast< const gl_buffer_info* >( m_device->get_buffer_info( b ) );
512        if ( info )
513        {
514                GLenum glenum = buffer_type_to_enum( info->type );
515                glBindBuffer( glenum, info->glid );
516                glBufferSubData( glenum, GLintptr( offset ), GLsizeiptr( size ), data );
517        }
518}
519
520void gl_context::clear( const clear_state& cs )
521{
522        // apply_framebuffer
523       
524        apply_scissor_test( cs.scissor_test );
525        apply_color_mask( cs.color_mask );
526        apply_depth_mask( cs.depth_mask );
527        // stencil_mask_separate
528
529        if ( m_clear_color != cs.color )
530        {
531                glClearColor( cs.color.r, cs.color.g, cs.color.b, cs.color.a );
532                m_clear_color = cs.color;
533        }
534
535        if ( m_clear_depth != cs.depth )
536        {
537                glClearDepth( cs.depth );
538                m_clear_depth = cs.depth;
539        }
540
541        if ( m_clear_stencil != cs.stencil )
542        {
543                glClearStencil( cs.stencil );
544                m_clear_stencil = cs.stencil;
545        }
546       
547        glClear( clear_state_buffers_to_mask( cs.buffers ) );
548}
549
550const ivec4& gl_context::get_viewport()
551{
552        return m_viewport;
553}
554
555void gl_context::set_viewport( const ivec4& viewport )
556{
557        if ( m_viewport != viewport )
558        {
559                NV_ASSERT_ALWAYS( viewport.z > 0 && viewport.w > 0, "viewport dimensions must be greater than zero!" );
560                m_viewport = viewport;
561                glViewport( viewport.x, viewport.y, viewport.z, viewport.w );
562        }
563}
564
565void gl_context::enable( unsigned int what, bool value )
566{
567        if ( value )
568        {
569                glEnable( what );
570        }
571        else
572        {
573                glDisable( what );
574        }
575}
576
577void gl_context::apply_stencil_test( const stencil_test& stencil )
578{
579        if ( m_render_state.stencil_test.enabled != stencil.enabled )
580        {
581                enable( GL_STENCIL_TEST, stencil.enabled );
582                m_render_state.stencil_test.enabled = stencil.enabled;
583        }
584       
585        if ( stencil.enabled )
586        {
587                apply_stencil_face( GL_FRONT, m_render_state.stencil_test.front_face, stencil.front_face );
588                apply_stencil_face( GL_BACK,  m_render_state.stencil_test.back_face,  stencil.back_face );
589        }
590}
591
592void gl_context::apply_stencil_face( unsigned face, stencil_test_face& stencil, const stencil_test_face& new_stencil )
593{
594        if (( stencil.op_fail       != new_stencil.op_fail       ) ||
595                ( stencil.op_depth_fail != new_stencil.op_depth_fail ) ||
596                ( stencil.op_depth_pass != new_stencil.op_depth_pass ) )
597        {
598                glStencilOpSeparate( face,
599                        stencil_operation_to_enum( new_stencil.op_fail ),
600                        stencil_operation_to_enum( new_stencil.op_depth_fail ),
601                        stencil_operation_to_enum( new_stencil.op_depth_pass )
602                );
603
604                stencil.op_fail       = new_stencil.op_fail;
605                stencil.op_depth_fail = new_stencil.op_depth_fail;
606                stencil.op_depth_pass = new_stencil.op_depth_pass;
607        }
608
609        if (( stencil.function  != new_stencil.function ) ||
610                ( stencil.ref_value != new_stencil.ref_value ) ||
611                ( stencil.mask      != new_stencil.mask ))
612        {
613                glStencilFuncSeparate( face,
614                        stencil_function_to_enum( new_stencil.function ),
615                        new_stencil.ref_value,
616                        new_stencil.mask
617                );
618
619                stencil.function  = new_stencil.function;
620                stencil.ref_value = new_stencil.ref_value;
621                stencil.mask      = new_stencil.mask;
622        }
623}
624
625void gl_context::apply_scissor_test( const scissor_test& scissor )
626{
627        if ( m_render_state.scissor_test.enabled != scissor.enabled )
628        {
629                enable( GL_SCISSOR_TEST, scissor.enabled );
630                m_render_state.scissor_test.enabled = scissor.enabled;
631        }
632
633
634        if ( scissor.enabled )
635        {
636                NV_ASSERT_ALWAYS( scissor.dim.x > 0 && scissor.dim.y > 0, "scissor_test.rect dimension equal to zero!" );
637
638                if ( m_render_state.scissor_test.dim != scissor.dim || m_render_state.scissor_test.pos != scissor.pos )
639                {
640                        glScissor(
641                                scissor.pos.x, scissor.pos.y,
642                                scissor.dim.x, scissor.dim.y
643                        );
644                        m_render_state.scissor_test.dim = scissor.dim;
645                        m_render_state.scissor_test.pos = scissor.pos;
646                }
647        }
648}
649
650void gl_context::apply_depth_test( const depth_test& depth )
651{
652        if ( m_render_state.depth_test.enabled != depth.enabled )
653        {
654                enable( GL_DEPTH_TEST, depth.enabled );
655                m_render_state.depth_test.enabled = depth.enabled;
656        }
657
658        if ( depth.enabled )
659        {
660                if ( m_render_state.depth_test.function != depth.function )
661                {
662                        glDepthFunc( depth_state_function_to_enum( depth.function ) );
663                        m_render_state.depth_test.function = depth.function;
664                }
665        }
666}
667
668void gl_context::apply_depth_mask( bool mask )
669{
670        if ( m_render_state.depth_mask != mask )
671        {
672                glDepthMask( mask );
673                m_render_state.depth_mask = mask;
674        }
675}
676
677void gl_context::apply_multisample( bool multisample )
678{
679        if ( m_render_state.multisample != multisample )
680        {
681                glDepthMask( multisample );
682                m_render_state.multisample = multisample;
683        }
684}
685
686void gl_context::apply_polygon_mode( const polygon_mode& mode )
687{
688        if ( m_render_state.polygon_mode.fill != mode.fill )
689        {
690                glPolygonMode( GL_FRONT_AND_BACK, polygon_mode_fill_to_enum( mode.fill ) );
691                m_render_state.polygon_mode.fill = mode.fill;
692        }
693}
694
695
696void gl_context::apply_depth_range( const depth_range& range )
697{
698        NV_ASSERT_ALWAYS( range.near >= 0.0 && range.near <= 1.0, "render_state.depth_range.near must be between zero and one!" );
699        NV_ASSERT_ALWAYS( range.far  >= 0.0 && range.far  <= 1.0, "render_state.depth_range.far must be between zero and one!" );
700
701        if ((m_render_state.depth_range.far  != range.far) ||
702                (m_render_state.depth_range.near != range.near))
703        {
704                glDepthRange( range.near, range.far );
705
706                m_render_state.depth_range.far  = range.far;
707                m_render_state.depth_range.near = range.near;
708        }
709}
710
711void gl_context::apply_color_mask( const color_mask& mask )
712{
713        if ( m_render_state.color_mask != mask )
714        {
715                glColorMask( mask.red, mask.green, mask.blue, mask.alpha );
716                m_render_state.color_mask = mask;
717        }
718}
719
720void gl_context::apply_blending( const blending& blend )
721{
722        if ( m_render_state.blending.enabled != blend.enabled )
723        {
724                enable( GL_BLEND, blend.enabled );
725                m_render_state.blending.enabled = blend.enabled;
726        }
727
728        if ( blend.enabled )
729        {
730                if ((m_render_state.blending.src_rgb_factor   != blend.src_rgb_factor ) ||
731                        (m_render_state.blending.dst_rgb_factor   != blend.dst_rgb_factor ) ||
732                        (m_render_state.blending.src_alpha_factor != blend.src_alpha_factor ) ||
733                        (m_render_state.blending.dst_alpha_factor != blend.dst_alpha_factor ))
734                {
735                        glBlendFuncSeparate(
736                                blending_factor_to_enum( blend.src_rgb_factor ),
737                                blending_factor_to_enum( blend.dst_rgb_factor ),
738                                blending_factor_to_enum( blend.src_alpha_factor ),
739                                blending_factor_to_enum( blend.dst_alpha_factor )
740                        );
741
742                        m_render_state.blending.src_rgb_factor   = blend.src_rgb_factor;
743                        m_render_state.blending.dst_rgb_factor   = blend.dst_rgb_factor;
744                        m_render_state.blending.src_alpha_factor = blend.src_alpha_factor;
745                        m_render_state.blending.dst_alpha_factor = blend.dst_alpha_factor;
746                }
747
748                if ((m_render_state.blending.rgb_equation   != blend.rgb_equation ) ||
749                        (m_render_state.blending.alpha_equation != blend.alpha_equation ))
750                {
751                        glBlendEquationSeparate(
752                                blending_equation_to_enum( blend.rgb_equation ),
753                                blending_equation_to_enum( blend.alpha_equation )
754                        );
755
756                        m_render_state.blending.rgb_equation   = blend.rgb_equation;
757                        m_render_state.blending.alpha_equation = blend.alpha_equation;
758                }
759
760                if (( m_render_state.blending.color != blend.color ))
761                {
762                        glBlendColor( blend.color.r, blend.color.g, blend.color.b, blend.color.a );
763                        m_render_state.blending.color = blend.color;
764                }
765        }
766}
767
768
769void gl_context::apply_culling( const culling& cull )
770{
771        if ( m_render_state.culling.enabled != cull.enabled )
772        {
773                enable( GL_CULL_FACE, cull.enabled );
774                m_render_state.culling.enabled = cull.enabled;
775        }
776
777        if ( cull.enabled )
778        {
779                if ( m_render_state.culling.face != cull.face )
780                {
781                        glCullFace( culling_face_type_to_enum( cull.face ) );
782                        m_render_state.culling.face = cull.face;
783                }
784        }
785
786        if ( m_render_state.culling.order != cull.order )
787        {
788                glFrontFace( culling_order_type_to_enum( cull.order ) );
789                m_render_state.culling.order = cull.order;
790        }
791}
792
793
794void gl_context::force_apply_render_state( const render_state& state )
795{
796        enable( GL_CULL_FACE, state.culling.enabled );
797        glCullFace( culling_face_type_to_enum( state.culling.face ) );
798        glFrontFace( culling_order_type_to_enum( state.culling.order ) );
799
800        enable( GL_SCISSOR_TEST, state.scissor_test.enabled );
801        glScissor(
802                state.scissor_test.pos.x, state.scissor_test.pos.y,
803                state.scissor_test.dim.x, state.scissor_test.dim.y
804        );
805
806        enable( GL_STENCIL_TEST, state.stencil_test.enabled );
807        force_apply_stencil_face( GL_FRONT, state.stencil_test.front_face );
808        force_apply_stencil_face( GL_BACK,  state.stencil_test.back_face  );
809
810        enable( GL_DEPTH_TEST, state.depth_test.enabled );
811        glDepthFunc( depth_state_function_to_enum( state.depth_test.function ) );
812        glDepthRange( state.depth_range.near, state.depth_range.far );
813
814        enable( GL_BLEND, state.blending.enabled );
815        glBlendFuncSeparate(
816                blending_factor_to_enum( state.blending.src_rgb_factor ),
817                blending_factor_to_enum( state.blending.dst_rgb_factor ),
818                blending_factor_to_enum( state.blending.src_alpha_factor ),
819                blending_factor_to_enum( state.blending.dst_alpha_factor )
820        );
821        glBlendEquationSeparate(
822                blending_equation_to_enum( state.blending.rgb_equation ),
823                blending_equation_to_enum( state.blending.alpha_equation )
824        );
825        glBlendColor(
826                state.blending.color.r, state.blending.color.g,
827                state.blending.color.b, state.blending.color.a
828        );
829
830        glDepthMask( state.depth_mask );
831        glColorMask(
832                state.color_mask.red, state.color_mask.green,
833                state.color_mask.blue, state.color_mask.alpha
834        );
835        glPolygonMode( GL_FRONT_AND_BACK, polygon_mode_fill_to_enum( state.polygon_mode.fill ) );
836}
837
838void gl_context::force_apply_stencil_face( unsigned face, const stencil_test_face& stencil )
839{
840        glStencilOpSeparate( face,
841                stencil_operation_to_enum( stencil.op_fail ),
842                stencil_operation_to_enum( stencil.op_depth_fail ),
843                stencil_operation_to_enum( stencil.op_depth_pass )
844        );
845
846        glStencilFuncSeparate( face,
847                stencil_function_to_enum( stencil.function ),
848                stencil.ref_value,
849                stencil.mask
850        );
851}
852
853
854void gl_context::apply_render_state( const render_state& state )
855{
856        // apply_primitive_restart
857        apply_culling( state.culling );
858        // apply_program_point_size
859        // apply_rasterization_mode
860        apply_scissor_test( state.scissor_test );
861        apply_stencil_test( state.stencil_test );
862        apply_depth_test( state.depth_test );
863        apply_depth_range( state.depth_range );
864        apply_blending( state.blending );
865        apply_color_mask( state.color_mask );
866        apply_depth_mask( state.depth_mask );
867        apply_multisample( state.multisample );
868        apply_polygon_mode( state.polygon_mode );
869}
870
871
872gl_context::gl_context( device* a_device, void* a_handle )
873        : context( a_device ), m_handle( a_handle )
874{
875        // TODO: configurable:
876//      load_gl_extensions( GL_EXT_FRAMEBUFFER_BLIT | GL_EXT_FRAMEBUFFER_OBJECT | GL_EXT_TEXTURE_ARRAY );
877        m_active_slot = texture_slot( -1 );
878        force_apply_render_state( m_render_state );
879}
880
881nv::gl_context::~gl_context()
882{
883        while ( m_framebuffers.size() > 0 )
884                release( m_framebuffers.get_handle(0) );
885        while ( m_vertex_arrays.size() > 0 )
886                release( m_vertex_arrays.get_handle(0) );
887}
888
889void nv::gl_context::apply_engine_uniforms( program p, const scene_state& s )
890{
891        gl_program_info* info = static_cast<gl_device*>( m_device )->m_programs.get( p );
892        if ( info )
893        {
894                for ( auto& u : *info->m_engine_uniforms )
895                {
896                        u->set( this, &s );
897                }
898        }
899}
900
901nv::texture nv::gl_context::create_texture( texture_type type, ivec2 size, pixel_format aformat, sampler asampler, const void* data /*= nullptr */ )
902{
903        texture result = create_texture( type, aformat );
904        gl_texture_info* info = static_cast<gl_device*>( m_device )->get_full_texture_info( result );
905        bind( result, texture_slot::TEXTURE_0 );
906        unsigned glid = info->glid;
907        unsigned gl_type = texture_type_to_enum( type );
908        GLenum gl_internal = GLenum( image_format_to_internal_enum( aformat ) );
909        unsigned gl_enum = image_format_to_enum( aformat );
910
911        bool is_depth = aformat == DEPTH16 || aformat == DEPTH24 || aformat == DEPTH32;
912
913        // Detect if mipmapping was requested
914        //      if ( gl_type == GL_TEXTURE_2D && gl_enum != GL_RED_INTEGER && asampler.filter_min != sampler::LINEAR && asampler.filter_min != sampler::NEAREST )
915        //      {
916        //              // TODO: This should not be done if we use framebuffers!
917        //              glTexParameteri( gl_type, GL_GENERATE_MIPMAP, GL_TRUE);
918        //      }
919
920        if ( asampler.filter_max != sampler::NEAREST )
921        {
922                asampler.filter_max = sampler::LINEAR;
923        }
924
925        if ( gl_type != GL_TEXTURE_2D_MULTISAMPLE )
926        {
927                glTexParameteri( gl_type, GL_TEXTURE_MIN_FILTER, GLint( nv::sampler_filter_to_enum( asampler.filter_min ) ) );
928                glTexParameteri( gl_type, GL_TEXTURE_MAG_FILTER, GLint( nv::sampler_filter_to_enum( asampler.filter_max ) ) );
929        }
930
931        if ( gl_type != GL_TEXTURE_2D_MULTISAMPLE && gl_enum != GL_RED_INTEGER )
932        {
933                glTexParameteri( gl_type, GL_TEXTURE_WRAP_S, GLint( nv::sampler_wrap_to_enum( asampler.wrap_s ) ) );
934                glTexParameteri( gl_type, GL_TEXTURE_WRAP_T, GLint( nv::sampler_wrap_to_enum( asampler.wrap_t ) ) );
935        }
936
937        if ( is_depth )
938        {
939                //              glTexParameteri( gl_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
940                //              glTexParameteri( gl_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
941
942                // This is to allow usage of shadow2DProj function in the shader
943                glTexParameteri( gl_type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE );
944                glTexParameteri( gl_type, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
945        }
946
947        // #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
948        // #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
949        //
950        //      float aniso = 0.0f;
951        //      glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso );
952        //      NV_LOG_INFO( "Anisotropy at ", aniso, " (", int( aniso ), " ) " );
953        //      glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso );
954
955        if ( gl_type != GL_TEXTURE_2D_MULTISAMPLE )
956                glTexImage2D( gl_type, 0, gl_internal, size.x, size.y, 0, gl_enum, nv::datatype_to_gl_enum( get_pixel_format_info( aformat ).type ), data );
957        else
958                glTexImage2DMultisample( gl_type, 4, gl_internal, size.x, size.y, 1 );
959
960        if ( gl_type == GL_TEXTURE_2D && gl_enum != GL_RED_INTEGER && asampler.filter_min != sampler::LINEAR && asampler.filter_min != sampler::NEAREST )
961        {
962                // TODO: This should not be done if we use framebuffers!
963                glGenerateMipmap( gl_type );
964        }
965
966        bind( texture(), texture_slot::TEXTURE_0 );
967
968        info->type = type;
969        info->format = aformat;
970        info->tsampler = asampler;
971        info->size = ivec3( size.x, size.y, 1 );
972        info->glid = glid;
973
974        return result;
975}
976
977nv::texture nv::gl_context::create_texture( texture_type type, ivec3 size, pixel_format aformat, sampler asampler, const void* data /*= nullptr */ )
978{
979        texture result = create_texture( type, aformat );
980        gl_texture_info* info = static_cast<gl_device*>( m_device )->get_full_texture_info( result );
981        bind( result, texture_slot::TEXTURE_0 );
982        unsigned glid = info->glid;
983
984        unsigned gl_type = texture_type_to_enum( type );
985
986        bool is_depth = aformat == DEPTH16 || aformat == DEPTH24 || aformat == DEPTH32;
987
988        if ( asampler.filter_max != sampler::NEAREST )
989        {
990                asampler.filter_max = sampler::LINEAR;
991        }
992
993        glTexParameteri( gl_type, GL_TEXTURE_MIN_FILTER, GLint( nv::sampler_filter_to_enum( asampler.filter_min ) ) );
994        glTexParameteri( gl_type, GL_TEXTURE_MAG_FILTER, GLint( nv::sampler_filter_to_enum( asampler.filter_max ) ) );
995        glTexParameteri( gl_type, GL_TEXTURE_WRAP_S, GLint( nv::sampler_wrap_to_enum( asampler.wrap_s ) ) );
996        glTexParameteri( gl_type, GL_TEXTURE_WRAP_T, GLint( nv::sampler_wrap_to_enum( asampler.wrap_t ) ) );
997        glTexParameteri( gl_type, GL_TEXTURE_WRAP_R, GLint( nv::sampler_wrap_to_enum( asampler.wrap_r ) ) );
998
999        if ( is_depth )
1000        {
1001                glTexParameteri( gl_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
1002                glTexParameteri( gl_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
1003
1004                // This is to allow usage of shadow2DProj function in the shader
1005                glTexParameteri( gl_type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE );
1006                glTexParameteri( gl_type, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
1007        }
1008
1009        //glTexStorage3D( GL_TEXTURE_2D_ARRAY, mipLevelCount, GL_RGBA8, width, height, layerCount );
1010        glTexImage3D( gl_type, 0, GLint( nv::image_format_to_internal_enum( aformat ) ), size.x, size.y, size.z, 0, nv::image_format_to_enum( aformat ), nv::datatype_to_gl_enum( get_pixel_format_info( aformat ).type ), data );
1011
1012        bind( texture(), texture_slot::TEXTURE_0 );
1013
1014        info->type = type;
1015        info->format = aformat;
1016        info->tsampler = asampler;
1017        info->size = size;
1018        info->glid = glid;
1019
1020        return result;
1021}
1022
1023nv::buffer nv::gl_context::create_buffer( buffer_type type, buffer_hint hint, uint32 size, const void* source /*= nullptr */ )
1024{
1025        buffer result = static_cast<gl_device*>( m_device )->create_buffer( type, hint );
1026        if ( size > 0 ) create_buffer( result, size, source );
1027        return result;
1028}
1029
1030void nv::gl_context::create_buffer( buffer b, uint32 size, const void* source /*= nullptr */ )
1031{
1032        gl_buffer_info* info = static_cast<gl_device*>( m_device )->get_full_buffer_info( b );
1033        if ( info )
1034        {
1035                unsigned glenum = buffer_type_to_enum( info->type );
1036                glBindBuffer( glenum, info->glid );
1037                glBufferData( glenum, GLsizeiptr( size ), source, buffer_hint_to_enum( info->hint ) );
1038                glBindBuffer( glenum, 0 );
1039        }
1040}
1041
1042void nv::gl_context::set_draw_buffers( uint32 count, const output_slot* slots )
1043{
1044        if ( count == 0 ) return;
1045        if ( count == 1 )
1046        {
1047                set_draw_buffer( slots[0] );
1048                return;
1049        }
1050        unsigned int buffers[8];
1051        count = nv::min<uint32>( count, 8 );
1052        for ( uint32 i = 0; i < count; ++i )
1053        {
1054                buffers[i] = output_slot_to_enum( slots[i] );
1055                if ( slots[i] > OUTPUT_7 ) buffers[i] = 0;
1056        }
1057        glDrawBuffers( GLsizei( count ), buffers );
1058}
1059
1060void nv::gl_context::set_draw_buffer( output_slot slot )
1061{
1062        glDrawBuffer( output_slot_to_enum(slot) );
1063}
1064
1065void nv::gl_context::set_read_buffer( output_slot slot )
1066{
1067        glReadBuffer( output_slot_to_enum(slot) );
1068}
1069
1070void gl_context::draw( primitive prim, const render_state& rs, program p, vertex_array va, nv::uint32 count, nv::uint32 first )
1071{
1072        apply_render_state( rs );
1073        const vertex_array_info* info = m_vertex_arrays.get( va );
1074        if ( count > 0 && info )
1075        {
1076                bind( p );
1077                bind( va );
1078                if ( info->index.is_valid() )
1079                {
1080                        glDrawElements( primitive_to_enum(prim), static_cast<GLsizei>( count ), datatype_to_gl_enum( info->index_type ), reinterpret_cast< const void* >( size_t( get_datatype_info( info->index_type ).size * first ) ) );
1081                }
1082                else
1083                {
1084                        glDrawArrays( primitive_to_enum(prim), static_cast<GLint>( first ), static_cast<GLsizei>( count ) );
1085                }
1086                unbind( va );
1087                //unbind( p );
1088        }
1089}
1090
1091void nv::gl_context::draw_instanced( primitive prim, const render_state& rs, program p, uint32 instances, vertex_array va, uint32 count, uint32 first /*= 0 */ )
1092{
1093        apply_render_state( rs );
1094        const vertex_array_info* info = m_vertex_arrays.get( va );
1095        if ( count > 0 && info )
1096        {
1097                bind( p );
1098                bind( va );
1099                if ( info->index.is_valid() )
1100                {
1101                        glDrawElementsInstanced( primitive_to_enum( prim ), static_cast<GLsizei>( count ), datatype_to_gl_enum( info->index_type ), reinterpret_cast<const void*>( size_t( get_datatype_info( info->index_type ).size * first ) ), instances );
1102                }
1103                else
1104                {
1105                        glDrawArraysInstanced( primitive_to_enum( prim ), static_cast<GLint>( first ), static_cast<GLsizei>( count ), instances );
1106                }
1107                unbind( va );
1108                //unbind( p );
1109        }
1110}
Note: See TracBrowser for help on using the repository browser.