Merge "Remove element of Property::Map by the specified key." into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.cpp
1 /*
2  * Copyright (c) 2022 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/graphics-api/graphics-types.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/internal/common/image-sampler.h>
25 #include <dali/internal/render/common/render-instruction.h>
26 #include <dali/internal/render/data-providers/node-data-provider.h>
27 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
28 #include <dali/internal/render/renderers/pipeline-cache.h>
29 #include <dali/internal/render/renderers/render-sampler.h>
30 #include <dali/internal/render/renderers/render-texture.h>
31 #include <dali/internal/render/renderers/render-vertex-buffer.h>
32 #include <dali/internal/render/renderers/shader-cache.h>
33 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
34 #include <dali/internal/render/renderers/uniform-buffer-view.h>
35 #include <dali/internal/render/shaders/program.h>
36 #include <dali/internal/render/shaders/render-shader.h>
37 #include <dali/internal/update/common/uniform-map.h>
38 #include <dali/public-api/signals/render-callback.h>
39
40 namespace Dali::Internal
41 {
42 namespace
43 {
44 // Helper to get the property value getter by type
45 typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
46 constexpr FuncGetter GetPropertyValueGetter(Property::Type type)
47 {
48   switch(type)
49   {
50     case Property::BOOLEAN:
51     {
52       return FuncGetter(&PropertyInputImpl::GetBoolean);
53     }
54     case Property::INTEGER:
55     {
56       return FuncGetter(&PropertyInputImpl::GetInteger);
57     }
58     case Property::FLOAT:
59     {
60       return FuncGetter(&PropertyInputImpl::GetFloat);
61     }
62     case Property::VECTOR2:
63     {
64       return FuncGetter(&PropertyInputImpl::GetVector2);
65     }
66     case Property::VECTOR3:
67     {
68       return FuncGetter(&PropertyInputImpl::GetVector3);
69     }
70     case Property::VECTOR4:
71     {
72       return FuncGetter(&PropertyInputImpl::GetVector4);
73     }
74     case Property::MATRIX3:
75     {
76       return FuncGetter(&PropertyInputImpl::GetMatrix3);
77     }
78     case Property::MATRIX:
79     {
80       return FuncGetter(&PropertyInputImpl::GetMatrix);
81     }
82     default:
83     {
84       return nullptr;
85     }
86   }
87 }
88
89 /**
90  * Helper function that returns size of uniform datatypes based
91  * on property type.
92  */
93 constexpr int GetPropertyValueSizeForUniform(Property::Type type)
94 {
95   switch(type)
96   {
97     case Property::Type::BOOLEAN:
98     {
99       return sizeof(bool);
100     }
101     case Property::Type::FLOAT:
102     {
103       return sizeof(float);
104     }
105     case Property::Type::INTEGER:
106     {
107       return sizeof(int);
108     }
109     case Property::Type::VECTOR2:
110     {
111       return sizeof(Vector2);
112     }
113     case Property::Type::VECTOR3:
114     {
115       return sizeof(Vector3);
116     }
117     case Property::Type::VECTOR4:
118     {
119       return sizeof(Vector4);
120     }
121     case Property::Type::MATRIX3:
122     {
123       return sizeof(Matrix3);
124     }
125     case Property::Type::MATRIX:
126     {
127       return sizeof(Matrix);
128     }
129     default:
130     {
131       return 0;
132     }
133   };
134 }
135
136 /**
137  * Helper function to calculate the correct alignment of data for uniform buffers
138  * @param dataSize size of uniform buffer
139  * @return aligned offset of data
140  */
141 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
142 {
143   return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
144 }
145
146 } // namespace
147
148 namespace Render
149 {
150 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
151                         Render::Geometry*               geometry,
152                         uint32_t                        blendingBitmask,
153                         const Vector4&                  blendColor,
154                         FaceCullingMode::Type           faceCullingMode,
155                         bool                            preMultipliedAlphaEnabled,
156                         DepthWriteMode::Type            depthWriteMode,
157                         DepthTestMode::Type             depthTestMode,
158                         DepthFunction::Type             depthFunction,
159                         StencilParameters&              stencilParameters)
160 {
161   return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
162 }
163
164 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
165                    Render::Geometry*               geometry,
166                    uint32_t                        blendingBitmask,
167                    const Vector4&                  blendColor,
168                    FaceCullingMode::Type           faceCullingMode,
169                    bool                            preMultipliedAlphaEnabled,
170                    DepthWriteMode::Type            depthWriteMode,
171                    DepthTestMode::Type             depthTestMode,
172                    DepthFunction::Type             depthFunction,
173                    StencilParameters&              stencilParameters)
174 : mGraphicsController(nullptr),
175   mRenderDataProvider(dataProvider),
176   mGeometry(geometry),
177   mProgramCache(nullptr),
178   mUniformIndexMap(),
179   mUniformsHash(),
180   mStencilParameters(stencilParameters),
181   mBlendingOptions(),
182   mIndexedDrawFirstElement(0),
183   mIndexedDrawElementsCount(0),
184   mDepthFunction(depthFunction),
185   mFaceCullingMode(faceCullingMode),
186   mDepthWriteMode(depthWriteMode),
187   mDepthTestMode(depthTestMode),
188   mPremultipliedAlphaEnabled(preMultipliedAlphaEnabled),
189   mShaderChanged(false),
190   mUpdated(true)
191 {
192   if(blendingBitmask != 0u)
193   {
194     mBlendingOptions.SetBitmask(blendingBitmask);
195   }
196
197   mBlendingOptions.SetBlendColor(blendColor);
198 }
199
200 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
201 {
202   mGraphicsController   = &graphicsController;
203   mProgramCache         = &programCache;
204   mShaderCache          = &shaderCache;
205   mUniformBufferManager = &uniformBufferManager;
206   mPipelineCache        = &pipelineCache;
207 }
208
209 Renderer::~Renderer() = default;
210
211 void Renderer::SetGeometry(Render::Geometry* geometry)
212 {
213   mGeometry = geometry;
214   mUpdated  = true;
215 }
216 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
217 {
218   mDrawCommands.clear();
219   mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
220 }
221
222 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
223 {
224   uint32_t textureUnit = 0;
225
226   const Dali::Vector<Render::Texture*>* textures(mRenderDataProvider->GetTextures());
227   const Dali::Vector<Render::Sampler*>* samplers(mRenderDataProvider->GetSamplers());
228
229   std::vector<Graphics::TextureBinding> textureBindings;
230
231   if(textures != nullptr)
232   {
233     const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
234     textureBindings.reserve(texturesCount);
235
236     for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
237     {
238       if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
239       {
240         Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
241         // if the sampler exists,
242         //   if it's default, delete the graphics object
243         //   otherwise re-initialize it if dirty
244
245         const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
246                                                                               : nullptr)
247                                                             : nullptr;
248
249         boundTextures.PushBack(graphicsTexture);
250         const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
251         textureBindings.push_back(textureBinding);
252
253         ++textureUnit;
254       }
255     }
256   }
257
258   if(!textureBindings.empty())
259   {
260     commandBuffer.BindTextures(textureBindings);
261   }
262 }
263
264 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
265 {
266   mFaceCullingMode = mode;
267   mUpdated         = true;
268 }
269
270 void Renderer::SetBlendingBitMask(uint32_t bitmask)
271 {
272   mBlendingOptions.SetBitmask(bitmask);
273   mUpdated = true;
274 }
275
276 void Renderer::SetBlendColor(const Vector4& color)
277 {
278   mBlendingOptions.SetBlendColor(color);
279   mUpdated = true;
280 }
281
282 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
283 {
284   mIndexedDrawFirstElement = firstElement;
285   mUpdated                 = true;
286 }
287
288 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
289 {
290   mIndexedDrawElementsCount = elementsCount;
291   mUpdated                  = true;
292 }
293
294 void Renderer::EnablePreMultipliedAlpha(bool enable)
295 {
296   mPremultipliedAlphaEnabled = enable;
297   mUpdated                   = true;
298 }
299
300 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
301 {
302   mDepthWriteMode = depthWriteMode;
303   mUpdated        = true;
304 }
305
306 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
307 {
308   mDepthTestMode = depthTestMode;
309   mUpdated       = true;
310 }
311
312 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
313 {
314   return mDepthWriteMode;
315 }
316
317 DepthTestMode::Type Renderer::GetDepthTestMode() const
318 {
319   return mDepthTestMode;
320 }
321
322 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
323 {
324   mDepthFunction = depthFunction;
325   mUpdated       = true;
326 }
327
328 DepthFunction::Type Renderer::GetDepthFunction() const
329 {
330   return mDepthFunction;
331 }
332
333 void Renderer::SetRenderMode(RenderMode::Type renderMode)
334 {
335   mStencilParameters.renderMode = renderMode;
336   mUpdated                      = true;
337 }
338
339 RenderMode::Type Renderer::GetRenderMode() const
340 {
341   return mStencilParameters.renderMode;
342 }
343
344 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
345 {
346   mStencilParameters.stencilFunction = stencilFunction;
347   mUpdated                           = true;
348 }
349
350 StencilFunction::Type Renderer::GetStencilFunction() const
351 {
352   return mStencilParameters.stencilFunction;
353 }
354
355 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
356 {
357   mStencilParameters.stencilFunctionMask = stencilFunctionMask;
358   mUpdated                               = true;
359 }
360
361 int Renderer::GetStencilFunctionMask() const
362 {
363   return mStencilParameters.stencilFunctionMask;
364 }
365
366 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
367 {
368   mStencilParameters.stencilFunctionReference = stencilFunctionReference;
369   mUpdated                                    = true;
370 }
371
372 int Renderer::GetStencilFunctionReference() const
373 {
374   return mStencilParameters.stencilFunctionReference;
375 }
376
377 void Renderer::SetStencilMask(int stencilMask)
378 {
379   mStencilParameters.stencilMask = stencilMask;
380   mUpdated                       = true;
381 }
382
383 int Renderer::GetStencilMask() const
384 {
385   return mStencilParameters.stencilMask;
386 }
387
388 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
389 {
390   mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
391   mUpdated                                  = true;
392 }
393
394 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
395 {
396   return mStencilParameters.stencilOperationOnFail;
397 }
398
399 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
400 {
401   mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
402   mUpdated                                   = true;
403 }
404
405 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
406 {
407   return mStencilParameters.stencilOperationOnZFail;
408 }
409
410 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
411 {
412   mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
413   mUpdated                                   = true;
414 }
415
416 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
417 {
418   return mStencilParameters.stencilOperationOnZPass;
419 }
420
421 void Renderer::Upload()
422 {
423   mGeometry->Upload(*mGraphicsController);
424 }
425
426 bool Renderer::Render(Graphics::CommandBuffer&                             commandBuffer,
427                       BufferIndex                                          bufferIndex,
428                       const SceneGraph::NodeDataProvider&                  node,
429                       const Matrix&                                        modelMatrix,
430                       const Matrix&                                        modelViewMatrix,
431                       const Matrix&                                        viewMatrix,
432                       const Matrix&                                        projectionMatrix,
433                       const Vector3&                                       size,
434                       bool                                                 blend,
435                       Vector<Graphics::Texture*>&                          boundTextures,
436                       const Dali::Internal::SceneGraph::RenderInstruction& instruction,
437                       uint32_t                                             queueIndex)
438 {
439   // Before doing anything test if the call happens in the right queue
440   if(mDrawCommands.empty() && queueIndex > 0)
441   {
442     return false;
443   }
444
445   // Check if there is render callback
446   if(mRenderCallback)
447   {
448     Graphics::DrawNativeInfo info{};
449     info.api      = Graphics::DrawNativeAPI::GLES;
450     info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
451     info.userData = &mRenderCallbackInput;
452     info.reserved = nullptr;
453
454     // pass render callback input
455     mRenderCallbackInput.size       = size;
456     mRenderCallbackInput.projection = projectionMatrix;
457     Matrix::Multiply(mRenderCallbackInput.mvp, modelViewMatrix, projectionMatrix);
458
459     // submit draw
460     commandBuffer.DrawNative(&info);
461     return true;
462   }
463
464   // Prepare commands
465   std::vector<DevelRenderer::DrawCommand*> commands;
466   for(auto& cmd : mDrawCommands)
467   {
468     if(cmd.queue == queueIndex)
469     {
470       commands.emplace_back(&cmd);
471     }
472   }
473
474   // Have commands but nothing to be drawn - abort
475   if(!mDrawCommands.empty() && commands.empty())
476   {
477     return false;
478   }
479
480   // Set blending mode
481   if(!mDrawCommands.empty())
482   {
483     blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
484   }
485
486   // Create Program
487   ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
488
489   Program* program = Program::New(*mProgramCache,
490                                   shaderData,
491                                   *mGraphicsController);
492   if(!program)
493   {
494     DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
495     return false;
496   }
497
498   // If program doesn't have Gfx program object assigned yet, prepare it.
499   if(!program->GetGraphicsProgramPtr())
500   {
501     const std::vector<char>& vertShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
502     const std::vector<char>& fragShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
503     Dali::Graphics::Shader&  vertexShader = mShaderCache->GetShader(
504       vertShader,
505       Graphics::PipelineStage::VERTEX_SHADER,
506       shaderData->GetSourceMode());
507
508     Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
509       fragShader,
510       Graphics::PipelineStage::FRAGMENT_SHADER,
511       shaderData->GetSourceMode());
512
513     std::vector<Graphics::ShaderState> shaderStates{
514       Graphics::ShaderState()
515         .SetShader(vertexShader)
516         .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
517       Graphics::ShaderState()
518         .SetShader(fragmentShader)
519         .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
520
521     auto createInfo = Graphics::ProgramCreateInfo();
522     createInfo.SetShaderState(shaderStates);
523     auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
524     program->SetGraphicsProgram(std::move(graphicsProgram));
525   }
526
527   // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
528   auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
529
530   commandBuffer.BindPipeline(pipeline);
531
532   BindTextures(commandBuffer, boundTextures);
533
534   BuildUniformIndexMap(bufferIndex, node, size, *program);
535
536   WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size);
537
538   bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
539                       // @todo We should detect this case much earlier to prevent unnecessary work
540
541   if(mDrawCommands.empty())
542   {
543     drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
544   }
545   else
546   {
547     for(auto& cmd : commands)
548     {
549       mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
550     }
551   }
552
553   mUpdated = false;
554   return drawn;
555 }
556
557 void Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
558 {
559   // Check if the map has changed
560   DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
561
562   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
563
564   if(uniformMapDataProvider.GetUniformMapChanged(bufferIndex) ||
565      node.GetUniformMapChanged(bufferIndex) ||
566      mUniformIndexMap.Count() == 0 ||
567      mShaderChanged)
568   {
569     // Reset shader pointer
570     mShaderChanged = false;
571
572     const SceneGraph::CollectedUniformMap& uniformMap     = uniformMapDataProvider.GetUniformMap(bufferIndex);
573     const SceneGraph::CollectedUniformMap& uniformMapNode = node.GetUniformMap(bufferIndex);
574
575     auto maxMaps = static_cast<uint32_t>(uniformMap.Count() + uniformMapNode.Count()); // 4,294,967,295 maps should be enough
576     mUniformIndexMap.Clear();                                                          // Clear contents, but keep memory if we don't change size
577     mUniformIndexMap.Resize(maxMaps);
578
579     // Copy uniform map into mUniformIndexMap
580     uint32_t mapIndex = 0;
581     for(; mapIndex < uniformMap.Count(); ++mapIndex)
582     {
583       mUniformIndexMap[mapIndex].propertyValue          = uniformMap[mapIndex].propertyPtr;
584       mUniformIndexMap[mapIndex].uniformName            = uniformMap[mapIndex].uniformName;
585       mUniformIndexMap[mapIndex].uniformNameHash        = uniformMap[mapIndex].uniformNameHash;
586       mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMap[mapIndex].uniformNameHashNoArray;
587       mUniformIndexMap[mapIndex].arrayIndex             = uniformMap[mapIndex].arrayIndex;
588     }
589
590     for(uint32_t nodeMapIndex = 0; nodeMapIndex < uniformMapNode.Count(); ++nodeMapIndex)
591     {
592       auto  hash = uniformMapNode[nodeMapIndex].uniformNameHash;
593       auto& name = uniformMapNode[nodeMapIndex].uniformName;
594       bool  found(false);
595       for(uint32_t i = 0; i < uniformMap.Count(); ++i)
596       {
597         if(mUniformIndexMap[i].uniformNameHash == hash &&
598            mUniformIndexMap[i].uniformName == name)
599         {
600           mUniformIndexMap[i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
601           found                             = true;
602           break;
603         }
604       }
605
606       if(!found)
607       {
608         mUniformIndexMap[mapIndex].propertyValue          = uniformMapNode[nodeMapIndex].propertyPtr;
609         mUniformIndexMap[mapIndex].uniformName            = uniformMapNode[nodeMapIndex].uniformName;
610         mUniformIndexMap[mapIndex].uniformNameHash        = uniformMapNode[nodeMapIndex].uniformNameHash;
611         mUniformIndexMap[mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
612         mUniformIndexMap[mapIndex].arrayIndex             = uniformMapNode[nodeMapIndex].arrayIndex;
613         ++mapIndex;
614       }
615     }
616
617     mUniformIndexMap.Resize(mapIndex);
618   }
619 }
620
621 void Renderer::WriteUniformBuffer(
622   BufferIndex                          bufferIndex,
623   Graphics::CommandBuffer&             commandBuffer,
624   Program*                             program,
625   const SceneGraph::RenderInstruction& instruction,
626   const SceneGraph::NodeDataProvider&  node,
627   const Matrix&                        modelMatrix,
628   const Matrix&                        modelViewMatrix,
629   const Matrix&                        viewMatrix,
630   const Matrix&                        projectionMatrix,
631   const Vector3&                       size)
632 {
633   // Create the UBO
634   uint32_t uboOffset{0u};
635
636   auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
637
638   uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
639
640   // Create uniform buffer view from uniform buffer
641   Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
642   if(uniformBlockAllocationBytes)
643   {
644     auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
645
646     uboView = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
647   }
648
649   // update the uniform buffer
650   // pass shared UBO and offset, return new offset for next item to be used
651   // don't process bindings if there are no uniform buffers allocated
652   if(uboView)
653   {
654     auto uboCount = reflection.GetUniformBlockCount();
655     mUniformBufferBindings.resize(uboCount);
656
657     std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
658
659     mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
660
661     // Write default uniforms
662     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
663     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
664     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
665     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
666
667     auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
668     if(mvpUniformInfo && !mvpUniformInfo->name.empty())
669     {
670       Matrix modelViewProjectionMatrix(false);
671       Matrix::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
672       WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
673     }
674
675     auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
676     if(normalUniformInfo && !normalUniformInfo->name.empty())
677     {
678       Matrix3 normalMatrix(modelViewMatrix);
679       normalMatrix.Invert();
680       normalMatrix.Transpose();
681       WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
682     }
683
684     Vector4        finalColor;                               ///< Applied renderer's opacity color
685     const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
686     if(mPremultipliedAlphaEnabled)
687     {
688       const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
689       finalColor         = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
690     }
691     else
692     {
693       finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
694     }
695     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
696     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
697
698     // Write uniforms from the uniform map
699     FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex);
700
701     // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
702     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
703
704     commandBuffer.BindUniformBuffers(*bindings);
705   }
706 }
707
708 template<class T>
709 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
710 {
711   if(uniformInfo && !uniformInfo->name.empty())
712   {
713     WriteUniform(ubo, *uniformInfo, data);
714     return true;
715   }
716   return false;
717 }
718
719 template<class T>
720 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
721 {
722   WriteUniform(ubo, uniformInfo, &data, sizeof(T));
723 }
724
725 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
726 {
727   ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
728 }
729
730 void Renderer::FillUniformBuffer(Program&                                      program,
731                                  const SceneGraph::RenderInstruction&          instruction,
732                                  Render::UniformBufferView&                    ubo,
733                                  std::vector<Graphics::UniformBufferBinding>*& outBindings,
734                                  uint32_t&                                     offset,
735                                  BufferIndex                                   updateBufferIndex)
736 {
737   auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
738   auto  uboCount   = reflection.GetUniformBlockCount();
739
740   // Setup bindings
741   uint32_t dataOffset = offset;
742   for(auto i = 0u; i < uboCount; ++i)
743   {
744     mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
745     mUniformBufferBindings[i].binding  = reflection.GetUniformBlockBinding(i);
746
747     dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
748     mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
749
750     for(UniformIndexMappings::Iterator iter = mUniformIndexMap.Begin(),
751                                        end  = mUniformIndexMap.End();
752         iter != end;
753         ++iter)
754     {
755       auto& uniform    = *iter;
756       int   arrayIndex = uniform.arrayIndex;
757
758       if(!uniform.uniformFunc)
759       {
760         auto uniformInfo  = Graphics::UniformInfo{};
761         auto uniformFound = program.GetUniform(uniform.uniformName.GetCString(),
762                                                uniform.uniformNameHashNoArray ? uniform.uniformNameHashNoArray
763                                                                               : uniform.uniformNameHash,
764                                                uniformInfo);
765
766         uniform.uniformOffset   = uniformInfo.offset;
767         uniform.uniformLocation = uniformInfo.location;
768
769         if(uniformFound)
770         {
771           auto       dst      = ubo.GetOffset() + uniformInfo.offset;
772           const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
773           const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
774           const auto func     = GetPropertyValueGetter((*iter).propertyValue->GetType());
775
776           ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
777                     typeSize,
778                     dest);
779
780           uniform.uniformSize = typeSize;
781           uniform.uniformFunc = func;
782         }
783       }
784       else
785       {
786         auto       dst      = ubo.GetOffset() + uniform.uniformOffset;
787         const auto typeSize = uniform.uniformSize;
788         const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
789         const auto func     = uniform.uniformFunc;
790
791         ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
792                   typeSize,
793                   dest);
794       }
795     }
796   }
797   // write output bindings
798   outBindings = &mUniformBufferBindings;
799
800   // Update offset
801   offset = dataOffset;
802 }
803
804 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
805 {
806   sortAttributes.shader   = &(mRenderDataProvider->GetShader());
807   sortAttributes.geometry = mGeometry;
808 }
809
810 void Renderer::SetShaderChanged(bool value)
811 {
812   mShaderChanged = value;
813 }
814
815 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
816 {
817   if(mUpdated)
818   {
819     mUpdated = false;
820     return true;
821   }
822
823   if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged())
824   {
825     return true;
826   }
827
828   auto* textures = mRenderDataProvider->GetTextures();
829   if(textures)
830   {
831     for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
832     {
833       auto texture = *iter;
834       if(texture && texture->IsNativeImage())
835       {
836         return true;
837       }
838     }
839   }
840
841   uint64_t                               hash           = 0xc70f6907UL;
842   const SceneGraph::CollectedUniformMap& uniformMapNode = node->GetUniformMap(bufferIndex);
843   for(const auto& uniformProperty : uniformMapNode)
844   {
845     hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
846   }
847
848   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
849   const SceneGraph::CollectedUniformMap&    uniformMap             = uniformMapDataProvider.GetUniformMap(bufferIndex);
850   for(const auto& uniformProperty : uniformMap)
851   {
852     hash = uniformProperty.propertyPtr->Hash(bufferIndex, hash);
853   }
854
855   if(mUniformsHash != hash)
856   {
857     mUniformsHash = hash;
858     return true;
859   }
860
861   return false;
862 }
863
864 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
865   Program&                                             program,
866   const Dali::Internal::SceneGraph::RenderInstruction& instruction,
867   const SceneGraph::NodeDataProvider&                  node,
868   bool                                                 blend)
869 {
870   if(mGeometry->AttributesChanged())
871   {
872     mUpdated = true;
873   }
874
875   // Prepare query info
876   PipelineCacheQueryInfo queryInfo{};
877   queryInfo.program               = &program;
878   queryInfo.renderer              = this;
879   queryInfo.geometry              = mGeometry;
880   queryInfo.blendingEnabled       = blend;
881   queryInfo.blendingOptions       = &mBlendingOptions;
882   queryInfo.alphaPremultiplied    = mPremultipliedAlphaEnabled;
883   queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
884
885   auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
886
887   // should be never null?
888   return *pipelineResult.pipeline;
889 }
890
891 void Renderer::SetRenderCallback(RenderCallback* callback)
892 {
893   mRenderCallback = callback;
894 }
895
896 } // namespace Render
897
898 } // namespace Dali::Internal