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