Merge "Klockwork: Remove unreachable code" into tizen
[platform/core/uifw/dali-core.git] / dali / internal / render / shaders / shader.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/shader.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/render/queue/render-queue.h>
23 #include <dali/internal/render/common/render-debug.h>
24 #include <dali/internal/render/common/post-process-resource-dispatcher.h>
25 #include <dali/internal/render/gl-resources/texture.h>
26 #include <dali/internal/render/gl-resources/texture-cache.h>
27 #include <dali/internal/render/gl-resources/texture-units.h>
28 #include <dali/internal/render/shaders/program.h>
29 #include <dali/internal/render/shaders/uniform-meta.h>
30 #include <dali/internal/common/image-sampler.h>
31
32 // See render-debug.h
33 #ifdef DALI_PRINT_RENDER_INFO
34
35 #include <sstream>
36 #define DALI_DEBUG_OSTREAM(streamName) std::stringstream streamName;
37
38 #define DALI_PRINT_UNIFORM(streamName,bufferIndex,name,value) \
39   { \
40     streamName << " " << name << ": " << value; \
41   }
42
43 #define DALI_PRINT_CUSTOM_UNIFORM(streamName,bufferIndex,name,property) \
44   { \
45     streamName << " " << name << ": "; \
46     property.DebugPrint( streamName, bufferIndex ); \
47   }
48
49 #define DALI_PRINT_SHADER_UNIFORMS(streamName) \
50   { \
51     std::string debugString( streamName.str() ); \
52     DALI_LOG_RENDER_INFO( "           %s\n", debugString.c_str() ); \
53   }
54
55 #else // DALI_PRINT_RENDER_INFO
56
57 #define DALI_DEBUG_OSTREAM(streamName)
58 #define DALI_PRINT_UNIFORM(streamName,bufferIndex,name,value)
59 #define DALI_PRINT_CUSTOM_UNIFORM(streamName,bufferIndex,name,property)
60 #define DALI_PRINT_SHADER_UNIFORMS(streamName)
61
62 #endif // DALI_PRINT_RENDER_INFO
63
64 namespace Dali
65 {
66
67 namespace Internal
68 {
69
70 namespace SceneGraph
71 {
72
73 namespace // unnamed namespace
74 {
75
76 // Convert Geometry type bitmask to an array index
77 inline unsigned int GetGeometryTypeIndex(GeometryType type)
78 {
79   unsigned int index = Log<GEOMETRY_TYPE_IMAGE>::value;
80   if ( type & GEOMETRY_TYPE_IMAGE )
81   {
82     index = Log<GEOMETRY_TYPE_IMAGE>::value;
83   }
84   else if ( type & GEOMETRY_TYPE_TEXT )
85   {
86     index = Log<GEOMETRY_TYPE_TEXT>::value;
87   }
88   else if ( type & GEOMETRY_TYPE_UNTEXTURED_MESH )
89   {
90     index = Log<GEOMETRY_TYPE_UNTEXTURED_MESH>::value;
91   }
92   else if ( type & GEOMETRY_TYPE_TEXTURED_MESH )
93   {
94     index = Log<GEOMETRY_TYPE_TEXTURED_MESH>::value;
95   }
96   return index;
97 }
98
99 } // unnamed namespace
100
101
102
103
104 Shader::Shader( Dali::ShaderEffect::GeometryHints& hints )
105 : mGeometryHints( hints ),
106   mGridDensity( Dali::ShaderEffect::DEFAULT_GRID_DENSITY ),
107   mTexture( NULL ),
108   mRenderTextureId( 0 ),
109   mUpdateTextureId( 0 ),
110   mRenderQueue(NULL),
111   mPostProcessDispatcher(NULL),
112   mTextureCache(NULL)
113 {
114   // Create enough size for all default types and sub-types
115   mPrograms.resize(Log<GEOMETRY_TYPE_LAST>::value);
116   for( unsigned int i = 0; i < Log<GEOMETRY_TYPE_LAST>::value; ++i)
117   {
118     mPrograms[ i ].Resize(SHADER_SUBTYPE_LAST);
119   }
120 }
121
122 Shader::~Shader()
123 {
124 }
125
126 void Shader::Initialize( PostProcessResourceDispatcher& postProcessDispatcher, RenderQueue& renderQueue, TextureCache& textureCache )
127 {
128   mPostProcessDispatcher = &postProcessDispatcher;
129   mRenderQueue = &renderQueue;
130   mTextureCache = &textureCache;
131 }
132
133 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
134 // The following methods are called during UpdateManager::Update()
135 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
136
137 void Shader::ForwardTextureId( BufferIndex updateBufferIndex, ResourceId textureId )
138 {
139   mUpdateTextureId = textureId;
140
141   typedef MessageValue1< Shader, Integration::ResourceId > DerivedType;
142
143   // Reserve some memory inside the render queue
144   unsigned int* slot = mRenderQueue->ReserveMessageSlot( updateBufferIndex, sizeof( DerivedType ) );
145
146   // Construct message in the render queue memory; note that delete should not be called on the return value
147   new (slot) DerivedType( this, &Shader::SetTextureId, textureId );
148 }
149
150 Integration::ResourceId Shader::GetEffectTextureResourceId()
151 {
152   return mUpdateTextureId;
153 }
154
155 void Shader::ForwardUniformMeta( BufferIndex updateBufferIndex, UniformMeta* meta )
156 {
157   // Defer setting uniform metadata until the next Render
158   // (Maintains thread safety on std::vector)
159
160   typedef MessageValue1< Shader, UniformMeta* > DerivedType;
161
162   // Reserve some memory inside the render queue
163   unsigned int* slot = mRenderQueue->ReserveMessageSlot( updateBufferIndex, sizeof( DerivedType ) );
164
165   // Construct message in the render queue memory; note that delete should not be called on the return value
166   new (slot) DerivedType( this, &Shader::InstallUniformMetaInRender, meta );
167 }
168
169 void Shader::ForwardGridDensity( BufferIndex updateBufferIndex, float density )
170 {
171   typedef MessageValue1< Shader, float > DerivedType;
172
173   // Reserve some memory inside the render queue
174   unsigned int* slot = mRenderQueue->ReserveMessageSlot( updateBufferIndex, sizeof( DerivedType ) );
175
176   // Construct message in the render queue memory; note that delete should not be called on the return value
177   new (slot) DerivedType( this, &Shader::SetGridDensity, density );
178 }
179
180 void Shader::ForwardHints( BufferIndex updateBufferIndex, Dali::ShaderEffect::GeometryHints hint )
181 {
182   typedef MessageValue1< Shader, Dali::ShaderEffect::GeometryHints > DerivedType;
183
184   // Reserve some memory inside the render queue
185   unsigned int* slot = mRenderQueue->ReserveMessageSlot( updateBufferIndex, sizeof( DerivedType ) );
186
187   // Construct message in the render queue memory; note that delete should not be called on the return value
188   new (slot) DerivedType( this, &Shader::SetGeometryHints, hint );
189 }
190
191 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
192 // The following methods are called during RenderManager::Render()
193 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
194
195 void Shader::SetTextureId( Integration::ResourceId textureId )
196 {
197   if ( mRenderTextureId != textureId )
198   {
199     mRenderTextureId = textureId;
200     mTexture = NULL;
201   }
202 }
203
204 Integration::ResourceId Shader::GetTextureIdToRender()
205 {
206   return mRenderTextureId;
207 }
208
209 void Shader::SetGridDensity( float density )
210 {
211   mGridDensity = density;
212 }
213
214 float Shader::GetGridDensity()
215 {
216   return mGridDensity;
217 }
218
219 void Shader::InstallUniformMetaInRender( UniformMeta* meta )
220 {
221   mUniformMetadata.PushBack( meta );
222 }
223
224 void Shader::SetProgram( GeometryType geometryType,
225                          ShaderSubTypes subType,
226                          Integration::ResourceId resourceId,
227                          Integration::ShaderDataPtr shaderData,
228                          Context* context,
229                          bool modifiesGeometry )
230 {
231   DALI_LOG_TRACE_METHOD_FMT(Debug::Filter::gShader, "%d %d\n", (int)geometryType, resourceId);
232
233   bool precompiledBinary = shaderData->HasBinary();
234
235   Program* program = Program::New( resourceId, shaderData, *context, modifiesGeometry );
236
237   ShaderSubTypes theSubType = subType;
238   if( subType == SHADER_SUBTYPE_ALL )
239   {
240     theSubType = SHADER_DEFAULT;
241   }
242
243   const unsigned int geometryIndex = GetGeometryTypeIndex( geometryType );
244   if(geometryType != GEOMETRY_TYPE_TEXT && subType == SHADER_SUBTYPE_ALL)
245   {
246     mPrograms[geometryIndex].Resize(1);
247     mPrograms[geometryIndex][theSubType] = program;
248     mPrograms[geometryIndex].mUseDefaultForAllSubtypes = true;
249   }
250   else
251   {
252     mPrograms[geometryIndex][theSubType] = program;
253     mPrograms[geometryIndex].mUseDefaultForAllSubtypes = false;
254   }
255
256   if( !precompiledBinary )
257   {
258     // The binary will have been compiled/linked during Program::New(), so save it
259     if( shaderData->HasBinary() )
260     {
261       DALI_ASSERT_DEBUG( mPostProcessDispatcher != NULL );
262       ResourcePostProcessRequest request( resourceId, ResourcePostProcessRequest::SAVE );
263       mPostProcessDispatcher->DispatchPostProcessRequest( request );
264     }
265   }
266 }
267
268 bool Shader::AreSubtypesRequired(GeometryType geometryType)
269 {
270   DALI_ASSERT_DEBUG(geometryType < GEOMETRY_TYPE_LAST);
271   unsigned int programType = GetGeometryTypeIndex( geometryType );
272
273   return ! mPrograms[ programType ].mUseDefaultForAllSubtypes;
274 }
275
276 Program* Shader::GetProgram( Context& context,
277                              GeometryType type,
278                              ShaderSubTypes subType,
279                              unsigned int& programIndex )
280 {
281   DALI_ASSERT_DEBUG(type < GEOMETRY_TYPE_LAST);
282   DALI_DEBUG_OSTREAM(debugStream);
283
284   programIndex = GetGeometryTypeIndex( type );
285
286   DALI_ASSERT_DEBUG((unsigned int)subType < mPrograms[ programIndex ].Count());
287
288   return mPrograms[ programIndex ][ subType ];
289 }
290
291
292 void Shader::SetUniforms( Context& context,
293                           Program& program,
294                           BufferIndex bufferIndex,
295                           unsigned int programIndex,
296                           ShaderSubTypes subType )
297 {
298   DALI_ASSERT_DEBUG( programIndex < Log<GEOMETRY_TYPE_LAST>::value );
299   DALI_DEBUG_OSTREAM(debugStream);
300
301   if( mRenderTextureId && ( mTexture == NULL ) )
302   {
303     mTexture = mTextureCache->GetTexture( mRenderTextureId );
304
305     DALI_ASSERT_DEBUG( mTexture != NULL );
306   }
307
308   GLint loc = Program::UNIFORM_UNKNOWN;
309
310   if( mTexture )
311   {
312     // got effect texture, bind it to texture unit 1
313     mTextureCache->BindTexture( mTexture, mRenderTextureId, GL_TEXTURE_2D, TextureUnitAsGLenum( TEXTURE_UNIT_SHADER ) );
314
315     // Just apply the default sampling options for now
316     mTexture->ApplySampler( ImageSampler::PackBitfield( FilterMode::DEFAULT, FilterMode::DEFAULT ) );
317
318     // get effect sampler uniform
319     const GLint loc = program.GetUniformLocation( Program::UNIFORM_EFFECT_SAMPLER );
320     if( Program::UNIFORM_UNKNOWN != loc )
321     {
322       DALI_PRINT_UNIFORM( debugStream, bufferIndex, "sEffect", TEXTURE_UNIT_SHADER );
323       // set the uniform
324       program.SetUniform1i( loc, TEXTURE_UNIT_SHADER );
325     }
326   }
327
328   // We should have one UniformMeta per uniform property
329   for ( unsigned int i = 0u; i < mUniformMetadata.Count(); ++i )
330   {
331     UniformMeta& metadata = *mUniformMetadata[i];
332     const PropertyBase& property = metadata.property;
333
334     // send the updated uniform to the program
335     if ( metadata.name.length() > 0 )
336     {
337       // 0 means program has not got a cache index for this uniform
338       if( 0 == metadata.cacheIndeces[ programIndex ][ subType ] )
339       {
340         // register cacheindex for this program
341         metadata.cacheIndeces[ programIndex ][ subType ] = program.RegisterUniform( metadata.name );
342       }
343       loc = program.GetUniformLocation( metadata.cacheIndeces[ programIndex ][ subType ] );
344
345       // if we find uniform with location
346       if ( Program::UNIFORM_UNKNOWN != loc )
347       {
348         DALI_PRINT_CUSTOM_UNIFORM( debugStream, bufferIndex, metadata.name, property );
349
350         // switch based on property type to use correct GL uniform setter
351         switch ( property.GetType() )
352         {
353           case Property::FLOAT :
354           {
355             program.SetUniform1f( loc, property.GetFloat( bufferIndex ) );
356             break;
357           }
358           case Property::INTEGER :
359           {
360             program.SetUniform1i( loc, property.GetInteger( bufferIndex ) );
361             break;
362           }
363           case Property::VECTOR2 :
364           {
365             Vector2 value( property.GetVector2( bufferIndex ) );
366
367             switch ( metadata.coordinateType )
368             {
369               case Dali::ShaderEffect::COORDINATE_TYPE_VIEWPORT_POSITION :
370               {
371                 /**
372                  * Convert coordinates from viewport to GL view space
373                  *
374                  * Viewport coordinate
375                  * (0,0)
376                  *      +-----+
377                  *      |     |
378                  *      |     |
379                  *      +-----+
380                  *             (width,height)
381                  *
382                  * GL view space coordinates
383                  * (width/2,-height/2)
384                  *      +-----+
385                  *      |     |
386                  *      |     |
387                  *      +-----+
388                  *             (-width/2,height/2)
389                  **/
390                 const Rect< int >& viewport = context.GetViewport();
391                 value.x = viewport.width * 0.5f - value.x;
392                 value.y = value.y - viewport.height * 0.5f;
393
394                 break;
395               }
396               case Dali::ShaderEffect::COORDINATE_TYPE_VIEWPORT_DIRECTION :
397               {
398                 // Check diagram in COORDINATE_TYPE_VIEWPORT_POSITION
399                 value.x *= -1.0f;
400                 break;
401               }
402               case Dali::ShaderEffect::COORDINATE_TYPE_TEXTURE_POSITION :
403               {
404                 if ( mTexture )
405                 {
406                   UvRect textureArea;
407                   mTexture->GetTextureCoordinates( textureArea );
408
409                   //TODO: this only works for textures that are mapped as a axis aligned rectangle
410                   float width = textureArea.u2 - textureArea.u0;
411                   float height = textureArea.v2 - textureArea.v0;
412                   value.x = textureArea.u0 + value.x * width;
413                   value.y = textureArea.v0 + value.y * height;
414                 }
415                 break;
416               }
417               case Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT :
418               {
419                 // nothing to do in this case
420                 break;
421               }
422               // no default so compiler will warn if a case is not handled
423             }
424
425             program.SetUniform2f( loc, value.x, value.y );
426             break;
427           }
428
429           case Property::VECTOR3 :
430           {
431             Vector3 value( property.GetVector3( bufferIndex ) );
432             if( Dali::ShaderEffect::COORDINATE_TYPE_VIEWPORT_DIRECTION == metadata.coordinateType)
433             {
434               value.y *= -1.0f;
435             }
436
437             program.SetUniform3f( loc, value.x, value.y, value.z );
438             break;
439           }
440
441           case Property::VECTOR4 :
442           {
443             Vector4 value( property.GetVector4( bufferIndex ) );
444             if( Dali::ShaderEffect::COORDINATE_TYPE_VIEWPORT_DIRECTION == metadata.coordinateType)
445             {
446               value.y *= -1.0f;
447             }
448
449             program.SetUniform4f( loc, value.x, value.y, value.z, value.w );
450             break;
451           }
452
453           case Property::MATRIX:
454           {
455             const Matrix& value = property.GetMatrix(bufferIndex);
456             program.SetUniformMatrix4fv(loc, 1, value.AsFloat() );
457             break;
458           }
459
460           case Property::MATRIX3:
461           {
462             const Matrix3& value = property.GetMatrix3(bufferIndex);
463             program.SetUniformMatrix3fv(loc, 1, value.AsFloat() );
464             break;
465           }
466
467           default :
468           {
469             // Only float and Vector properties are passed as uniforms; other types are ignored.
470             break;
471           }
472         }
473       }
474     }
475   }
476
477   DALI_PRINT_SHADER_UNIFORMS(debugStream);
478 }
479
480 } // namespace SceneGraph
481
482 } // namespace Internal
483
484 } // namespace Dali