Regenerating uniform maps fix
[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
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                          uint32_t 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                     uint32_t 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   mShaderChanged( false )
150 {
151   if( blendingBitmask != 0u )
152   {
153     mBlendingOptions.SetBitmask( blendingBitmask );
154   }
155
156   mBlendingOptions.SetBlendColor( blendColor );
157 }
158
159 void Renderer::Initialize( Context& context )
160 {
161   mContext = &context;
162 }
163
164 Renderer::~Renderer()
165 {
166 }
167
168 void Renderer::SetGeometry( Render::Geometry* geometry )
169 {
170   mGeometry = geometry;
171   mUpdateAttributesLocation = true;
172 }
173
174 void Renderer::SetBlending( Context& context, bool blend )
175 {
176   context.SetBlend( blend );
177   if( blend )
178   {
179     // Blend color is optional and rarely used
180     const Vector4* blendColor = mBlendingOptions.GetBlendColor();
181     if( blendColor )
182     {
183       context.SetCustomBlendColor( *blendColor );
184     }
185     else
186     {
187       context.SetDefaultBlendColor();
188     }
189
190     // Set blend source & destination factors
191     context.BlendFuncSeparate( mBlendingOptions.GetBlendSrcFactorRgb(),
192                                mBlendingOptions.GetBlendDestFactorRgb(),
193                                mBlendingOptions.GetBlendSrcFactorAlpha(),
194                                mBlendingOptions.GetBlendDestFactorAlpha() );
195
196     // Set blend equations
197     context.BlendEquationSeparate( mBlendingOptions.GetBlendEquationRgb(),
198                                    mBlendingOptions.GetBlendEquationAlpha() );
199   }
200 }
201
202 void Renderer::GlContextDestroyed()
203 {
204   mGeometry->GlContextDestroyed();
205 }
206
207 void Renderer::GlCleanup()
208 {
209 }
210
211 void Renderer::SetUniforms( BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program )
212 {
213   // Check if the map has changed
214   DALI_ASSERT_DEBUG( mRenderDataProvider && "No Uniform map data provider available" );
215
216   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMap();
217
218   if( uniformMapDataProvider.GetUniformMapChanged( bufferIndex ) ||
219       node.GetUniformMapChanged(bufferIndex) ||
220       mUniformIndexMap.Count() == 0 ||
221       mShaderChanged )
222   {
223     // Reset shader pointer
224     mShaderChanged = false;
225
226     const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetUniformMap( bufferIndex );
227     const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap( bufferIndex );
228
229     uint32_t maxMaps = static_cast<uint32_t>( uniformMap.Count() + uniformMapNode.Count() ); // 4,294,967,295 maps should be enough
230     mUniformIndexMap.Clear(); // Clear contents, but keep memory if we don't change size
231     mUniformIndexMap.Resize( maxMaps );
232
233     uint32_t mapIndex = 0;
234     for(; mapIndex < uniformMap.Count() ; ++mapIndex )
235     {
236       mUniformIndexMap[mapIndex].propertyValue = uniformMap[mapIndex]->propertyPtr;
237       mUniformIndexMap[mapIndex].uniformIndex = program.RegisterUniform( uniformMap[mapIndex]->uniformName );
238     }
239
240     for( uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count() ; ++nodeMapIndex )
241     {
242       uint32_t uniformIndex = program.RegisterUniform( uniformMapNode[nodeMapIndex]->uniformName );
243       bool found(false);
244       for( uint32_t i = 0; i<uniformMap.Count(); ++i )
245       {
246         if( mUniformIndexMap[i].uniformIndex == uniformIndex )
247         {
248           mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
249           found = true;
250           break;
251         }
252       }
253
254       if( !found )
255       {
256         mUniformIndexMap[mapIndex].propertyValue = uniformMapNode[nodeMapIndex]->propertyPtr;
257         mUniformIndexMap[mapIndex].uniformIndex = uniformIndex;
258         ++mapIndex;
259       }
260     }
261
262     mUniformIndexMap.Resize( mapIndex );
263   }
264
265   // Set uniforms in local map
266   for( UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
267          end = mUniformIndexMap.End() ;
268        iter != end ;
269        ++iter )
270   {
271     SetUniformFromProperty( bufferIndex, program, *iter );
272   }
273
274   GLint sizeLoc = program.GetUniformLocation( Program::UNIFORM_SIZE );
275   if( -1 != sizeLoc )
276   {
277     program.SetSizeUniform3f( sizeLoc, size.x, size.y, size.z );
278   }
279 }
280
281 void Renderer::SetUniformFromProperty( BufferIndex bufferIndex, Program& program, UniformIndexMap& map )
282 {
283   GLint location = program.GetUniformLocation(map.uniformIndex);
284   if( Program::UNIFORM_UNKNOWN != location )
285   {
286     // switch based on property type to use correct GL uniform setter
287     switch ( map.propertyValue->GetType() )
288     {
289       case Property::INTEGER:
290       {
291         program.SetUniform1i( location, map.propertyValue->GetInteger( bufferIndex ) );
292         break;
293       }
294       case Property::FLOAT:
295       {
296         program.SetUniform1f( location, map.propertyValue->GetFloat( bufferIndex ) );
297         break;
298       }
299       case Property::VECTOR2:
300       {
301         Vector2 value( map.propertyValue->GetVector2( bufferIndex ) );
302         program.SetUniform2f( location, value.x, value.y );
303         break;
304       }
305
306       case Property::VECTOR3:
307       {
308         Vector3 value( map.propertyValue->GetVector3( bufferIndex ) );
309         program.SetUniform3f( location, value.x, value.y, value.z );
310         break;
311       }
312
313       case Property::VECTOR4:
314       {
315         Vector4 value( map.propertyValue->GetVector4( bufferIndex ) );
316         program.SetUniform4f( location, value.x, value.y, value.z, value.w );
317         break;
318       }
319
320       case Property::ROTATION:
321       {
322         Quaternion value( map.propertyValue->GetQuaternion( bufferIndex ) );
323         program.SetUniform4f( location, value.mVector.x, value.mVector.y, value.mVector.z, value.mVector.w );
324         break;
325       }
326
327       case Property::MATRIX:
328       {
329         const Matrix& value = map.propertyValue->GetMatrix(bufferIndex);
330         program.SetUniformMatrix4fv(location, 1, value.AsFloat() );
331         break;
332       }
333
334       case Property::MATRIX3:
335       {
336         const Matrix3& value = map.propertyValue->GetMatrix3(bufferIndex);
337         program.SetUniformMatrix3fv(location, 1, value.AsFloat() );
338         break;
339       }
340
341       default:
342       {
343         // Other property types are ignored
344         break;
345       }
346     }
347   }
348 }
349
350 bool Renderer::BindTextures( Context& context, Program& program, Vector<GLuint>& boundTextures )
351 {
352   uint32_t textureUnit = 0;
353   bool result = true;
354
355   GLint uniformLocation(-1);
356   std::vector<Render::Sampler*>& samplers( mRenderDataProvider->GetSamplers() );
357   std::vector<Render::Texture*>& textures( mRenderDataProvider->GetTextures() );
358   for( uint32_t i = 0; i < static_cast<uint32_t>( textures.size() ) && result; ++i ) // not expecting more than uint32_t of textures
359   {
360     if( textures[i] )
361     {
362       result = textures[i]->Bind(context, textureUnit, samplers[i] );
363       boundTextures.PushBack( textures[i]->GetId() );
364       if( result && program.GetSamplerUniformLocation( i, uniformLocation ) )
365       {
366         program.SetUniform1i( uniformLocation, textureUnit );
367         ++textureUnit;
368       }
369     }
370   }
371
372   return result;
373 }
374
375 void Renderer::SetFaceCullingMode( FaceCullingMode::Type mode )
376 {
377   mFaceCullingMode =  mode;
378 }
379
380 void Renderer::SetBlendingBitMask( uint32_t bitmask )
381 {
382   mBlendingOptions.SetBitmask( bitmask );
383 }
384
385 void Renderer::SetBlendColor( const Vector4& color )
386 {
387   mBlendingOptions.SetBlendColor( color );
388 }
389
390 void Renderer::SetIndexedDrawFirstElement( uint32_t firstElement )
391 {
392   mIndexedDrawFirstElement = firstElement;
393 }
394
395 void Renderer::SetIndexedDrawElementsCount( uint32_t elementsCount )
396 {
397   mIndexedDrawElementsCount = elementsCount;
398 }
399
400 void Renderer::EnablePreMultipliedAlpha( bool enable )
401 {
402   mPremultipledAlphaEnabled = enable;
403 }
404
405 void Renderer::SetDepthWriteMode( DepthWriteMode::Type depthWriteMode )
406 {
407   mDepthWriteMode = depthWriteMode;
408 }
409
410 void Renderer::SetDepthTestMode( DepthTestMode::Type depthTestMode )
411 {
412   mDepthTestMode = depthTestMode;
413 }
414
415 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
416 {
417   return mDepthWriteMode;
418 }
419
420 DepthTestMode::Type Renderer::GetDepthTestMode() const
421 {
422   return mDepthTestMode;
423 }
424
425 void Renderer::SetDepthFunction( DepthFunction::Type depthFunction )
426 {
427   mDepthFunction = depthFunction;
428 }
429
430 DepthFunction::Type Renderer::GetDepthFunction() const
431 {
432   return mDepthFunction;
433 }
434
435 void Renderer::SetRenderMode( RenderMode::Type renderMode )
436 {
437   mStencilParameters.renderMode = renderMode;
438 }
439
440 RenderMode::Type Renderer::GetRenderMode() const
441 {
442   return mStencilParameters.renderMode;
443 }
444
445 void Renderer::SetStencilFunction( StencilFunction::Type stencilFunction )
446 {
447   mStencilParameters.stencilFunction = stencilFunction;
448 }
449
450 StencilFunction::Type Renderer::GetStencilFunction() const
451 {
452   return mStencilParameters.stencilFunction;
453 }
454
455 void Renderer::SetStencilFunctionMask( int stencilFunctionMask )
456 {
457   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
458 }
459
460 int Renderer::GetStencilFunctionMask() const
461 {
462   return mStencilParameters.stencilFunctionMask;
463 }
464
465 void Renderer::SetStencilFunctionReference( int stencilFunctionReference )
466 {
467   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
468 }
469
470 int Renderer::GetStencilFunctionReference() const
471 {
472   return mStencilParameters.stencilFunctionReference;
473 }
474
475 void Renderer::SetStencilMask( int stencilMask )
476 {
477   mStencilParameters.stencilMask = stencilMask;
478 }
479
480 int Renderer::GetStencilMask() const
481 {
482   return mStencilParameters.stencilMask;
483 }
484
485 void Renderer::SetStencilOperationOnFail( StencilOperation::Type stencilOperationOnFail )
486 {
487   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
488 }
489
490 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
491 {
492   return mStencilParameters.stencilOperationOnFail;
493 }
494
495 void Renderer::SetStencilOperationOnZFail( StencilOperation::Type stencilOperationOnZFail )
496 {
497   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
498 }
499
500 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
501 {
502   return mStencilParameters.stencilOperationOnZFail;
503 }
504
505 void Renderer::SetStencilOperationOnZPass( StencilOperation::Type stencilOperationOnZPass )
506 {
507   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
508 }
509
510 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
511 {
512   return mStencilParameters.stencilOperationOnZPass;
513 }
514
515 void Renderer::Upload( Context& context )
516 {
517   mGeometry->Upload( context );
518 }
519
520 void Renderer::Render( Context& context,
521                        BufferIndex bufferIndex,
522                        const SceneGraph::NodeDataProvider& node,
523                        const Matrix& modelMatrix,
524                        const Matrix& modelViewMatrix,
525                        const Matrix& viewMatrix,
526                        const Matrix& projectionMatrix,
527                        const Vector3& size,
528                        bool blend,
529                        Vector<GLuint>& boundTextures )
530 {
531   // Get the program to use:
532   Program* program = mRenderDataProvider->GetShader().GetProgram();
533   if( !program )
534   {
535     DALI_LOG_ERROR( "Failed to get program for shader at address %p.\n", reinterpret_cast< void* >( &mRenderDataProvider->GetShader() ) );
536     return;
537   }
538
539   //Set cull face  mode
540   context.CullFace( mFaceCullingMode );
541
542   //Set blending mode
543   SetBlending( context, blend );
544
545   // Take the program into use so we can send uniforms to it
546   program->Use();
547
548   if( DALI_LIKELY( BindTextures( context, *program, boundTextures ) ) )
549   {
550     // Only set up and draw if we have textures and they are all valid
551
552     // set projection and view matrix if program has not yet received them yet this frame
553     SetMatrices( *program, modelMatrix, viewMatrix, projectionMatrix, modelViewMatrix );
554
555     // set color uniform
556     GLint loc = program->GetUniformLocation( Program::UNIFORM_COLOR );
557     if( Program::UNIFORM_UNKNOWN != loc )
558     {
559       const Vector4& color = node.GetRenderColor( bufferIndex );
560       if( mPremultipledAlphaEnabled )
561       {
562         float alpha = color.a * mRenderDataProvider->GetOpacity( bufferIndex );
563         program->SetUniform4f( loc, color.r * alpha, color.g * alpha, color.b * alpha, alpha );
564       }
565       else
566       {
567         program->SetUniform4f( loc, color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity( bufferIndex ) );
568       }
569     }
570
571     SetUniforms( bufferIndex, node, size, *program );
572
573     if( mUpdateAttributesLocation || mGeometry->AttributesChanged() )
574     {
575       mGeometry->GetAttributeLocationFromProgram( mAttributesLocation, *program, bufferIndex );
576       mUpdateAttributesLocation = false;
577     }
578
579     mGeometry->Draw( context,
580                      bufferIndex,
581                      mAttributesLocation,
582                      mIndexedDrawFirstElement,
583                      mIndexedDrawElementsCount );
584   }
585 }
586
587 void Renderer::SetSortAttributes( BufferIndex bufferIndex,
588                                   SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes ) const
589 {
590   sortAttributes.shader = &( mRenderDataProvider->GetShader() );
591   sortAttributes.geometry = mGeometry;
592 }
593
594 void Renderer::SetShaderChanged( bool value )
595 {
596   mShaderChanged = value;
597 }
598
599 } // namespace SceneGraph
600
601 } // namespace Internal
602
603 } // namespace Dali