2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/render/shaders/program.h>
25 #include <dali/public-api/common/dali-common.h>
26 #include <dali/public-api/common/dali-vector.h>
27 #include <dali/public-api/common/constants.h>
28 #include <dali/integration-api/debug.h>
29 #include <dali/integration-api/shader-data.h>
30 #include <dali/integration-api/gl-defines.h>
31 #include <dali/internal/render/common/performance-monitor.h>
32 #include <dali/internal/render/shaders/program-cache.h>
33 #include <dali/internal/render/gl-resources/gl-call-debug.h>
37 void LogWithLineNumbers( const char * source )
39 unsigned int lineNumber = 0u;
40 const char *prev = source;
41 const char *ptr = prev;
49 // seek the next end of line or end of text
50 while( *ptr!='\n' && *ptr != '\0' )
55 std::string line( prev, ptr-prev );
56 Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugError, "%4d %s\n", lineNumber, line.c_str());
79 const char* gStdAttribs[ Program::ATTRIB_TYPE_LAST ] =
81 "aPosition", // ATTRIB_POSITION
82 "aNormal", // ATTRIB_NORMAL
83 "aTexCoord", // ATTRIB_TEXCOORD
84 "aColor", // ATTRIB_COLOR
85 "aBoneWeights", // ATTRIB_BONE_WEIGHTS
86 "aBoneIndices" // ATTRIB_BONE_INDICES
89 const char* gStdUniforms[ Program::UNIFORM_TYPE_LAST ] =
91 "uMvpMatrix", // UNIFORM_MVP_MATRIX
92 "uModelView", // UNIFORM_MODELVIEW_MATRIX
93 "uProjection", // UNIFORM_PROJECTION_MATRIX
94 "uModelMatrix", // UNIFORM_MODEL_MATRIX,
95 "uViewMatrix", // UNIFORM_VIEW_MATRIX,
96 "uNormalMatrix", // UNIFORM_NORMAL_MATRIX
97 "uColor", // UNIFORM_COLOR
98 "uCustomTextureCoords", // UNIFORM_CUSTOM_TEXTURE_COORDS
99 "sTexture", // UNIFORM_SAMPLER
100 "sTextureRect", // UNIFORM_SAMPLER_RECT
101 "sEffect", // UNIFORM_EFFECT_SAMPLER
102 "sEffectRect", // UNIFORM_EFFECT_SAMPLER_RECT
103 "uTimeDelta", // UNIFORM_TIME_DELTA
104 "sOpacityTexture", // UNIFORM_SAMPLER_OPACITY
105 "sNormalMapTexture" // UNIFORM_SAMPLER_NORMAL_MAP
108 } // <unnamed> namespace
112 Program* Program::New( ProgramCache& cache, Integration::ShaderDataPtr shaderData, bool modifiesGeometry )
114 size_t shaderHash = shaderData->GetHashValue();
115 Program* program = cache.GetProgram( shaderHash );
117 if( NULL == program )
119 // program not found so create it
120 program = new Program( cache, shaderData, modifiesGeometry );
122 // we want to lazy load programs so dont do a Load yet, it gets done in Use()
124 cache.AddProgram( shaderHash, program );
139 if ( this != mCache.GetCurrentProgram() )
141 LOG_GL( "UseProgram(%d)\n", mProgramId );
142 CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(mProgramId) );
143 INCREASE_COUNTER(PerformanceMonitor::SHADER_STATE_CHANGES);
145 mCache.SetCurrentProgram( this );
150 bool Program::IsUsed()
152 return ( this == mCache.GetCurrentProgram() );
155 GLint Program::GetAttribLocation( AttribType type )
157 DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
159 if( mAttribLocations[ type ] == ATTRIB_UNKNOWN )
161 GLint loc = CHECK_GL( mGlAbstraction, mGlAbstraction.GetAttribLocation( mProgramId, gStdAttribs[type] ) );
162 mAttribLocations[ type ] = loc;
163 LOG_GL( "GetAttribLocation(program=%d,%s) = %d\n", mProgramId, gStdAttribs[type], mAttribLocations[type] );
166 return mAttribLocations[type];
169 unsigned int Program::RegisterUniform( const std::string& name )
171 unsigned int index = 0;
172 // find the value from cache
173 for( ;index < mUniformLocations.size(); ++index )
175 if( mUniformLocations[ index ].first == name )
177 // name found so return index
181 // if we get here, index is one past end so push back the new name
182 mUniformLocations.push_back( std::make_pair( name, UNIFORM_NOT_QUERIED ) );
186 GLint Program::GetUniformLocation( unsigned int uniformIndex )
188 // debug check that index is within name cache
189 DALI_ASSERT_DEBUG( mUniformLocations.size() > uniformIndex );
191 // check if we have already queried the location of the uniform
192 GLint location = mUniformLocations[ uniformIndex ].second;
194 if( location == UNIFORM_NOT_QUERIED )
196 location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetUniformLocation( mProgramId, mUniformLocations[ uniformIndex ].first.c_str() ) );
198 mUniformLocations[ uniformIndex ].second = location;
199 LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[ uniformIndex ].first.c_str(), mUniformLocations[ uniformIndex ].second );
205 void Program::SetUniform1i( GLint location, GLint value0 )
207 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
209 if( UNIFORM_UNKNOWN == location )
211 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
212 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
213 // specified uniform variable will not be changed.following opengl silently do nothing
217 // check if uniform location fits the cache
218 if( location >= MAX_UNIFORM_CACHE_SIZE )
220 // not cached, make the gl call
221 LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
222 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
226 // check if the value is different from what's already been set
227 if( value0 != mUniformCacheInt[ location ] )
230 LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
231 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
233 mUniformCacheInt[ location ] = value0;
238 void Program::SetUniform4i( GLint location, GLint value0, GLint value1, GLint value2, GLint value3 )
240 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
242 if( UNIFORM_UNKNOWN == location )
244 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
245 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
246 // specified uniform variable will not be changed.following opengl silently do nothing
250 // Not caching these as based on current analysis this is not called that often by our shaders
251 LOG_GL( "Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3 );
252 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
255 void Program::SetUniform1f( GLint location, GLfloat value0 )
257 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
259 if( UNIFORM_UNKNOWN == location )
261 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
262 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
263 // specified uniform variable will not be changed.following opengl silently do nothing
267 // check if uniform location fits the cache
268 if( location >= MAX_UNIFORM_CACHE_SIZE )
270 // not cached, make the gl call
271 LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
272 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
276 // check if the same value has already been set, reset if it is different
277 if( ( fabsf(value0 - mUniformCacheFloat[ location ]) >= Math::MACHINE_EPSILON_1 ) )
280 LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
281 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
284 mUniformCacheFloat[ location ] = value0;
289 void Program::SetUniform2f( GLint location, GLfloat value0, GLfloat value1 )
291 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
293 if( UNIFORM_UNKNOWN == location )
295 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
296 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
297 // specified uniform variable will not be changed.following opengl silently do nothing
301 // Not caching these as based on current analysis this is not called that often by our shaders
302 LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
303 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
306 void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
308 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
310 if( UNIFORM_UNKNOWN == location )
312 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
313 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
314 // specified uniform variable will not be changed.following opengl silently do nothing
318 // Not caching these as based on current analysis this is not called that often by our shaders
319 LOG_GL( "Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2 );
320 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
323 void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3 )
325 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
327 if( UNIFORM_UNKNOWN == location )
329 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
330 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
331 // specified uniform variable will not be changed.following opengl silently do nothing
335 // check if uniform location fits the cache
336 if( location >= MAX_UNIFORM_CACHE_SIZE )
338 // not cached, make the gl call
339 LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
340 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
344 // check if the same value has already been set, reset if any component is different
345 // checking index 3 first because we're often animating alpha (rgba)
346 if( ( fabsf(value3 - mUniformCacheFloat4[ location ][ 3 ]) >= Math::MACHINE_EPSILON_1 )||
347 ( fabsf(value0 - mUniformCacheFloat4[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
348 ( fabsf(value1 - mUniformCacheFloat4[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 )||
349 ( fabsf(value2 - mUniformCacheFloat4[ location ][ 2 ]) >= Math::MACHINE_EPSILON_1 ) )
352 LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
353 CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
355 mUniformCacheFloat4[ location ][ 0 ] = value0;
356 mUniformCacheFloat4[ location ][ 1 ] = value1;
357 mUniformCacheFloat4[ location ][ 2 ] = value2;
358 mUniformCacheFloat4[ location ][ 3 ] = value3;
363 void Program::SetUniformMatrix4fv( GLint location, GLsizei count, const GLfloat* value )
365 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
367 if( UNIFORM_UNKNOWN == location )
369 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
370 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
371 // specified uniform variable will not be changed.following opengl silently do nothing
375 // Not caching these calls. Based on current analysis this is called very often
376 // but with different values (we're using this for MVP matrices)
377 // NOTE! we never want driver or GPU to transpose
378 LOG_GL( "UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
379 CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
382 void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat* value )
384 DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
386 if( UNIFORM_UNKNOWN == location )
388 // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
389 // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
390 // specified uniform variable will not be changed.following opengl silently do nothing
395 // Not caching these calls. Based on current analysis this is called very often
396 // but with different values (we're using this for MVP matrices)
397 // NOTE! we never want driver or GPU to transpose
398 LOG_GL( "UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
399 CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
402 void Program::GlContextCreated()
406 void Program::GlContextDestroyed()
410 mFragmentShaderId = 0;
413 ResetAttribsUniformCache();
416 bool Program::ModifiesGeometry()
418 return mModifiesGeometry;
421 Program::Program( ProgramCache& cache, Integration::ShaderDataPtr shaderData, bool modifiesGeometry )
423 mGlAbstraction( mCache.GetGlAbstraction() ),
424 mProjectionMatrix( NULL ),
427 mVertexShaderId( 0 ),
428 mFragmentShaderId( 0 ),
430 mProgramData(shaderData),
431 mModifiesGeometry( modifiesGeometry )
433 // reserve space for standard uniforms
434 mUniformLocations.reserve( UNIFORM_TYPE_LAST );
435 // reset built in uniform names in cache
436 for( int i = 0; i < UNIFORM_TYPE_LAST; ++i )
438 RegisterUniform( gStdUniforms[ i ] );
441 ResetAttribsUniformCache();
451 DALI_ASSERT_ALWAYS( NULL != mProgramData.Get() && "Program data is not initialized" );
453 LOG_GL( "CreateProgram()\n" );
454 mProgramId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateProgram() );
456 GLint linked = GL_FALSE;
458 const bool binariesSupported = mCache.IsBinarySupported();
460 // if shader binaries are supported and ShaderData contains compiled bytecode?
461 if( binariesSupported && mProgramData->HasBinary() )
463 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->GetBufferSize());
465 CHECK_GL( mGlAbstraction, mGlAbstraction.ProgramBinary(mProgramId, mCache.ProgramBinaryFormat(), mProgramData->GetBufferData(), mProgramData->GetBufferSize()) );
467 CHECK_GL( mGlAbstraction, mGlAbstraction.ValidateProgram(mProgramId) );
470 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
472 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "ValidateProgram Status = %d\n", success);
474 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
476 if( GL_FALSE == linked )
478 DALI_LOG_ERROR("Failed to load program binary \n");
482 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
485 szLog = new char[ nLength ];
486 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog ) );
487 DALI_LOG_ERROR( "Program Link Error: %s\n", szLog );
498 // Fall back to compiling and linking the vertex and fragment sources
499 if( GL_FALSE == linked )
501 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Runtime compilation\n");
502 if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->GetVertexShader() ) )
504 if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->GetFragmentShader() ) )
508 if( binariesSupported && mLinked )
510 GLint binaryLength = 0;
513 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
514 DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - GL_PROGRAM_BINARY_LENGTH_OES: %d\n", binaryLength);
515 if( binaryLength > 0 )
517 // Allocate space for the bytecode in ShaderData
518 mProgramData->AllocateBuffer(binaryLength);
519 // Copy the bytecode to ShaderData
520 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->GetBufferData()) );
521 mCache.StoreBinary( mProgramData );
532 void Program::Unload()
536 if( this == mCache.GetCurrentProgram() )
538 CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(0) );
540 mCache.SetCurrentProgram( NULL );
545 LOG_GL( "DeleteProgram(%d)\n", mProgramId );
546 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteProgram( mProgramId ) );
554 bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* src )
558 LOG_GL( "CreateShader(%d)\n", shaderType );
559 shaderId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateShader( shaderType ) );
560 LOG_GL( "AttachShader(%d,%d)\n", mProgramId, shaderId );
561 CHECK_GL( mGlAbstraction, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
564 LOG_GL( "ShaderSource(%d)\n", shaderId );
565 CHECK_GL( mGlAbstraction, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
567 LOG_GL( "CompileShader(%d)\n", shaderId );
568 CHECK_GL( mGlAbstraction, mGlAbstraction.CompileShader( shaderId ) );
571 LOG_GL( "GetShaderiv(%d)\n", shaderId );
572 CHECK_GL( mGlAbstraction, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
574 if (compiled == GL_FALSE)
576 DALI_LOG_ERROR("Failed to compile shader\n");
577 LogWithLineNumbers(src);
580 mGlAbstraction.GetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &nLength);
583 Dali::Vector< char > szLog;
584 szLog.Resize( nLength );
585 mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, szLog.Begin() );
586 DALI_LOG_ERROR( "Shader Compiler Error: %s\n", szLog.Begin() );
589 DALI_ASSERT_ALWAYS( 0 && "Shader compilation failure" );
592 return compiled != 0;
597 LOG_GL( "LinkProgram(%d)\n", mProgramId );
598 CHECK_GL( mGlAbstraction, mGlAbstraction.LinkProgram( mProgramId ) );
601 LOG_GL( "GetProgramiv(%d)\n", mProgramId );
602 CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
604 if (linked == GL_FALSE)
606 DALI_LOG_ERROR("Shader failed to link \n");
609 mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength);
612 Dali::Vector< char > szLog;
613 szLog.Resize( nLength );
614 mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() );
615 DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog.Begin() );
618 DALI_ASSERT_ALWAYS( 0 && "Shader linking failure" );
621 mLinked = linked != GL_FALSE;
624 void Program::FreeShaders()
628 LOG_GL( "DeleteShader(%d)\n", mVertexShaderId );
629 CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
630 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mVertexShaderId ) );
634 if (mFragmentShaderId)
636 LOG_GL( "DeleteShader(%d)\n", mFragmentShaderId );
637 CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
638 CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
639 mFragmentShaderId = 0;
643 void Program::ResetAttribsUniformCache()
645 // reset attribute locations
646 for( unsigned i = 0; i < ATTRIB_TYPE_LAST; ++i )
648 mAttribLocations[ i ] = ATTRIB_UNKNOWN;
651 // reset all gl uniform locations
652 for( unsigned int i = 0; i < mUniformLocations.size(); ++i )
654 // reset gl program locations and names
655 mUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
658 // reset uniform cache
659 for( int i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i )
661 // GL initializes uniforms to 0
662 mUniformCacheInt[ i ] = 0;
663 mUniformCacheFloat[ i ] = 0.0f;
664 mUniformCacheFloat4[ i ][ 0 ] = 0.0f;
665 mUniformCacheFloat4[ i ][ 1 ] = 0.0f;
666 mUniformCacheFloat4[ i ][ 2 ] = 0.0f;
667 mUniformCacheFloat4[ i ][ 3 ] = 0.0f;
671 } // namespace Internal