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