Revert "[Tizen] Add codes for Dali Windows Backend"
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / program.cpp
1 /*
2  * Copyright (c) 2017 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, static_cast< GLuint >( i ), uniformMaxNameLength,
262                                        &nameLength, &number, &type, name );
263
264       if( type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_EXTERNAL_OES )
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 = NULL;
276   const char* token = strtok_r( fragShader, " ;\n", &nextPtr );
277   int samplerPosition = 0;
278   while( token )
279   {
280     if( ( strncmp( token, "sampler2D", 9u )    == 0 ) ||
281         ( strncmp( token, "samplerCube", 11u ) == 0 ) ||
282         ( strncmp( token, "samplerExternalOES", 18u ) == 0 ) )
283     {
284       bool found( false );
285       token = strtok_r( NULL, " ;\n", &nextPtr );
286       for( size_t i=0; i<samplerUniformLocations.size(); ++i )
287       {
288         if( samplerUniformLocations[i].position == -1 &&
289             strncmp( token, samplerNames[i].c_str(), samplerNames[i].size() ) == 0 )
290         {
291           samplerUniformLocations[i].position = samplerPosition++;
292           found = true;
293           break;
294         }
295       }
296       if( !found )
297       {
298         DALI_LOG_ERROR("Sampler uniform %s declared but not used in the shader\n", token );
299       }
300     }
301     else
302     {
303       token = strtok_r( NULL, " ;\n", &nextPtr );
304     }
305   }
306
307   free( fragShader );
308
309   // Re-order according to declaration order in the fragment source.
310   size_t samplerUniformCount = samplerUniformLocations.size();
311   if( samplerUniformCount > 1 )
312   {
313     std::sort( samplerUniformLocations.begin(), samplerUniformLocations.end(), sortByPosition);
314   }
315
316   mSamplerUniformLocations.resize( samplerUniformCount );
317   for( size_t i=0; i<samplerUniformCount; ++i )
318   {
319     mSamplerUniformLocations[i] = samplerUniformLocations[i].uniformLocation;
320   }
321 }
322
323 bool Program::GetSamplerUniformLocation( unsigned int index, GLint& location  )
324 {
325   bool result = false;
326   if( index < mSamplerUniformLocations.size() )
327   {
328     location = mSamplerUniformLocations[index];
329     result = true;
330   }
331   return result;
332 }
333
334 size_t Program::GetActiveSamplerCount() const
335 {
336   return mSamplerUniformLocations.size();
337 }
338
339 void Program::SetUniform1i( GLint location, GLint value0 )
340 {
341   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
342
343   if( UNIFORM_UNKNOWN == location )
344   {
345     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
346     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
347     // specified uniform variable will not be changed.following opengl silently do nothing
348     return;
349   }
350
351   // check if uniform location fits the cache
352   if( location >= MAX_UNIFORM_CACHE_SIZE )
353   {
354     // not cached, make the gl call
355     LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
356     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
357   }
358   else
359   {
360     // check if the value is different from what's already been set
361     if( value0 != mUniformCacheInt[ location ] )
362     {
363       // make the gl call
364       LOG_GL( "Uniform1i(%d,%d)\n", location, value0 );
365       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1i( location, value0 ) );
366       // update cache
367       mUniformCacheInt[ location ] = value0;
368     }
369   }
370 }
371
372 void Program::SetUniform4i( GLint location, GLint value0, GLint value1, GLint value2, GLint value3 )
373 {
374   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
375
376   if( UNIFORM_UNKNOWN == location )
377   {
378     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
379     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
380     // specified uniform variable will not be changed.following opengl silently do nothing
381     return;
382   }
383
384   // Not caching these as based on current analysis this is not called that often by our shaders
385   LOG_GL( "Uniform4i(%d,%d,%d,%d,%d)\n", location, value0, value1, value2, value3 );
386   CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4i( location, value0, value1, value2, value3 ) );
387 }
388
389 void Program::SetUniform1f( GLint location, GLfloat value0 )
390 {
391   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
392
393   if( UNIFORM_UNKNOWN == location )
394   {
395     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
396     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
397     // specified uniform variable will not be changed.following opengl silently do nothing
398     return;
399   }
400
401   // check if uniform location fits the cache
402   if( location >= MAX_UNIFORM_CACHE_SIZE )
403   {
404     // not cached, make the gl call
405     LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
406     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
407   }
408   else
409   {
410     // check if the same value has already been set, reset if it is different
411     if( ( fabsf(value0 - mUniformCacheFloat[ location ]) >= Math::MACHINE_EPSILON_1 ) )
412     {
413       // make the gl call
414       LOG_GL( "Uniform1f(%d,%f)\n", location, value0 );
415       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform1f( location, value0 ) );
416
417       // update cache
418       mUniformCacheFloat[ location ] = value0;
419     }
420   }
421 }
422
423 void Program::SetUniform2f( GLint location, GLfloat value0, GLfloat value1 )
424 {
425   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
426
427   if( UNIFORM_UNKNOWN == location )
428   {
429     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
430     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
431     // specified uniform variable will not be changed.following opengl silently do nothing
432     return;
433   }
434
435   // check if uniform location fits the cache
436   if( location >= MAX_UNIFORM_CACHE_SIZE )
437   {
438     // not cached, make the gl call
439     LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
440     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
441   }
442   else
443   {
444     // check if the same value has already been set, reset if it is different
445     if( ( fabsf(value0 - mUniformCacheFloat2[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
446         ( fabsf(value1 - mUniformCacheFloat2[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 ) )
447     {
448       // make the gl call
449       LOG_GL( "Uniform2f(%d,%f,%f)\n", location, value0, value1 );
450       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform2f( location, value0, value1 ) );
451
452       // update cache
453       mUniformCacheFloat2[ location ][ 0 ] = value0;
454       mUniformCacheFloat2[ location ][ 1 ] = value1;
455     }
456   }
457 }
458
459 void Program::SetSizeUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
460 {
461   if( ( fabsf(value0 - mSizeUniformCache.x) >= Math::MACHINE_EPSILON_1 )||
462       ( fabsf(value1 - mSizeUniformCache.y) >= Math::MACHINE_EPSILON_1 )||
463       ( fabsf(value2 - mSizeUniformCache.z) >= Math::MACHINE_EPSILON_1 ) )
464   {
465     mSizeUniformCache.x = value0;
466     mSizeUniformCache.y = value1;
467     mSizeUniformCache.z = value2;
468     SetUniform3f( location, value0, value1, value2 );
469   }
470 }
471
472 void Program::SetUniform3f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2 )
473 {
474   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
475
476   if( UNIFORM_UNKNOWN == location )
477   {
478     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
479     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
480     // specified uniform variable will not be changed.following opengl silently do nothing
481     return;
482   }
483
484   // Not caching these as based on current analysis this is not called that often by our shaders
485   LOG_GL( "Uniform3f(%d,%f,%f,%f)\n", location, value0, value1, value2 );
486   CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform3f( location, value0, value1, value2 ) );
487 }
488
489 void Program::SetUniform4f( GLint location, GLfloat value0, GLfloat value1, GLfloat value2, GLfloat value3 )
490 {
491   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
492
493   if( UNIFORM_UNKNOWN == location )
494   {
495     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
496     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
497     // specified uniform variable will not be changed.following opengl silently do nothing
498     return;
499   }
500
501   // check if uniform location fits the cache
502   if( location >= MAX_UNIFORM_CACHE_SIZE )
503   {
504     // not cached, make the gl call
505     LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
506     CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
507   }
508   else
509   {
510     // check if the same value has already been set, reset if any component is different
511     // checking index 3 first because we're often animating alpha (rgba)
512     if( ( fabsf(value3 - mUniformCacheFloat4[ location ][ 3 ]) >= Math::MACHINE_EPSILON_1 )||
513         ( fabsf(value0 - mUniformCacheFloat4[ location ][ 0 ]) >= Math::MACHINE_EPSILON_1 )||
514         ( fabsf(value1 - mUniformCacheFloat4[ location ][ 1 ]) >= Math::MACHINE_EPSILON_1 )||
515         ( fabsf(value2 - mUniformCacheFloat4[ location ][ 2 ]) >= Math::MACHINE_EPSILON_1 ) )
516     {
517       // make the gl call
518       LOG_GL( "Uniform4f(%d,%f,%f,%f,%f)\n", location, value0, value1, value2, value3 );
519       CHECK_GL( mGlAbstraction, mGlAbstraction.Uniform4f( location, value0, value1, value2, value3 ) );
520       // update cache
521       mUniformCacheFloat4[ location ][ 0 ] = value0;
522       mUniformCacheFloat4[ location ][ 1 ] = value1;
523       mUniformCacheFloat4[ location ][ 2 ] = value2;
524       mUniformCacheFloat4[ location ][ 3 ] = value3;
525     }
526   }
527 }
528
529 void Program::SetUniformMatrix4fv( GLint location, GLsizei count, const GLfloat* value )
530 {
531   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
532
533   if( UNIFORM_UNKNOWN == location )
534   {
535     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
536     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
537     // specified uniform variable will not be changed.following opengl silently do nothing
538     return;
539   }
540
541   // Not caching these calls. Based on current analysis this is called very often
542   // but with different values (we're using this for MVP matrices)
543   // NOTE! we never want driver or GPU to transpose
544   LOG_GL( "UniformMatrix4fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
545   CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix4fv( location, count, GL_FALSE, value ) );
546 }
547
548 void Program::SetUniformMatrix3fv( GLint location, GLsizei count, const GLfloat* value )
549 {
550   DALI_ASSERT_DEBUG( IsUsed() ); // should not call this if this program is not used
551
552   if( UNIFORM_UNKNOWN == location )
553   {
554     // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml : Notes
555     // If location is equal to UNIFORM_UNKNOWN, the data passed in will be silently ignored and the
556     // specified uniform variable will not be changed.following opengl silently do nothing
557     return;
558   }
559
560
561   // Not caching these calls. Based on current analysis this is called very often
562   // but with different values (we're using this for MVP matrices)
563   // NOTE! we never want driver or GPU to transpose
564   LOG_GL( "UniformMatrix3fv(%d,%d,GL_FALSE,%x)\n", location, count, value );
565   CHECK_GL( mGlAbstraction, mGlAbstraction.UniformMatrix3fv( location, count, GL_FALSE, value ) );
566 }
567
568 void Program::GlContextCreated()
569 {
570 }
571
572 void Program::GlContextDestroyed()
573 {
574   mLinked = false;
575   mVertexShaderId = 0;
576   mFragmentShaderId = 0;
577   mProgramId = 0;
578
579   ResetAttribsUniformCache();
580 }
581
582 bool Program::ModifiesGeometry()
583 {
584   return mModifiesGeometry;
585 }
586
587 Program::Program( ProgramCache& cache, Internal::ShaderDataPtr shaderData, bool modifiesGeometry )
588 : mCache( cache ),
589   mGlAbstraction( mCache.GetGlAbstraction() ),
590   mProjectionMatrix( NULL ),
591   mViewMatrix( NULL ),
592   mLinked( false ),
593   mVertexShaderId( 0 ),
594   mFragmentShaderId( 0 ),
595   mProgramId( 0 ),
596   mProgramData(shaderData),
597   mModifiesGeometry( modifiesGeometry )
598 {
599   // reserve space for standard attributes
600   mAttributeLocations.reserve( ATTRIB_TYPE_LAST );
601   for( int i=0; i<ATTRIB_TYPE_LAST; ++i )
602   {
603     RegisterCustomAttribute( gStdAttribs[i] );
604   }
605
606   // reserve space for standard uniforms
607   mUniformLocations.reserve( UNIFORM_TYPE_LAST );
608   // reset built in uniform names in cache
609   for( int i = 0; i < UNIFORM_TYPE_LAST; ++i )
610   {
611     RegisterUniform( gStdUniforms[ i ] );
612   }
613
614   // reset values
615   ResetAttribsUniformCache();
616 }
617
618 Program::~Program()
619 {
620   Unload();
621 }
622
623 void Program::Load()
624 {
625   DALI_ASSERT_ALWAYS( NULL != mProgramData.Get() && "Program data is not initialized" );
626   DALI_ASSERT_DEBUG( mProgramId == 0 && "mProgramId != 0, so about to leak a GL resource by overwriting it." );
627
628   LOG_GL( "CreateProgram()\n" );
629   mProgramId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateProgram() );
630
631   GLint linked = GL_FALSE;
632
633   const bool binariesSupported = mCache.IsBinarySupported();
634
635   // if shader binaries are supported and ShaderData contains compiled bytecode?
636   if( binariesSupported && mProgramData->HasBinary() )
637   {
638     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Using Compiled Shader, Size = %d\n", mProgramData->GetBufferSize());
639
640     CHECK_GL( mGlAbstraction, mGlAbstraction.ProgramBinary(mProgramId, mCache.ProgramBinaryFormat(), mProgramData->GetBufferData(), mProgramData->GetBufferSize()) );
641
642     CHECK_GL( mGlAbstraction, mGlAbstraction.ValidateProgram(mProgramId) );
643
644     GLint success;
645     CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_VALIDATE_STATUS, &success ) );
646
647     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "ValidateProgram Status = %d\n", success);
648
649     CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
650
651     if( GL_FALSE == linked )
652     {
653       DALI_LOG_ERROR("Failed to load program binary \n");
654
655       GLint nLength;
656       CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength) );
657       if(nLength > 0)
658       {
659         Dali::Vector< char > szLog;
660         szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
661         CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() ) );
662         DALI_LOG_ERROR( "Program Link Error: %s\n", szLog.Begin() );
663       }
664     }
665     else
666     {
667       mLinked = true;
668       DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Reused binary.\n" );
669     }
670   }
671
672   // Fall back to compiling and linking the vertex and fragment sources
673   if( GL_FALSE == linked )
674   {
675     DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - Runtime compilation\n");
676     if( CompileShader( GL_VERTEX_SHADER, mVertexShaderId, mProgramData->GetVertexShader() ) )
677     {
678       if( CompileShader( GL_FRAGMENT_SHADER, mFragmentShaderId, mProgramData->GetFragmentShader() ) )
679       {
680         Link();
681
682         if( binariesSupported && mLinked )
683         {
684           GLint  binaryLength = 0;
685           GLenum binaryFormat;
686           DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Compiled and linked.\n\nVS:\n%s\nFS:\n%s\n", mProgramData->GetVertexShader(), mProgramData->GetFragmentShader() );
687
688           CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv(mProgramId, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength) );
689           DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "Program::Load() - GL_PROGRAM_BINARY_LENGTH_OES: %d\n", binaryLength);
690           if( binaryLength > 0 )
691           {
692             // Allocate space for the bytecode in ShaderData
693             mProgramData->AllocateBuffer(binaryLength);
694             // Copy the bytecode to ShaderData
695             CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramBinary(mProgramId, binaryLength, NULL, &binaryFormat, mProgramData->GetBufferData()) );
696             mCache.StoreBinary( mProgramData );
697             DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "Saved binary.\n" );
698           }
699         }
700       }
701     }
702   }
703
704   GetActiveSamplerUniforms();
705
706   // No longer needed
707   FreeShaders();
708 }
709
710 void Program::Unload()
711 {
712   FreeShaders();
713
714   if( this == mCache.GetCurrentProgram() )
715   {
716     CHECK_GL( mGlAbstraction, mGlAbstraction.UseProgram(0) );
717
718     mCache.SetCurrentProgram( NULL );
719   }
720
721   if (mProgramId)
722   {
723     LOG_GL( "DeleteProgram(%d)\n", mProgramId );
724     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteProgram( mProgramId ) );
725     mProgramId = 0;
726   }
727
728   mLinked = false;
729
730 }
731
732 bool Program::CompileShader( GLenum shaderType, GLuint& shaderId, const char* src )
733 {
734   if (!shaderId)
735   {
736     LOG_GL( "CreateShader(%d)\n", shaderType );
737     shaderId = CHECK_GL( mGlAbstraction, mGlAbstraction.CreateShader( shaderType ) );
738     LOG_GL( "AttachShader(%d,%d)\n", mProgramId, shaderId );
739     CHECK_GL( mGlAbstraction, mGlAbstraction.AttachShader( mProgramId, shaderId ) );
740   }
741
742   LOG_GL( "ShaderSource(%d)\n", shaderId );
743   CHECK_GL( mGlAbstraction, mGlAbstraction.ShaderSource(shaderId, 1, &src, NULL ) );
744
745   LOG_GL( "CompileShader(%d)\n", shaderId );
746   CHECK_GL( mGlAbstraction, mGlAbstraction.CompileShader( shaderId ) );
747
748   GLint compiled;
749   LOG_GL( "GetShaderiv(%d)\n", shaderId );
750   CHECK_GL( mGlAbstraction, mGlAbstraction.GetShaderiv( shaderId, GL_COMPILE_STATUS, &compiled ) );
751
752   if (compiled == GL_FALSE)
753   {
754     DALI_LOG_ERROR("Failed to compile shader\n");
755     LogWithLineNumbers(src);
756
757     GLint nLength;
758     mGlAbstraction.GetShaderiv( shaderId, GL_INFO_LOG_LENGTH, &nLength);
759     if(nLength > 0)
760     {
761       Dali::Vector< char > szLog;
762       szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
763       mGlAbstraction.GetShaderInfoLog( shaderId, nLength, &nLength, szLog.Begin() );
764       DALI_LOG_ERROR( "Shader Compiler Error: %s\n", szLog.Begin() );
765     }
766
767     DALI_ASSERT_ALWAYS( 0 && "Shader compilation failure" );
768   }
769
770   return compiled != 0;
771 }
772
773 void Program::Link()
774 {
775   LOG_GL( "LinkProgram(%d)\n", mProgramId );
776   CHECK_GL( mGlAbstraction, mGlAbstraction.LinkProgram( mProgramId ) );
777
778   GLint linked;
779   LOG_GL( "GetProgramiv(%d)\n", mProgramId );
780   CHECK_GL( mGlAbstraction, mGlAbstraction.GetProgramiv( mProgramId, GL_LINK_STATUS, &linked ) );
781
782   if (linked == GL_FALSE)
783   {
784     DALI_LOG_ERROR("Shader failed to link \n");
785
786     GLint nLength;
787     mGlAbstraction.GetProgramiv( mProgramId, GL_INFO_LOG_LENGTH, &nLength);
788     if(nLength > 0)
789     {
790       Dali::Vector< char > szLog;
791       szLog.Reserve( nLength ); // Don't call Resize as we don't want to initialise the data, just reserve a buffer
792       mGlAbstraction.GetProgramInfoLog( mProgramId, nLength, &nLength, szLog.Begin() );
793       DALI_LOG_ERROR( "Shader Link Error: %s\n", szLog.Begin() );
794     }
795
796     DALI_ASSERT_ALWAYS( 0 && "Shader linking failure" );
797   }
798
799   mLinked = linked != GL_FALSE;
800 }
801
802 void Program::FreeShaders()
803 {
804   if (mVertexShaderId)
805   {
806     LOG_GL( "DeleteShader(%d)\n", mVertexShaderId );
807     CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mVertexShaderId ) );
808     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mVertexShaderId ) );
809     mVertexShaderId = 0;
810   }
811
812   if (mFragmentShaderId)
813   {
814     LOG_GL( "DeleteShader(%d)\n", mFragmentShaderId );
815     CHECK_GL( mGlAbstraction, mGlAbstraction.DetachShader( mProgramId, mFragmentShaderId ) );
816     CHECK_GL( mGlAbstraction, mGlAbstraction.DeleteShader( mFragmentShaderId ) );
817     mFragmentShaderId = 0;
818   }
819 }
820
821 void Program::ResetAttribsUniformCache()
822 {
823   // reset attribute locations
824   for( unsigned i = 0; i < mAttributeLocations.size() ; ++i )
825   {
826     mAttributeLocations[ i ].second = ATTRIB_UNKNOWN;
827   }
828
829   // reset all gl uniform locations
830   for( unsigned int i = 0; i < mUniformLocations.size(); ++i )
831   {
832     // reset gl program locations and names
833     mUniformLocations[ i ].second = UNIFORM_NOT_QUERIED;
834   }
835
836   mSamplerUniformLocations.clear();
837
838   // reset uniform caches
839   mSizeUniformCache.x = mSizeUniformCache.y = mSizeUniformCache.z = 0.f;
840
841   for( int i = 0; i < MAX_UNIFORM_CACHE_SIZE; ++i )
842   {
843     // GL initializes uniforms to 0
844     mUniformCacheInt[ i ] = 0;
845     mUniformCacheFloat[ i ] = 0.0f;
846     mUniformCacheFloat2[ i ][ 0 ] = 0.0f;
847     mUniformCacheFloat2[ i ][ 1 ] = 0.0f;
848     mUniformCacheFloat4[ i ][ 0 ] = 0.0f;
849     mUniformCacheFloat4[ i ][ 1 ] = 0.0f;
850     mUniformCacheFloat4[ i ][ 2 ] = 0.0f;
851     mUniformCacheFloat4[ i ][ 3 ] = 0.0f;
852   }
853 }
854
855 } // namespace Internal
856
857 } // namespace Dali