a7fb497cda8fc58acf38bbe966d22afca964e2d9
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / program.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/shaders/program.h>
20
21 // EXTERNAL INCLUDES
22 #include <iomanip>
23 #include <cstring>
24
25 // INTERNAL INCLUDES
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/common/dali-vector.h>
28 #include <dali/public-api/common/constants.h>
29 #include <dali/integration-api/debug.h>
30 #include <dali/internal/common/shader-data.h>
31 #include <dali/integration-api/gl-defines.h>
32 #include <dali/internal/render/common/performance-monitor.h>
33 #include <dali/internal/render/shaders/program-cache.h>
34 #include <dali/internal/render/gl-resources/gl-call-debug.h>
35
36 namespace
37 {
38 void LogWithLineNumbers( const char * source )
39 {
40   unsigned int lineNumber = 0u;
41   const char *prev = source;
42   const char *ptr = prev;
43
44   while( true )
45   {
46     if(lineNumber > 200u)
47     {
48       break;
49     }
50     // seek the next end of line or end of text
51     while( *ptr!='\n' && *ptr != '\0' )
52     {
53       ++ptr;
54     }
55
56     std::string line( prev, ptr-prev );
57     Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugError, "%4d %s\n", lineNumber, line.c_str());
58
59     if( *ptr == '\0' )
60     {
61       break;
62     }
63     prev = ++ptr;
64     ++lineNumber;
65   }
66 }
67
68 } //namespace
69
70 namespace Dali
71 {
72
73 namespace Internal
74 {
75
76 // LOCAL STUFF
77 namespace
78 {
79
80 const char* gStdAttribs[ Program::ATTRIB_TYPE_LAST ] =
81 {
82   "aPosition",    // ATTRIB_POSITION
83   "aTexCoord",    // ATTRIB_TEXCOORD
84 };
85
86 const char* gStdUniforms[ Program::UNIFORM_TYPE_LAST ] =
87 {
88   "uMvpMatrix",           // UNIFORM_MVP_MATRIX
89   "uModelView",           // UNIFORM_MODELVIEW_MATRIX
90   "uProjection",          // UNIFORM_PROJECTION_MATRIX
91   "uModelMatrix",         // UNIFORM_MODEL_MATRIX,
92   "uViewMatrix",          // UNIFORM_VIEW_MATRIX,
93   "uNormalMatrix",        // UNIFORM_NORMAL_MATRIX
94   "uColor",               // UNIFORM_COLOR
95   "sTexture",             // UNIFORM_SAMPLER
96   "sTextureRect",         // UNIFORM_SAMPLER_RECT
97   "sEffect",              // UNIFORM_EFFECT_SAMPLER
98   "uSize"                 // UNIFORM_SIZE
99 };
100
101 }  // <unnamed> namespace
102
103 // IMPLEMENTATION
104
105 Program* Program::New( ProgramCache& cache, Internal::ShaderDataPtr shaderData, bool modifiesGeometry )
106 {
107   size_t shaderHash = shaderData->GetHashValue();
108   Program* program = cache.GetProgram( shaderHash );
109
110   if( NULL == program )
111   {
112     // program not found so create it
113     program = new Program( cache, shaderData, modifiesGeometry );
114     program->Load();
115     cache.AddProgram( shaderHash, program );
116   }
117
118   return program;
119 }
120
121 void Program::Use()
122 {
123   if ( mLinked )
124   {
125     if ( this != mCache.GetCurrentProgram() )
126     {
127       LOG_GL( "UseProgram(%d)\n", mProgramId );
128       CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(mProgramId) );
129
130       mCache.SetCurrentProgram( this );
131     }
132   }
133 }
134
135 bool Program::IsUsed()
136 {
137   return ( this == mCache.GetCurrentProgram() );
138 }
139
140 GLint Program::GetAttribLocation( AttribType type )
141 {
142   DALI_ASSERT_DEBUG(type != ATTRIB_UNKNOWN);
143
144   return GetCustomAttributeLocation( type );
145 }
146
147 unsigned int Program::RegisterCustomAttribute( const std::string& name )
148 {
149   unsigned int index = 0;
150   // find the value from cache
151   for( ;index < mAttributeLocations.size(); ++index )
152   {
153     if( mAttributeLocations[ index ].first == name )
154     {
155       // name found so return index
156       return index;
157     }
158   }
159   // if we get here, index is one past end so push back the new name
160   mAttributeLocations.push_back( std::make_pair( name, ATTRIB_UNKNOWN ) );
161   return index;
162 }
163
164 GLint Program::GetCustomAttributeLocation( unsigned int attributeIndex )
165 {
166   // debug check that index is within name cache
167   DALI_ASSERT_DEBUG( mAttributeLocations.size() > attributeIndex );
168
169   // check if we have already queried the location of the attribute
170   GLint location = mAttributeLocations[ attributeIndex ].second;
171
172   if( location == ATTRIB_UNKNOWN )
173   {
174     location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetAttribLocation( mProgramId, mAttributeLocations[ attributeIndex ].first.c_str() ) );
175
176     mAttributeLocations[ attributeIndex ].second = location;
177     LOG_GL( "GetAttributeLocation(program=%d,%s) = %d\n", mProgramId, mAttributeLocations[ attributeIndex ].first.c_str(), mAttributeLocations[ attributeIndex ].second );
178   }
179
180   return location;
181 }
182
183
184 unsigned int Program::RegisterUniform( const std::string& name )
185 {
186   unsigned int index = 0;
187   // find the value from cache
188   for( ;index < mUniformLocations.size(); ++index )
189   {
190     if( mUniformLocations[ index ].first == name )
191     {
192       // name found so return index
193       return index;
194     }
195   }
196   // if we get here, index is one past end so push back the new name
197   mUniformLocations.push_back( std::make_pair( name, UNIFORM_NOT_QUERIED ) );
198   return index;
199 }
200
201 GLint Program::GetUniformLocation( unsigned int uniformIndex )
202 {
203   // debug check that index is within name cache
204   DALI_ASSERT_DEBUG( mUniformLocations.size() > uniformIndex );
205
206   // check if we have already queried the location of the uniform
207   GLint location = mUniformLocations[ uniformIndex ].second;
208
209   if( location == UNIFORM_NOT_QUERIED )
210   {
211     location = CHECK_GL( mGlAbstraction, mGlAbstraction.GetUniformLocation( mProgramId, mUniformLocations[ uniformIndex ].first.c_str() ) );
212
213     mUniformLocations[ uniformIndex ].second = location;
214     LOG_GL( "GetUniformLocation(program=%d,%s) = %d\n", mProgramId, mUniformLocations[ uniformIndex ].first.c_str(), mUniformLocations[ uniformIndex ].second );
215   }
216
217   return location;
218 }
219
220 namespace
221 {
222 /**
223  * This struct is used to record the position of a uniform declaration
224  * within the fragment shader source code.
225  */
226 struct LocationPosition
227 {
228   GLint uniformLocation; ///< The location of the uniform (used as an identifier)
229   int position;          ///< the position of the uniform declaration
230   LocationPosition( GLint uniformLocation, int position )
231   : uniformLocation(uniformLocation), position(position)
232   {
233   }
234 };
235
236 bool sortByPosition( LocationPosition a, LocationPosition b )
237 {
238   return a.position < b.position;
239 }
240 }
241
242 void Program::GetActiveSamplerUniforms()
243 {
244   GLint numberOfActiveUniforms = -1;
245   GLint uniformMaxNameLength=-1;
246
247   mGlAbstraction.GetProgramiv( mProgramId, GL_ACTIVE_UNIFORMS, &numberOfActiveUniforms );
248   mGlAbstraction.GetProgramiv( mProgramId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformMaxNameLength );
249
250   std::vector<std::string> samplerNames;
251   char name[uniformMaxNameLength+1]; // Allow for null terminator
252   std::vector< LocationPosition >  samplerUniformLocations;
253
254   {
255     int nameLength = -1;
256     int number = -1;
257     GLenum type = GL_ZERO;
258
259     for( int i=0; i<numberOfActiveUniforms; ++i )
260     {
261       mGlAbstraction.GetActiveUniform( mProgramId, (GLuint)i, uniformMaxNameLength,
262                                        &nameLength, &number, &type, name );
263
264       if( type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE ) /// Is there a native sampler type?
265       {
266         GLuint location = mGlAbstraction.GetUniformLocation( mProgramId, name );
267         samplerNames.push_back(name);
268         samplerUniformLocations.push_back(LocationPosition(location, -1));
269       }
270     }
271   }
272
273   //Determine declaration order of each sampler
274   char* fragShader = strdup( mProgramData->GetFragmentShader() );
275   char* nextPtr;
276   const char* token = strtok_r( fragShader, " ;\n", &nextPtr );
277   int samplerPosition = 0;
278   while( token )
279   {
280     if( ( strncmp( token, "sampler2D", 9u ) == 0 ) || ( strncmp( token, "samplerCube", 11u ) == 0 ) )
281     {
282       bool found( false );
283       token = strtok_r( NULL, " ;\n", &nextPtr );
284       for( size_t i=0; i<samplerUniformLocations.size(); ++i )
285       {
286         if( samplerUniformLocations[i].position == -1 &&
287             strncmp( token, samplerNames[i].c_str(), samplerNames[i].size() ) == 0 )
288         {
289           samplerUniformLocations[i].position = samplerPosition++;
290           found = true;
291           break;
292         }
293       }
294       if( !found )
295       {
296         DALI_LOG_ERROR("Sampler uniform %s declared but not used in the shader\n", token );
297       }
298     }
299     else
300     {
301       token = strtok_r( NULL, " ;\n", &nextPtr );
302     }
303   }
304
305   free( fragShader );
306
307   // Re-order according to declaration order in the fragment source.
308   size_t samplerUniformCount = samplerUniformLocations.size();
309   if( samplerUniformCount > 1 )
310   {
311     std::sort( samplerUniformLocations.begin(), samplerUniformLocations.end(), sortByPosition);
312   }
313
314   mSamplerUniformLocations.resize( samplerUniformCount );
315   for( size_t i=0; i<samplerUniformCount; ++i )
316   {
317     mSamplerUniformLocations[i] = samplerUniformLocations[i].uniformLocation;
318   }
319 }
320
321 bool Program::GetSamplerUniformLocation( unsigned int index, GLint& location  )
322 {
323   bool result = false;
324   if( index < mSamplerUniformLocations.size() )
325   {
326     location = mSamplerUniformLocations[index];
327     result = true;
328   }
329   return result;
330 }
331
332 size_t Program::GetActiveSamplerCount() const
333 {
334   return mSamplerUniformLocations.size();
335 }
336
337 void Program::SetUniform1i( GLint location, GLint value0 )
338 {
339   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
340
341   if( UNIFORM_UNKNOWN == location )
342   {
343     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
344     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
345     // specified uniform variable will not be changed.following opengl silently do nothing
346     return;
347   }
348
349   // check if uniform location fits the cache
350   if( location >= MAX_UNIFORM_CACHE_SIZE )
351   {
352     // not cached, make the gl call
353     LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
354     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
355   }
356   else
357   {
358     // check if the value is different from what's already been set
359     if( value0 != mUniformCacheInt[ location ] )
360     {
361       // make the gl call
362       LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
363       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
364       // update cache
365       mUniformCacheInt[ location ] = value0;
366     }
367   }
368 }
369
370 void Program::SetUniform4i( GLint location, GLint value0, GLint value1, GLint value2, GLint value3 )
371 {
372   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
373
374   if( UNIFORM_UNKNOWN == location )
375   {
376     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
377     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
378     // specified uniform variable will not be changed.following opengl silently do nothing
379     return;
380   }
381
382   // Not caching these as based on current analysis this is not called that often by our shaders
383   LOG_GL( "Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3 );
384   CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
385 }
386
387 void Program::SetUniform1f( GLint location, GLfloat value0 )
388 {
389   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
390
391   if( UNIFORM_UNKNOWN == location )
392   {
393     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
394     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
395     // specified uniform variable will not be changed.following opengl silently do nothing
396     return;
397   }
398
399   // check if uniform location fits the cache
400   if( location >= MAX_UNIFORM_CACHE_SIZE )
401   {
402     // not cached, make the gl call
403     LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
404     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
405   }
406   else
407   {
408     // check if the same value has already been set, reset if it is different
409     if( ( fabsf(value0 - mUniformCacheFloat[ location ]) >= Math::MACHINE_EPSILON_1 ) )
410     {
411       // make the gl call
412       LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
413       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
414
415       // update cache
416       mUniformCacheFloat[ location ] = value0;
417     }
418   }
419 }
420
421 void Program::SetUniform2f( GLint location, GLfloat value0, GLfloat value1 )
422 {
423   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
424
425   if( UNIFORM_UNKNOWN == location )
426   {
427     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
428     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
429     // specified uniform variable will not be changed.following opengl silently do nothing
430     return;
431   }
432
433   // check if uniform location fits the cache
434   if( location >= MAX_UNIFORM_CACHE_SIZE )
435   {
436     // not cached, make the gl call
437     LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
438     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
439   }
440   else
441   {
442     // check if the same value has already been set, reset if it is different
443     if( ( fabsf(value0 - mUniformCacheFloat2[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
444         ( fabsf(value1 - mUniformCacheFloat2[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 ) )
445     {
446       // make the gl call
447       LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
448       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
449
450       // update cache
451       mUniformCacheFloat2[ location ][ 0 ] = value0;
452       mUniformCacheFloat2[ location ][ 1 ] = value1;
453     }
454   }
455 }
456
457 void Program::SetSizeUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
458 {
459   if( ( fabsf(value0 - mSizeUniformCache.x) >= Math::MACHINE_EPSILON_1 )||
460       ( fabsf(value1 - mSizeUniformCache.y) >= Math::MACHINE_EPSILON_1 )||
461       ( fabsf(value2 - mSizeUniformCache.z) >= Math::MACHINE_EPSILON_1 ) )
462   {
463     mSizeUniformCache.x = value0;
464     mSizeUniformCache.y = value1;
465     mSizeUniformCache.z = value2;
466     SetUniform3f( location, value0, value1, value2 );
467   }
468 }
469
470 void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
471 {
472   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
473
474   if( UNIFORM_UNKNOWN == location )
475   {
476     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
477     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
478     // specified uniform variable will not be changed.following opengl silently do nothing
479     return;
480   }
481
482   // Not caching these as based on current analysis this is not called that often by our shaders
483   LOG_GL( "Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2 );
484   CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
485 }
486
487 void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3 )
488 {
489   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
490
491   if( UNIFORM_UNKNOWN == location )
492   {
493     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
494     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
495     // specified uniform variable will not be changed.following opengl silently do nothing
496     return;
497   }
498
499   // check if uniform location fits the cache
500   if( location >= MAX_UNIFORM_CACHE_SIZE )
501   {
502     // not cached, make the gl call
503     LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
504     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
505   }
506   else
507   {
508     // check if the same value has already been set, reset if any component is different
509     // checking index 3 first because we're often animating alpha (rgba)
510     if( ( fabsf(value3 - mUniformCacheFloat4[ location ][ 3 ]) >= Math::MACHINE_EPSILON_1 )||
511         ( fabsf(value0 - mUniformCacheFloat4[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
512         ( fabsf(value1 - mUniformCacheFloat4[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 )||
513         ( fabsf(value2 - mUniformCacheFloat4[ location ][ 2 ]) >= Math::MACHINE_EPSILON_1 ) )
514     {
515       // make the gl call
516       LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
517       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
518       // update cache
519       mUniformCacheFloat4[ location ][ 0 ] = value0;
520       mUniformCacheFloat4[ location ][ 1 ] = value1;
521       mUniformCacheFloat4[ location ][ 2 ] = value2;
522       mUniformCacheFloat4[ location ][ 3 ] = value3;
523     }
524   }
525 }
526
527 void Program::SetUniformMatrix4fv( GLint location, GLsizei count, const GLfloat* value )
528 {
529   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
530
531   if( UNIFORM_UNKNOWN == location )
532   {
533     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
534     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
535     // specified uniform variable will not be changed.following opengl silently do nothing
536     return;
537   }
538
539   // Not caching these calls. Based on current analysis this is called very often
540   // but with different values (we're using this for MVP matrices)
541   // NOTE! we never want driver or GPU to transpose
542   LOG_GL( "UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
543   CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
544 }
545
546 void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat* value )
547 {
548   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
549
550   if( UNIFORM_UNKNOWN == location )
551   {
552     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
553     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
554     // specified uniform variable will not be changed.following opengl silently do nothing
555     return;
556   }
557
558
559   // Not caching these calls. Based on current analysis this is called very often
560   // but with different values (we're using this for MVP matrices)
561   // NOTE! we never want driver or GPU to transpose
562   LOG_GL( "UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
563   CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
564 }
565
566 void Program::GlContextCreated()
567 {
568 }
569
570 void Program::GlContextDestroyed()
571 {
572   mLinked = false;
573   mVertexShaderId = 0;
574   mFragmentShaderId = 0;
575   mProgramId = 0;
576
577   ResetAttribsUniformCache();
578 }
579
580 bool Program::ModifiesGeometry()
581 {
582   return mModifiesGeometry;
583 }
584
585 Program::Program( ProgramCache& cache, Internal::ShaderDataPtr shaderData, bool modifiesGeometry )
586 : mCache( cache ),
587   mGlAbstraction( mCache.GetGlAbstraction() ),
588   mProjectionMatrix( NULL ),
589   mViewMatrix( NULL ),
590   mLinked( false ),
591   mVertexShaderId( 0 ),
592   mFragmentShaderId( 0 ),
593   mProgramId( 0 ),
594   mProgramData(shaderData),
595   mModifiesGeometry( modifiesGeometry )
596 {
597   // reserve space for standard attributes
598   mAttributeLocations.reserve( ATTRIB_TYPE_LAST );
599   for( int i=0; i<ATTRIB_TYPE_LAST; ++i )
600   {
601     RegisterCustomAttribute( gStdAttribs[i] );
602   }
603
604   // reserve space for standard uniforms
605   mUniformLocations.reserve( UNIFORM_TYPE_LAST );
606   // reset built in uniform names in cache
607   for( int i = 0; i < UNIFORM_TYPE_LAST; ++i )
608   {
609     RegisterUniform( gStdUniforms[ i ] );
610   }
611
612   // reset values
613   ResetAttribsUniformCache();
614 }
615
616 Program::~Program()
617 {
618   Unload();
619 }
620
621 void Program::Load()
622 {
623   DALI_ASSERT_ALWAYS( NULL != mProgramData.Get() && "Program data is not initialized" );
624   DALI_ASSERT_DEBUG( mProgramId == 0 && "mProgramId != 0, so about to leak a GL resource by overwriting it." );
625
626   LOG_GL( "CreateProgram()\n" );
627   mProgramId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateProgram() );
628
629   GLint linked = GL_FALSE;
630
631   const bool binariesSupported = mCache.IsBinarySupported();
632
633   // if shader binaries are supported and ShaderData contains compiled bytecode?
634   if( binariesSupported && mProgramData->HasBinary() )
635   {
636     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->GetBufferSize());
637
638     CHECK_GL( mGlAbstraction, mGlAbstraction.ProgramBinary(mProgramId, mCache.ProgramBinaryFormat(), mProgramData->GetBufferData(), mProgramData->GetBufferSize()) );
639
640     CHECK_GL( mGlAbstraction, mGlAbstraction.ValidateProgram(mProgramId) );
641
642     GLint success;
643     CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
644
645     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "ValidateProgram Status = %d\n", success);
646
647     CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
648
649     if( GL_FALSE == linked )
650     {
651       DALI_LOG_ERROR("Failed to load program binary \n");
652
653       GLint nLength;
654       CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
655       if(nLength > 0)
656       {
657         Dali::Vector< char > szLog;
658         szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
659         CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() ) );
660         DALI_LOG_ERROR( "Program Link Error: %s\n", szLog.Begin() );
661       }
662     }
663     else
664     {
665       mLinked = true;
666       DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Reused binary.\n" );
667     }
668   }
669
670   // Fall back to compiling and linking the vertex and fragment sources
671   if( GL_FALSE == linked )
672   {
673     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Runtime compilation\n");
674     if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->GetVertexShader() ) )
675     {
676       if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->GetFragmentShader() ) )
677       {
678         Link();
679
680         if( binariesSupported && mLinked )
681         {
682           GLint  binaryLength = 0;
683           GLenum binaryFormat;
684           DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Compiled and linked.\n\nVS:\n%s\nFS:\n%s\n", mProgramData->GetVertexShader(), mProgramData->GetFragmentShader() );
685
686           CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
687           DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - GL_PROGRAM_BINARY_LENGTH_OES: %d\n", binaryLength);
688           if( binaryLength > 0 )
689           {
690             // Allocate space for the bytecode in ShaderData
691             mProgramData->AllocateBuffer(binaryLength);
692             // Copy the bytecode to ShaderData
693             CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->GetBufferData()) );
694             mCache.StoreBinary( mProgramData );
695             DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Saved binary.\n" );
696           }
697         }
698       }
699     }
700   }
701
702   GetActiveSamplerUniforms();
703
704   // No longer needed
705   FreeShaders();
706 }
707
708 void Program::Unload()
709 {
710   FreeShaders();
711
712   if( this == mCache.GetCurrentProgram() )
713   {
714     CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(0) );
715
716     mCache.SetCurrentProgram( NULL );
717   }
718
719   if (mProgramId)
720   {
721     LOG_GL( "DeleteProgram(%d)\n", mProgramId );
722     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteProgram( mProgramId ) );
723     mProgramId = 0;
724   }
725
726   mLinked = false;
727
728 }
729
730 bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* src )
731 {
732   if (!shaderId)
733   {
734     LOG_GL( "CreateShader(%d)\n", shaderType );
735     shaderId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateShader( shaderType ) );
736     LOG_GL( "AttachShader(%d,%d)\n", mProgramId, shaderId );
737     CHECK_GL( mGlAbstraction, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
738   }
739
740   LOG_GL( "ShaderSource(%d)\n", shaderId );
741   CHECK_GL( mGlAbstraction, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
742
743   LOG_GL( "CompileShader(%d)\n", shaderId );
744   CHECK_GL( mGlAbstraction, mGlAbstraction.CompileShader( shaderId ) );
745
746   GLint compiled;
747   LOG_GL( "GetShaderiv(%d)\n", shaderId );
748   CHECK_GL( mGlAbstraction, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
749
750   if (compiled == GL_FALSE)
751   {
752     DALI_LOG_ERROR("Failed to compile shader\n");
753     LogWithLineNumbers(src);
754
755     GLint nLength;
756     mGlAbstraction.GetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &nLength);
757     if(nLength > 0)
758     {
759       Dali::Vector< char > szLog;
760       szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
761       mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, szLog.Begin() );
762       DALI_LOG_ERROR( "Shader Compiler Error: %s\n", szLog.Begin() );
763     }
764
765     DALI_ASSERT_ALWAYS( 0 && "Shader compilation failure" );
766   }
767
768   return compiled != 0;
769 }
770
771 void Program::Link()
772 {
773   LOG_GL( "LinkProgram(%d)\n", mProgramId );
774   CHECK_GL( mGlAbstraction, mGlAbstraction.LinkProgram( mProgramId ) );
775
776   GLint linked;
777   LOG_GL( "GetProgramiv(%d)\n", mProgramId );
778   CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
779
780   if (linked == GL_FALSE)
781   {
782     DALI_LOG_ERROR("Shader failed to link \n");
783
784     GLint nLength;
785     mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength);
786     if(nLength > 0)
787     {
788       Dali::Vector< char > szLog;
789       szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
790       mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() );
791       DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog.Begin() );
792     }
793
794     DALI_ASSERT_ALWAYS( 0 && "Shader linking failure" );
795   }
796
797   mLinked = linked != GL_FALSE;
798 }
799
800 void Program::FreeShaders()
801 {
802   if (mVertexShaderId)
803   {
804     LOG_GL( "DeleteShader(%d)\n", mVertexShaderId );
805     CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
806     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mVertexShaderId ) );
807     mVertexShaderId = 0;
808   }
809
810   if (mFragmentShaderId)
811   {
812     LOG_GL( "DeleteShader(%d)\n", mFragmentShaderId );
813     CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
814     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
815     mFragmentShaderId = 0;
816   }
817 }
818
819 void Program::ResetAttribsUniformCache()
820 {
821   // reset attribute locations
822   for( unsigned i = 0; i < mAttributeLocations.size() ; ++i )
823   {
824     mAttributeLocations[ i ].second = ATTRIB_UNKNOWN;
825   }
826
827   // reset all gl uniform locations
828   for( unsigned int i = 0; i < mUniformLocations.size(); ++i )
829   {
830     // reset gl program locations and names
831     mUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
832   }
833
834   mSamplerUniformLocations.clear();
835
836   // reset uniform caches
837   mSizeUniformCache.x = mSizeUniformCache.y = mSizeUniformCache.z = 0.f;
838
839   for( int i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i )
840   {
841     // GL initializes uniforms to 0
842     mUniformCacheInt[ i ] = 0;
843     mUniformCacheFloat[ i ] = 0.0f;
844     mUniformCacheFloat2[ i ][ 0 ] = 0.0f;
845     mUniformCacheFloat2[ i ][ 1 ] = 0.0f;
846     mUniformCacheFloat4[ i ][ 0 ] = 0.0f;
847     mUniformCacheFloat4[ i ][ 1 ] = 0.0f;
848     mUniformCacheFloat4[ i ][ 2 ] = 0.0f;
849     mUniformCacheFloat4[ i ][ 3 ] = 0.0f;
850   }
851 }
852
853 } // namespace Internal
854
855 } // namespace Dali