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