Merge changes Ifb1d366c,I250378ee into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.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/renderers/render-renderer.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/common/image-sampler.h>
23 #include <dali/internal/render/gl-resources/context.h>
24 #include <dali/internal/render/renderers/render-sampler.h>
25 #include <dali/internal/render/shaders/scene-graph-shader.h>
26 #include <dali/internal/render/shaders/program.h>
27 #include <dali/internal/render/data-providers/node-data-provider.h>
28
29 namespace Dali
30 {
31
32 namespace Internal
33 {
34
35 namespace
36 {
37
38 static Matrix gModelViewProjectionMatrix( false ); ///< a shared matrix to calculate the MVP matrix, dont want to store it in object to reduce storage overhead
39 static Matrix3 gNormalMatrix; ///< a shared matrix to calculate normal matrix, dont want to store it in object to reduce storage overhead
40
41 /**
42  * Helper to set view and projection matrices once per program
43  * @param program to set the matrices to
44  * @param modelMatrix to set
45  * @param viewMatrix to set
46  * @param projectionMatrix to set
47  * @param modelViewMatrix to set
48  * @param modelViewProjectionMatrix to set
49  */
50 inline void SetMatrices( Program& program,
51                          const Matrix& modelMatrix,
52                          const Matrix& viewMatrix,
53                          const Matrix& projectionMatrix,
54                          const Matrix& modelViewMatrix )
55 {
56   GLint loc = program.GetUniformLocation( Program::UNIFORM_MODEL_MATRIX );
57   if( Program::UNIFORM_UNKNOWN != loc )
58   {
59     program.SetUniformMatrix4fv( loc, 1, modelMatrix.AsFloat() );
60   }
61   loc = program.GetUniformLocation( Program::UNIFORM_VIEW_MATRIX );
62   if( Program::UNIFORM_UNKNOWN != loc )
63   {
64     if( program.GetViewMatrix() != &viewMatrix )
65     {
66       program.SetViewMatrix( &viewMatrix );
67       program.SetUniformMatrix4fv( loc, 1, viewMatrix.AsFloat() );
68     }
69   }
70   // set projection matrix if program has not yet received it this frame or if it is dirty
71   loc = program.GetUniformLocation( Program::UNIFORM_PROJECTION_MATRIX );
72   if( Program::UNIFORM_UNKNOWN != loc )
73   {
74     if( program.GetProjectionMatrix() != &projectionMatrix )
75     {
76       program.SetProjectionMatrix( &projectionMatrix );
77       program.SetUniformMatrix4fv( loc, 1, projectionMatrix.AsFloat() );
78     }
79   }
80   loc = program.GetUniformLocation(Program::UNIFORM_MODELVIEW_MATRIX);
81   if( Program::UNIFORM_UNKNOWN != loc )
82   {
83     program.SetUniformMatrix4fv( loc, 1, modelViewMatrix.AsFloat() );
84   }
85
86   loc = program.GetUniformLocation( Program::UNIFORM_MVP_MATRIX );
87   if( Program::UNIFORM_UNKNOWN != loc )
88   {
89     Matrix::Multiply( gModelViewProjectionMatrix, modelViewMatrix, projectionMatrix );
90     program.SetUniformMatrix4fv( loc, 1, gModelViewProjectionMatrix.AsFloat() );
91   }
92
93   loc = program.GetUniformLocation( Program::UNIFORM_NORMAL_MATRIX );
94   if( Program::UNIFORM_UNKNOWN != loc )
95   {
96     gNormalMatrix = modelViewMatrix;
97     gNormalMatrix.Invert();
98     gNormalMatrix.Transpose();
99     program.SetUniformMatrix3fv( loc, 1, gNormalMatrix.AsFloat() );
100   }
101 }
102
103 }
104
105 namespace Render
106 {
107
108 Renderer* Renderer::New( SceneGraph::RenderDataProvider* dataProvider,
109                          Render::Geometry* geometry,
110                          unsigned int blendingBitmask,
111                          const Vector4& blendColor,
112                          FaceCullingMode::Type faceCullingMode,
113                          bool preMultipliedAlphaEnabled,
114                          DepthWriteMode::Type depthWriteMode,
115                          DepthTestMode::Type depthTestMode,
116                          DepthFunction::Type depthFunction,
117                          StencilParameters& stencilParameters )
118 {
119   return new Renderer( dataProvider, geometry, blendingBitmask, blendColor,
120                        faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode,
121                        depthFunction, stencilParameters );
122 }
123
124 Renderer::Renderer( SceneGraph::RenderDataProvider* dataProvider,
125                     Render::Geometry* geometry,
126                     unsigned int blendingBitmask,
127                     const Vector4& blendColor,
128                     FaceCullingMode::Type faceCullingMode,
129                     bool preMultipliedAlphaEnabled,
130                     DepthWriteMode::Type depthWriteMode,
131                     DepthTestMode::Type depthTestMode,
132                     DepthFunction::Type depthFunction,
133                     StencilParameters& stencilParameters )
134 : mRenderDataProvider( dataProvider ),
135   mContext( NULL),
136   mGeometry( geometry ),
137   mUniformIndexMap(),
138   mAttributesLocation(),
139   mStencilParameters( stencilParameters ),
140   mBlendingOptions(),
141   mIndexedDrawFirstElement( 0 ),
142   mIndexedDrawElementsCount( 0 ),
143   mDepthFunction( depthFunction ),
144   mFaceCullingMode( faceCullingMode ),
145   mDepthWriteMode( depthWriteMode ),
146   mDepthTestMode( depthTestMode ),
147   mUpdateAttributesLocation( true ),
148   mPremultipledAlphaEnabled( preMultipliedAlphaEnabled )
149 {
150   if( blendingBitmask != 0u )
151   {
152     mBlendingOptions.SetBitmask( blendingBitmask );
153   }
154
155   mBlendingOptions.SetBlendColor( blendColor );
156 }
157
158 void Renderer::Initialize( Context& context )
159 {
160   mContext = &context;
161 }
162
163 Renderer::~Renderer()
164 {
165 }
166
167 void Renderer::SetRenderDataProvider( OwnerPointer<SceneGraph::RenderDataProvider>& dataProvider )
168 {
169   mRenderDataProvider = dataProvider;
170   mUpdateAttributesLocation = true;
171
172   // Check that the number of textures match the number of samplers in the shader
173   size_t textureCount =  mRenderDataProvider->GetTextures().size();
174   Program* program = mRenderDataProvider->GetShader().GetProgram();
175   if( program && program->GetActiveSamplerCount() != textureCount )
176   {
177     DALI_LOG_WARNING("The number of active samplers in the shader(%lu) does not match the number of textures in the TextureSet(%lu)\n",
178                    program->GetActiveSamplerCount(),
179                    textureCount );
180   }
181 }
182
183 void Renderer::SetGeometry( Render::Geometry* geometry )
184 {
185   mGeometry = geometry;
186   mUpdateAttributesLocation = true;
187 }
188
189 void Renderer::SetBlending( Context& context, bool blend )
190 {
191   context.SetBlend( blend );
192   if( blend )
193   {
194     // Blend color is optional and rarely used
195     const Vector4* blendColor = mBlendingOptions.GetBlendColor();
196     if( blendColor )
197     {
198       context.SetCustomBlendColor( *blendColor );
199     }
200     else
201     {
202       context.SetDefaultBlendColor();
203     }
204
205     // Set blend source & destination factors
206     context.BlendFuncSeparate( mBlendingOptions.GetBlendSrcFactorRgb(),
207                                mBlendingOptions.GetBlendDestFactorRgb(),
208                                mBlendingOptions.GetBlendSrcFactorAlpha(),
209                                mBlendingOptions.GetBlendDestFactorAlpha() );
210
211     // Set blend equations
212     context.BlendEquationSeparate( mBlendingOptions.GetBlendEquationRgb(),
213                                    mBlendingOptions.GetBlendEquationAlpha() );
214   }
215 }
216
217 void Renderer::GlContextDestroyed()
218 {
219   mGeometry->GlContextDestroyed();
220 }
221
222 void Renderer::GlCleanup()
223 {
224 }
225
226 void Renderer::SetUniforms( BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program )
227 {
228   // Check if the map has changed
229   DALI_ASSERT_DEBUG( mRenderDataProvider && "No Uniform map data provider available" );
230
231   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
232
233   if( uniformMapDataProvider.GetUniformMapChanged( bufferIndex ) ||
234       node.GetUniformMapChanged(bufferIndex) ||
235       mUniformIndexMap.Count() == 0)
236   {
237     const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap( bufferIndex );
238     const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap( bufferIndex );
239
240     unsigned int maxMaps = uniformMap.Count() + uniformMapNode.Count();
241     mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
242     mUniformIndexMap.Resize( maxMaps );
243
244     unsigned int mapIndex(0);
245     for(; mapIndex < uniformMap.Count() ; ++mapIndex )
246     {
247       mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex]->propertyPtr;
248       mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform( uniformMap[mapIndex]->uniformName );
249     }
250
251     for( unsigned int nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count() ; ++nodeMapIndex )
252     {
253       unsigned int uniformIndex = program.RegisterUniform( uniformMapNode[nodeMapIndex]->uniformName );
254       bool found(false);
255       for( unsigned int i(0); i<uniformMap.Count(); ++i )
256       {
257         if( mUniformIndexMap[i].uniformIndex == uniformIndex )
258         {
259           mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
260           found = true;
261           break;
262         }
263       }
264
265       if( !found )
266       {
267         mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
268         mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
269         ++mapIndex;
270       }
271     }
272
273     mUniformIndexMap.Resize( mapIndex );
274   }
275
276   // Set uniforms in local map
277   for( UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
278          end = mUniformIndexMap.End() ;
279        iter != end ;
280        ++iter )
281   {
282     SetUniformFromProperty( bufferIndex, program, *iter );
283   }
284
285   GLint sizeLoc = program.GetUniformLocation( Program::UNIFORM_SIZE );
286   if( -1 != sizeLoc )
287   {
288     program.SetSizeUniform3f( sizeLoc, size.x, size.y, size.z );
289   }
290 }
291
292 void Renderer::SetUniformFromProperty( BufferIndex bufferIndex, Program& program, UniformIndexMap& map )
293 {
294   GLint location = program.GetUniformLocation(map.uniformIndex);
295   if( Program::UNIFORM_UNKNOWN != location )
296   {
297     // switch based on property type to use correct GL uniform setter
298     switch ( map.propertyValue->GetType() )
299     {
300       case Property::INTEGER:
301       {
302         program.SetUniform1i( location, map.propertyValue->GetInteger( bufferIndex ) );
303         break;
304       }
305       case Property::FLOAT:
306       {
307         program.SetUniform1f( location, map.propertyValue->GetFloat( bufferIndex ) );
308         break;
309       }
310       case Property::VECTOR2:
311       {
312         Vector2 value( map.propertyValue->GetVector2( bufferIndex ) );
313         program.SetUniform2f( location, value.x, value.y );
314         break;
315       }
316
317       case Property::VECTOR3:
318       {
319         Vector3 value( map.propertyValue->GetVector3( bufferIndex ) );
320         program.SetUniform3f( location, value.x, value.y, value.z );
321         break;
322       }
323
324       case Property::VECTOR4:
325       {
326         Vector4 value( map.propertyValue->GetVector4( bufferIndex ) );
327         program.SetUniform4f( location, value.x, value.y, value.z, value.w );
328         break;
329       }
330
331       case Property::ROTATION:
332       {
333         Quaternion value( map.propertyValue->GetQuaternion( bufferIndex ) );
334         program.SetUniform4f( location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w );
335         break;
336       }
337
338       case Property::MATRIX:
339       {
340         const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
341         program.SetUniformMatrix4fv(location, 1, value.AsFloat() );
342         break;
343       }
344
345       case Property::MATRIX3:
346       {
347         const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
348         program.SetUniformMatrix3fv(location, 1, value.AsFloat() );
349         break;
350       }
351
352       default:
353       {
354         // Other property types are ignored
355         break;
356       }
357     }
358   }
359 }
360
361 bool Renderer::BindTextures( Context& context, Program& program )
362 {
363   unsigned int textureUnit = 0;
364   bool result = true;
365
366   GLint uniformLocation(-1);
367   std::vector<Render::Sampler*>& samplers( mRenderDataProvider->GetSamplers() );
368   std::vector<Render::Texture*>& textures( mRenderDataProvider->GetTextures() );
369   for( size_t i(0); i<textures.size() && result; ++i )
370   {
371     if( textures[i] )
372     {
373       result = textures[i]->Bind(context, textureUnit, samplers[i] );
374       if( result && program.GetSamplerUniformLocation( i, uniformLocation ) )
375       {
376         program.SetUniform1i( uniformLocation, textureUnit );
377         ++textureUnit;
378       }
379     }
380   }
381
382   return result;
383 }
384
385 void Renderer::SetFaceCullingMode( FaceCullingMode::Type mode )
386 {
387   mFaceCullingMode =  mode;
388 }
389
390 void Renderer::SetBlendingBitMask( unsigned int bitmask )
391 {
392   mBlendingOptions.SetBitmask( bitmask );
393 }
394
395 void Renderer::SetBlendColor( const Vector4& color )
396 {
397   mBlendingOptions.SetBlendColor( color );
398 }
399
400 void Renderer::SetIndexedDrawFirstElement( size_t firstElement )
401 {
402   mIndexedDrawFirstElement = firstElement;
403 }
404
405 void Renderer::SetIndexedDrawElementsCount( size_t elementsCount )
406 {
407   mIndexedDrawElementsCount = elementsCount;
408 }
409
410 void Renderer::EnablePreMultipliedAlpha( bool enable )
411 {
412   mPremultipledAlphaEnabled = enable;
413 }
414
415 void Renderer::SetDepthWriteMode( DepthWriteMode::Type depthWriteMode )
416 {
417   mDepthWriteMode = depthWriteMode;
418 }
419
420 void Renderer::SetDepthTestMode( DepthTestMode::Type depthTestMode )
421 {
422   mDepthTestMode = depthTestMode;
423 }
424
425 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
426 {
427   return mDepthWriteMode;
428 }
429
430 DepthTestMode::Type Renderer::GetDepthTestMode() const
431 {
432   return mDepthTestMode;
433 }
434
435 void Renderer::SetDepthFunction( DepthFunction::Type depthFunction )
436 {
437   mDepthFunction = depthFunction;
438 }
439
440 DepthFunction::Type Renderer::GetDepthFunction() const
441 {
442   return mDepthFunction;
443 }
444
445 void Renderer::SetRenderMode( RenderMode::Type renderMode )
446 {
447   mStencilParameters.renderMode = renderMode;
448 }
449
450 RenderMode::Type Renderer::GetRenderMode() const
451 {
452   return mStencilParameters.renderMode;
453 }
454
455 void Renderer::SetStencilFunction( StencilFunction::Type stencilFunction )
456 {
457   mStencilParameters.stencilFunction = stencilFunction;
458 }
459
460 StencilFunction::Type Renderer::GetStencilFunction() const
461 {
462   return mStencilParameters.stencilFunction;
463 }
464
465 void Renderer::SetStencilFunctionMask( int stencilFunctionMask )
466 {
467   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
468 }
469
470 int Renderer::GetStencilFunctionMask() const
471 {
472   return mStencilParameters.stencilFunctionMask;
473 }
474
475 void Renderer::SetStencilFunctionReference( int stencilFunctionReference )
476 {
477   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
478 }
479
480 int Renderer::GetStencilFunctionReference() const
481 {
482   return mStencilParameters.stencilFunctionReference;
483 }
484
485 void Renderer::SetStencilMask( int stencilMask )
486 {
487   mStencilParameters.stencilMask = stencilMask;
488 }
489
490 int Renderer::GetStencilMask() const
491 {
492   return mStencilParameters.stencilMask;
493 }
494
495 void Renderer::SetStencilOperationOnFail( StencilOperation::Type stencilOperationOnFail )
496 {
497   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
498 }
499
500 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
501 {
502   return mStencilParameters.stencilOperationOnFail;
503 }
504
505 void Renderer::SetStencilOperationOnZFail( StencilOperation::Type stencilOperationOnZFail )
506 {
507   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
508 }
509
510 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
511 {
512   return mStencilParameters.stencilOperationOnZFail;
513 }
514
515 void Renderer::SetStencilOperationOnZPass( StencilOperation::Type stencilOperationOnZPass )
516 {
517   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
518 }
519
520 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
521 {
522   return mStencilParameters.stencilOperationOnZPass;
523 }
524
525 void Renderer::Render( Context& context,
526                        BufferIndex bufferIndex,
527                        const SceneGraph::NodeDataProvider& node,
528                        const Matrix& modelMatrix,
529                        const Matrix& modelViewMatrix,
530                        const Matrix& viewMatrix,
531                        const Matrix& projectionMatrix,
532                        const Vector3& size,
533                        bool blend )
534 {
535   // Get the program to use:
536   Program* program = mRenderDataProvider->GetShader().GetProgram();
537   if( !program )
538   {
539     DALI_LOG_ERROR( "Failed to get program for shader at address %p.\n", reinterpret_cast< void* >( &mRenderDataProvider->GetShader() ) );
540     return;
541   }
542
543   //Set cull face  mode
544   context.CullFace( mFaceCullingMode );
545
546   //Set blending mode
547   SetBlending( context, blend );
548
549   // Take the program into use so we can send uniforms to it
550   program->Use();
551
552   if( DALI_LIKELY( BindTextures( context, *program ) ) )
553   {
554     // Only set up and draw if we have textures and they are all valid
555
556     // set projection and view matrix if program has not yet received them yet this frame
557     SetMatrices( *program, modelMatrix, viewMatrix, projectionMatrix, modelViewMatrix );
558
559     // set color uniform
560     GLint loc = program->GetUniformLocation( Program::UNIFORM_COLOR );
561     if( Program::UNIFORM_UNKNOWN != loc )
562     {
563       const Vector4& color = node.GetRenderColor( bufferIndex );
564       if( mPremultipledAlphaEnabled )
565       {
566         program->SetUniform4f( loc, color.r*color.a, color.g*color.a, color.b*color.a, color.a );
567       }
568       else
569       {
570         program->SetUniform4f( loc, color.r, color.g, color.b, color.a );
571       }
572     }
573
574     SetUniforms( bufferIndex, node, size, *program );
575
576     if( mUpdateAttributesLocation || mGeometry->AttributesChanged() )
577     {
578       mGeometry->GetAttributeLocationFromProgram( mAttributesLocation, *program, bufferIndex );
579       mUpdateAttributesLocation = false;
580     }
581
582     mGeometry->UploadAndDraw( context,
583                               bufferIndex,
584                               mAttributesLocation,
585                               mIndexedDrawFirstElement,
586                               mIndexedDrawElementsCount );
587   }
588 }
589
590 void Renderer::SetSortAttributes( BufferIndex bufferIndex,
591                                   SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes ) const
592 {
593   sortAttributes.shader = &( mRenderDataProvider->GetShader() );
594   sortAttributes.geometry = mGeometry;
595 }
596
597 } // namespace SceneGraph
598
599 } // namespace Internal
600
601 } // namespace Dali