(DR) Fix texture binding
[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/common/matrix-utils.h>
26 #include <dali/internal/event/rendering/texture-impl.h>
27 #include <dali/internal/render/common/render-instruction.h>
28 #include <dali/internal/render/data-providers/node-data-provider.h>
29 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
30 #include <dali/internal/render/renderers/pipeline-cache.h>
31 #include <dali/internal/render/renderers/render-sampler.h>
32 #include <dali/internal/render/renderers/render-texture.h>
33 #include <dali/internal/render/renderers/render-vertex-buffer.h>
34 #include <dali/internal/render/renderers/shader-cache.h>
35 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
36 #include <dali/internal/render/renderers/uniform-buffer-view.h>
37 #include <dali/internal/render/shaders/program.h>
38 #include <dali/internal/render/shaders/render-shader.h>
39 #include <dali/internal/update/common/uniform-map.h>
40 #include <dali/public-api/signals/render-callback.h>
41
42 namespace Dali::Internal
43 {
44 namespace
45 {
46 // Helper to get the property value getter by type
47 typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
48 constexpr FuncGetter GetPropertyValueGetter(Property::Type type)
49 {
50   switch(type)
51   {
52     case Property::BOOLEAN:
53     {
54       return FuncGetter(&PropertyInputImpl::GetBoolean);
55     }
56     case Property::INTEGER:
57     {
58       return FuncGetter(&PropertyInputImpl::GetInteger);
59     }
60     case Property::FLOAT:
61     {
62       return FuncGetter(&PropertyInputImpl::GetFloat);
63     }
64     case Property::VECTOR2:
65     {
66       return FuncGetter(&PropertyInputImpl::GetVector2);
67     }
68     case Property::VECTOR3:
69     {
70       return FuncGetter(&PropertyInputImpl::GetVector3);
71     }
72     case Property::VECTOR4:
73     {
74       return FuncGetter(&PropertyInputImpl::GetVector4);
75     }
76     case Property::MATRIX3:
77     {
78       return FuncGetter(&PropertyInputImpl::GetMatrix3);
79     }
80     case Property::MATRIX:
81     {
82       return FuncGetter(&PropertyInputImpl::GetMatrix);
83     }
84     default:
85     {
86       return nullptr;
87     }
88   }
89 }
90
91 /**
92  * Helper function that returns size of uniform datatypes based
93  * on property type.
94  */
95 constexpr int GetPropertyValueSizeForUniform(Property::Type type)
96 {
97   switch(type)
98   {
99     case Property::Type::BOOLEAN:
100     {
101       return sizeof(bool);
102     }
103     case Property::Type::FLOAT:
104     {
105       return sizeof(float);
106     }
107     case Property::Type::INTEGER:
108     {
109       return sizeof(int);
110     }
111     case Property::Type::VECTOR2:
112     {
113       return sizeof(Vector2);
114     }
115     case Property::Type::VECTOR3:
116     {
117       return sizeof(Vector3);
118     }
119     case Property::Type::VECTOR4:
120     {
121       return sizeof(Vector4);
122     }
123     case Property::Type::MATRIX3:
124     {
125       return sizeof(Matrix3);
126     }
127     case Property::Type::MATRIX:
128     {
129       return sizeof(Matrix);
130     }
131     default:
132     {
133       return 0;
134     }
135   };
136 }
137
138 /**
139  * Helper function to calculate the correct alignment of data for uniform buffers
140  * @param dataSize size of uniform buffer
141  * @return aligned offset of data
142  */
143 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
144 {
145   return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
146 }
147
148 } // namespace
149
150 namespace Render
151 {
152 Renderer* Renderer::New(SceneGraph::RenderDataProvider* dataProvider,
153                         Render::Geometry*               geometry,
154                         uint32_t                        blendingBitmask,
155                         const Vector4&                  blendColor,
156                         FaceCullingMode::Type           faceCullingMode,
157                         bool                            preMultipliedAlphaEnabled,
158                         DepthWriteMode::Type            depthWriteMode,
159                         DepthTestMode::Type             depthTestMode,
160                         DepthFunction::Type             depthFunction,
161                         StencilParameters&              stencilParameters)
162 {
163   return new Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
164 }
165
166 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
167                    Render::Geometry*               geometry,
168                    uint32_t                        blendingBitmask,
169                    const Vector4&                  blendColor,
170                    FaceCullingMode::Type           faceCullingMode,
171                    bool                            preMultipliedAlphaEnabled,
172                    DepthWriteMode::Type            depthWriteMode,
173                    DepthTestMode::Type             depthTestMode,
174                    DepthFunction::Type             depthFunction,
175                    StencilParameters&              stencilParameters)
176 : mGraphicsController(nullptr),
177   mRenderDataProvider(dataProvider),
178   mGeometry(geometry),
179   mProgramCache(nullptr),
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
453     // Set storage for the context to be used
454     info.glesNativeInfo.eglSharedContextStoragePointer = &mRenderCallbackInput.eglContext;
455     info.reserved                                      = nullptr;
456
457     auto& textureResources = mRenderCallback->GetTextureResources();
458
459     if(!textureResources.empty())
460     {
461       mRenderCallbackTextureBindings.clear();
462       mRenderCallbackInput.textureBindings.resize(textureResources.size());
463       auto i = 0u;
464       for(auto& texture : textureResources)
465       {
466         auto& textureImpl     = GetImplementation(texture);
467         auto  graphicsTexture = textureImpl.GetRenderObject()->GetGraphicsObject();
468
469         auto properties = mGraphicsController->GetTextureProperties(*graphicsTexture);
470
471         mRenderCallbackTextureBindings.emplace_back(graphicsTexture);
472         mRenderCallbackInput.textureBindings[i++] = properties.nativeHandle;
473       }
474       info.textureCount = mRenderCallbackTextureBindings.size();
475       info.textureList  = mRenderCallbackTextureBindings.data();
476     }
477
478     // pass render callback input
479     mRenderCallbackInput.size       = size;
480     mRenderCallbackInput.projection = projectionMatrix;
481
482     MatrixUtils::Multiply(mRenderCallbackInput.mvp, modelViewMatrix, projectionMatrix);
483
484     // submit draw
485     commandBuffer.DrawNative(&info);
486     return true;
487   }
488
489   // Prepare commands
490   std::vector<DevelRenderer::DrawCommand*> commands;
491   for(auto& cmd : mDrawCommands)
492   {
493     if(cmd.queue == queueIndex)
494     {
495       commands.emplace_back(&cmd);
496     }
497   }
498
499   // Have commands but nothing to be drawn - abort
500   if(!mDrawCommands.empty() && commands.empty())
501   {
502     return false;
503   }
504
505   // Set blending mode
506   if(!mDrawCommands.empty())
507   {
508     blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
509   }
510
511   // Create Program
512   ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
513
514   Program* program = Program::New(*mProgramCache,
515                                   shaderData,
516                                   *mGraphicsController);
517   if(!program)
518   {
519     DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
520     return false;
521   }
522
523   // If program doesn't have Gfx program object assigned yet, prepare it.
524   if(!program->GetGraphicsProgramPtr())
525   {
526     const std::vector<char>& vertShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
527     const std::vector<char>& fragShader   = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
528     Dali::Graphics::Shader&  vertexShader = mShaderCache->GetShader(
529       vertShader,
530       Graphics::PipelineStage::VERTEX_SHADER,
531       shaderData->GetSourceMode());
532
533     Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
534       fragShader,
535       Graphics::PipelineStage::FRAGMENT_SHADER,
536       shaderData->GetSourceMode());
537
538     std::vector<Graphics::ShaderState> shaderStates{
539       Graphics::ShaderState()
540         .SetShader(vertexShader)
541         .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
542       Graphics::ShaderState()
543         .SetShader(fragmentShader)
544         .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
545
546     auto createInfo = Graphics::ProgramCreateInfo();
547     createInfo.SetShaderState(shaderStates);
548     auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
549     program->SetGraphicsProgram(std::move(graphicsProgram));
550   }
551
552   // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
553   auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
554
555   commandBuffer.BindPipeline(pipeline);
556
557   BindTextures(commandBuffer, boundTextures);
558
559   std::size_t nodeIndex = BuildUniformIndexMap(bufferIndex, node, size, *program);
560
561   WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size, nodeIndex);
562
563   bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
564                       // @todo We should detect this case much earlier to prevent unnecessary work
565
566   if(mDrawCommands.empty())
567   {
568     drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
569   }
570   else
571   {
572     for(auto& cmd : commands)
573     {
574       mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
575     }
576   }
577
578   mUpdated = false;
579   return drawn;
580 }
581
582 std::size_t Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
583 {
584   // Check if the map has changed
585   DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
586
587   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
588   const SceneGraph::CollectedUniformMap&    uniformMap             = uniformMapDataProvider.GetCollectedUniformMap();
589   const SceneGraph::UniformMap&             uniformMapNode         = node.GetNodeUniformMap();
590
591   bool updateMaps;
592
593   // Usual case is to only have 1 node, however we do allow multiple nodes to reuse the same
594   // renderer, so we have to cache uniform map per render item (node / renderer pair).
595
596   // Specially, if node don't have uniformMap, we mark nodePtr as nullptr.
597   // So, all nodes without uniformMap will share same UniformIndexMap, contains only render data providers.
598   const auto nodePtr = uniformMapNode.Count() ? &node : nullptr;
599
600   const auto nodeChangeCounter          = nodePtr ? uniformMapNode.GetChangeCounter() : 0;
601   const auto renderItemMapChangeCounter = uniformMap.GetChangeCounter();
602
603   auto iter = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
604
605   std::size_t renderItemMapIndex;
606   if(iter == mNodeIndexMap.end())
607   {
608     renderItemMapIndex = mUniformIndexMaps.size();
609     RenderItemLookup renderItemLookup;
610     renderItemLookup.node                       = nodePtr;
611     renderItemLookup.index                      = renderItemMapIndex;
612     renderItemLookup.nodeChangeCounter          = nodeChangeCounter;
613     renderItemLookup.renderItemMapChangeCounter = renderItemMapChangeCounter;
614     mNodeIndexMap.emplace_back(renderItemLookup);
615
616     updateMaps = true;
617     mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
618   }
619   else
620   {
621     renderItemMapIndex = iter->index;
622
623     updateMaps = (nodeChangeCounter != iter->nodeChangeCounter) ||
624                  (renderItemMapChangeCounter != iter->renderItemMapChangeCounter) ||
625                  (mUniformIndexMaps[renderItemMapIndex].size() == 0);
626
627     iter->nodeChangeCounter          = nodeChangeCounter;
628     iter->renderItemMapChangeCounter = renderItemMapChangeCounter;
629   }
630
631   if(updateMaps || mShaderChanged)
632   {
633     // Reset shader pointer
634     mShaderChanged = false;
635
636     const uint32_t mapCount     = uniformMap.Count();
637     const uint32_t mapNodeCount = uniformMapNode.Count();
638
639     mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
640     mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
641
642     // Copy uniform map into mUniformIndexMap
643     uint32_t mapIndex = 0;
644     for(; mapIndex < mapCount; ++mapIndex)
645     {
646       mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMap.mUniformMap[mapIndex].propertyPtr;
647       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMap.mUniformMap[mapIndex].uniformName;
648       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMap.mUniformMap[mapIndex].uniformNameHash;
649       mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
650       mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMap.mUniformMap[mapIndex].arrayIndex;
651     }
652
653     for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
654     {
655       auto  hash = uniformMapNode[nodeMapIndex].uniformNameHash;
656       auto& name = uniformMapNode[nodeMapIndex].uniformName;
657       bool  found(false);
658       for(uint32_t i = 0; i < mapCount; ++i)
659       {
660         if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
661            mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
662         {
663           mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
664           found                                                  = true;
665           break;
666         }
667       }
668
669       if(!found)
670       {
671         mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue          = uniformMapNode[nodeMapIndex].propertyPtr;
672         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName            = uniformMapNode[nodeMapIndex].uniformName;
673         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash        = uniformMapNode[nodeMapIndex].uniformNameHash;
674         mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
675         mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex             = uniformMapNode[nodeMapIndex].arrayIndex;
676         ++mapIndex;
677       }
678     }
679
680     mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
681   }
682   return renderItemMapIndex;
683 }
684
685 void Renderer::WriteUniformBuffer(
686   BufferIndex                          bufferIndex,
687   Graphics::CommandBuffer&             commandBuffer,
688   Program*                             program,
689   const SceneGraph::RenderInstruction& instruction,
690   const SceneGraph::NodeDataProvider&  node,
691   const Matrix&                        modelMatrix,
692   const Matrix&                        modelViewMatrix,
693   const Matrix&                        viewMatrix,
694   const Matrix&                        projectionMatrix,
695   const Vector3&                       size,
696   std::size_t                          nodeIndex)
697 {
698   // Create the UBO
699   uint32_t uboOffset{0u};
700
701   auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
702
703   uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
704
705   // Create uniform buffer view from uniform buffer
706   Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
707   if(uniformBlockAllocationBytes)
708   {
709     auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
710     uboView          = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
711   }
712
713   // update the uniform buffer
714   // pass shared UBO and offset, return new offset for next item to be used
715   // don't process bindings if there are no uniform buffers allocated
716   if(uboView)
717   {
718     auto uboCount = reflection.GetUniformBlockCount();
719     mUniformBufferBindings.resize(uboCount);
720
721     std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
722
723     mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
724
725     // Write default uniforms
726     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
727     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
728     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
729     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
730
731     auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
732     if(mvpUniformInfo && !mvpUniformInfo->name.empty())
733     {
734       Matrix modelViewProjectionMatrix(false);
735       MatrixUtils::Multiply(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
736       WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
737     }
738
739     auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
740     if(normalUniformInfo && !normalUniformInfo->name.empty())
741     {
742       Matrix3 normalMatrix(modelViewMatrix);
743       normalMatrix.Invert();
744       normalMatrix.Transpose();
745       WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
746     }
747
748     Vector4        finalColor;                               ///< Applied renderer's opacity color
749     const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
750     if(mPremultipliedAlphaEnabled)
751     {
752       const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
753       finalColor         = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
754     }
755     else
756     {
757       finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
758     }
759     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
760     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
761
762     // Write uniforms from the uniform map
763     FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
764
765     // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
766     WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
767
768     commandBuffer.BindUniformBuffers(*bindings);
769   }
770 }
771
772 template<class T>
773 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
774 {
775   if(uniformInfo && !uniformInfo->name.empty())
776   {
777     WriteUniform(ubo, *uniformInfo, data);
778     return true;
779   }
780   return false;
781 }
782
783 template<class T>
784 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
785 {
786   WriteUniform(ubo, uniformInfo, &data, sizeof(T));
787 }
788
789 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
790 {
791   ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
792 }
793
794 void Renderer::FillUniformBuffer(Program&                                      program,
795                                  const SceneGraph::RenderInstruction&          instruction,
796                                  Render::UniformBufferView&                    ubo,
797                                  std::vector<Graphics::UniformBufferBinding>*& outBindings,
798                                  uint32_t&                                     offset,
799                                  BufferIndex                                   updateBufferIndex,
800                                  std::size_t                                   nodeIndex)
801 {
802   auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
803   auto  uboCount   = reflection.GetUniformBlockCount();
804
805   // Setup bindings
806   uint32_t dataOffset = offset;
807   for(auto i = 0u; i < uboCount; ++i)
808   {
809     mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
810     mUniformBufferBindings[i].binding  = reflection.GetUniformBlockBinding(i);
811
812     dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
813     mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
814
815     for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
816              end  = mUniformIndexMaps[nodeIndex].end();
817         iter != end;
818         ++iter)
819     {
820       auto& uniform    = *iter;
821       int   arrayIndex = uniform.arrayIndex;
822
823       if(!uniform.uniformFunc)
824       {
825         auto uniformInfo  = Graphics::UniformInfo{};
826         auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
827                                                uniform.uniformNameHash,
828                                                uniform.uniformNameHashNoArray,
829                                                uniformInfo);
830
831         uniform.uniformOffset   = uniformInfo.offset;
832         uniform.uniformLocation = uniformInfo.location;
833
834         if(uniformFound)
835         {
836           auto       dst      = ubo.GetOffset() + uniformInfo.offset;
837           const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
838           const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
839           const auto func     = GetPropertyValueGetter((*iter).propertyValue->GetType());
840
841           ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
842                     typeSize,
843                     dest);
844
845           uniform.uniformSize = typeSize;
846           uniform.uniformFunc = func;
847         }
848       }
849       else
850       {
851         auto       dst      = ubo.GetOffset() + uniform.uniformOffset;
852         const auto typeSize = uniform.uniformSize;
853         const auto dest     = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
854         const auto func     = uniform.uniformFunc;
855
856         ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
857                   typeSize,
858                   dest);
859       }
860     }
861   }
862   // write output bindings
863   outBindings = &mUniformBufferBindings;
864
865   // Update offset
866   offset = dataOffset;
867 }
868
869 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
870 {
871   sortAttributes.shader   = &(mRenderDataProvider->GetShader());
872   sortAttributes.geometry = mGeometry;
873 }
874
875 void Renderer::SetShaderChanged(bool value)
876 {
877   mShaderChanged = value;
878 }
879
880 bool Renderer::Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node)
881 {
882   if(mUpdated)
883   {
884     mUpdated = false;
885     return true;
886   }
887
888   if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged())
889   {
890     return true;
891   }
892
893   auto* textures = mRenderDataProvider->GetTextures();
894   if(textures)
895   {
896     for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
897     {
898       auto texture = *iter;
899       if(texture && texture->IsNativeImage())
900       {
901         return true;
902       }
903     }
904   }
905
906   // Hash the property values. If the values are different, then rendering is required.
907   uint64_t                      hash           = 0xc70f6907UL;
908   const SceneGraph::UniformMap& uniformMapNode = node->GetNodeUniformMap();
909   for(uint32_t i = 0u, count = uniformMapNode.Count(); i < count; ++i)
910   {
911     hash = uniformMapNode[i].propertyPtr->Hash(bufferIndex, hash);
912   }
913
914   const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
915   const SceneGraph::CollectedUniformMap&    collectedUniformMap    = uniformMapDataProvider.GetCollectedUniformMap();
916   for(uint32_t i = 0u, count = collectedUniformMap.Count(); i < count; ++i)
917   {
918     hash = collectedUniformMap.mUniformMap[i].propertyPtr->Hash(bufferIndex, hash);
919   }
920
921   if(mUniformsHash != hash)
922   {
923     mUniformsHash = hash;
924     return true;
925   }
926
927   return false;
928 }
929
930 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
931   Program&                                             program,
932   const Dali::Internal::SceneGraph::RenderInstruction& instruction,
933   const SceneGraph::NodeDataProvider&                  node,
934   bool                                                 blend)
935 {
936   if(mGeometry->AttributesChanged())
937   {
938     mUpdated = true;
939   }
940
941   // Prepare query info
942   PipelineCacheQueryInfo queryInfo{};
943   queryInfo.program               = &program;
944   queryInfo.renderer              = this;
945   queryInfo.geometry              = mGeometry;
946   queryInfo.blendingEnabled       = blend;
947   queryInfo.blendingOptions       = &mBlendingOptions;
948   queryInfo.alphaPremultiplied    = mPremultipliedAlphaEnabled;
949   queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
950
951   auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
952
953   // should be never null?
954   return *pipelineResult.pipeline;
955 }
956
957 void Renderer::SetRenderCallback(RenderCallback* callback)
958 {
959   mRenderCallback = callback;
960 }
961
962 } // namespace Render
963
964 } // namespace Dali::Internal