2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/render/renderers/render-renderer.h>
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/common/memory-pool-object-allocator.h>
27 #include <dali/internal/event/rendering/texture-impl.h>
28 #include <dali/internal/render/common/render-instruction.h>
29 #include <dali/internal/render/data-providers/node-data-provider.h>
30 #include <dali/internal/render/data-providers/uniform-map-data-provider.h>
31 #include <dali/internal/render/renderers/pipeline-cache.h>
32 #include <dali/internal/render/renderers/render-sampler.h>
33 #include <dali/internal/render/renderers/render-texture.h>
34 #include <dali/internal/render/renderers/render-vertex-buffer.h>
35 #include <dali/internal/render/renderers/shader-cache.h>
36 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
37 #include <dali/internal/render/renderers/uniform-buffer-view.h>
38 #include <dali/internal/render/shaders/program.h>
39 #include <dali/internal/render/shaders/render-shader.h>
40 #include <dali/internal/update/common/uniform-map.h>
41 #include <dali/public-api/signals/render-callback.h>
43 namespace Dali::Internal
47 // Helper to get the property value getter by type
48 typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
49 constexpr FuncGetter GetPropertyValueGetter(Property::Type type)
53 case Property::BOOLEAN:
55 return FuncGetter(&PropertyInputImpl::GetBoolean);
57 case Property::INTEGER:
59 return FuncGetter(&PropertyInputImpl::GetInteger);
63 return FuncGetter(&PropertyInputImpl::GetFloat);
65 case Property::VECTOR2:
67 return FuncGetter(&PropertyInputImpl::GetVector2);
69 case Property::VECTOR3:
71 return FuncGetter(&PropertyInputImpl::GetVector3);
73 case Property::VECTOR4:
75 return FuncGetter(&PropertyInputImpl::GetVector4);
77 case Property::MATRIX3:
79 return FuncGetter(&PropertyInputImpl::GetMatrix3);
81 case Property::MATRIX:
83 return FuncGetter(&PropertyInputImpl::GetMatrix);
93 * Helper function that returns size of uniform datatypes based
96 constexpr int GetPropertyValueSizeForUniform(Property::Type type)
100 case Property::Type::BOOLEAN:
104 case Property::Type::FLOAT:
106 return sizeof(float);
108 case Property::Type::INTEGER:
112 case Property::Type::VECTOR2:
114 return sizeof(Vector2);
116 case Property::Type::VECTOR3:
118 return sizeof(Vector3);
120 case Property::Type::VECTOR4:
122 return sizeof(Vector4);
124 case Property::Type::MATRIX3:
126 return sizeof(Matrix3);
128 case Property::Type::MATRIX:
130 return sizeof(Matrix);
140 * Helper function to calculate the correct alignment of data for uniform buffers
141 * @param dataSize size of uniform buffer
142 * @return aligned offset of data
144 inline uint32_t GetUniformBufferDataAlignment(uint32_t dataSize)
146 return ((dataSize / 256u) + ((dataSize % 256u) ? 1u : 0u)) * 256u;
150 * @brief Store latest bound RenderGeometry, and help that we can skip duplicated vertex attributes bind.
152 * @param[in] geometry Current geometry to be used, or nullptr if render finished
153 * @return True if we can reuse latest bound vertex attributes. False otherwise.
155 inline bool ReuseLatestBoundVertexAttributes(const Render::Geometry* geometry)
157 static const Render::Geometry* gLatestVertexBoundGeometry = nullptr;
158 if(gLatestVertexBoundGeometry == geometry)
162 gLatestVertexBoundGeometry = geometry;
172 MemoryPoolObjectAllocator<Renderer>& GetRenderRendererMemoryPool()
174 static MemoryPoolObjectAllocator<Renderer> gRenderRendererMemoryPool;
175 return gRenderRendererMemoryPool;
179 void Renderer::PrepareCommandBuffer()
181 // Reset latest geometry informations, So we can bind the first of geometry.
182 ReuseLatestBoundVertexAttributes(nullptr);
184 // todo : Fill here as many caches as we can store for reduce the number of command buffers
187 RendererKey Renderer::NewKey(SceneGraph::RenderDataProvider* dataProvider,
188 Render::Geometry* geometry,
189 uint32_t blendingBitmask,
190 const Vector4& blendColor,
191 FaceCullingMode::Type faceCullingMode,
192 bool preMultipliedAlphaEnabled,
193 DepthWriteMode::Type depthWriteMode,
194 DepthTestMode::Type depthTestMode,
195 DepthFunction::Type depthFunction,
196 StencilParameters& stencilParameters)
198 void* ptr = GetRenderRendererMemoryPool().AllocateRawThreadSafe();
199 auto key = GetRenderRendererMemoryPool().GetKeyFromPtr(static_cast<Renderer*>(ptr));
201 // Use placement new to construct renderer.
202 new(ptr) Renderer(dataProvider, geometry, blendingBitmask, blendColor, faceCullingMode, preMultipliedAlphaEnabled, depthWriteMode, depthTestMode, depthFunction, stencilParameters);
203 return RendererKey(key);
206 Renderer::Renderer(SceneGraph::RenderDataProvider* dataProvider,
207 Render::Geometry* geometry,
208 uint32_t blendingBitmask,
209 const Vector4& blendColor,
210 FaceCullingMode::Type faceCullingMode,
211 bool preMultipliedAlphaEnabled,
212 DepthWriteMode::Type depthWriteMode,
213 DepthTestMode::Type depthTestMode,
214 DepthFunction::Type depthFunction,
215 StencilParameters& stencilParameters)
216 : mGraphicsController(nullptr),
217 mRenderDataProvider(dataProvider),
219 mProgramCache(nullptr),
220 mStencilParameters(stencilParameters),
222 mIndexedDrawFirstElement(0),
223 mIndexedDrawElementsCount(0),
224 mDepthFunction(depthFunction),
225 mFaceCullingMode(faceCullingMode),
226 mDepthWriteMode(depthWriteMode),
227 mDepthTestMode(depthTestMode),
228 mPremultipliedAlphaEnabled(preMultipliedAlphaEnabled),
229 mShaderChanged(false)
231 if(blendingBitmask != 0u)
233 mBlendingOptions.SetBitmask(blendingBitmask);
236 mBlendingOptions.SetBlendColor(blendColor);
239 void Renderer::Initialize(Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager, Render::PipelineCache& pipelineCache)
241 mGraphicsController = &graphicsController;
242 mProgramCache = &programCache;
243 mShaderCache = &shaderCache;
244 mUniformBufferManager = &uniformBufferManager;
245 mPipelineCache = &pipelineCache;
248 Renderer::~Renderer()
250 // Reset old pipeline
251 mPipelineCache->ResetPipeline(mPipeline);
254 void Renderer::operator delete(void* ptr)
256 GetRenderRendererMemoryPool().FreeThreadSafe(static_cast<Renderer*>(ptr));
259 Renderer* Renderer::Get(RendererKey::KeyType rendererKey)
261 return GetRenderRendererMemoryPool().GetPtrFromKey(rendererKey);
264 void Renderer::SetGeometry(Render::Geometry* geometry)
266 mGeometry = geometry;
269 void Renderer::SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size)
271 mDrawCommands.clear();
272 mDrawCommands.insert(mDrawCommands.end(), pDrawCommands, pDrawCommands + size);
275 void Renderer::BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures)
277 uint32_t textureUnit = 0;
279 auto textures(mRenderDataProvider->GetTextures());
280 auto samplers(mRenderDataProvider->GetSamplers());
282 std::vector<Graphics::TextureBinding> textureBindings;
284 if(textures != nullptr)
286 const std::uint32_t texturesCount(static_cast<std::uint32_t>(textures->Count()));
287 textureBindings.reserve(texturesCount);
289 for(uint32_t i = 0; i < texturesCount; ++i) // not expecting more than uint32_t of textures
291 if((*textures)[i] && (*textures)[i]->GetGraphicsObject())
293 Graphics::Texture* graphicsTexture = (*textures)[i]->GetGraphicsObject();
294 // if the sampler exists,
295 // if it's default, delete the graphics object
296 // otherwise re-initialize it if dirty
298 const Graphics::Sampler* graphicsSampler = samplers ? ((*samplers)[i] ? (*samplers)[i]->GetGraphicsObject()
302 boundTextures.PushBack(graphicsTexture);
303 const Graphics::TextureBinding textureBinding{graphicsTexture, graphicsSampler, textureUnit};
304 textureBindings.push_back(textureBinding);
311 if(!textureBindings.empty())
313 commandBuffer.BindTextures(textureBindings);
317 void Renderer::SetFaceCullingMode(FaceCullingMode::Type mode)
319 mFaceCullingMode = mode;
322 void Renderer::SetBlendingBitMask(uint32_t bitmask)
324 mBlendingOptions.SetBitmask(bitmask);
327 void Renderer::SetBlendColor(const Vector4& color)
329 mBlendingOptions.SetBlendColor(color);
332 void Renderer::SetIndexedDrawFirstElement(uint32_t firstElement)
334 mIndexedDrawFirstElement = firstElement;
337 void Renderer::SetIndexedDrawElementsCount(uint32_t elementsCount)
339 mIndexedDrawElementsCount = elementsCount;
342 void Renderer::EnablePreMultipliedAlpha(bool enable)
344 mPremultipliedAlphaEnabled = enable;
347 void Renderer::SetDepthWriteMode(DepthWriteMode::Type depthWriteMode)
349 mDepthWriteMode = depthWriteMode;
352 void Renderer::SetDepthTestMode(DepthTestMode::Type depthTestMode)
354 mDepthTestMode = depthTestMode;
357 DepthWriteMode::Type Renderer::GetDepthWriteMode() const
359 return mDepthWriteMode;
362 DepthTestMode::Type Renderer::GetDepthTestMode() const
364 return mDepthTestMode;
367 void Renderer::SetDepthFunction(DepthFunction::Type depthFunction)
369 mDepthFunction = depthFunction;
372 DepthFunction::Type Renderer::GetDepthFunction() const
374 return mDepthFunction;
377 void Renderer::SetRenderMode(RenderMode::Type renderMode)
379 mStencilParameters.renderMode = renderMode;
382 RenderMode::Type Renderer::GetRenderMode() const
384 return mStencilParameters.renderMode;
387 void Renderer::SetStencilFunction(StencilFunction::Type stencilFunction)
389 mStencilParameters.stencilFunction = stencilFunction;
392 StencilFunction::Type Renderer::GetStencilFunction() const
394 return mStencilParameters.stencilFunction;
397 void Renderer::SetStencilFunctionMask(int stencilFunctionMask)
399 mStencilParameters.stencilFunctionMask = stencilFunctionMask;
402 int Renderer::GetStencilFunctionMask() const
404 return mStencilParameters.stencilFunctionMask;
407 void Renderer::SetStencilFunctionReference(int stencilFunctionReference)
409 mStencilParameters.stencilFunctionReference = stencilFunctionReference;
412 int Renderer::GetStencilFunctionReference() const
414 return mStencilParameters.stencilFunctionReference;
417 void Renderer::SetStencilMask(int stencilMask)
419 mStencilParameters.stencilMask = stencilMask;
422 int Renderer::GetStencilMask() const
424 return mStencilParameters.stencilMask;
427 void Renderer::SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail)
429 mStencilParameters.stencilOperationOnFail = stencilOperationOnFail;
432 StencilOperation::Type Renderer::GetStencilOperationOnFail() const
434 return mStencilParameters.stencilOperationOnFail;
437 void Renderer::SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail)
439 mStencilParameters.stencilOperationOnZFail = stencilOperationOnZFail;
442 StencilOperation::Type Renderer::GetStencilOperationOnZFail() const
444 return mStencilParameters.stencilOperationOnZFail;
447 void Renderer::SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass)
449 mStencilParameters.stencilOperationOnZPass = stencilOperationOnZPass;
452 StencilOperation::Type Renderer::GetStencilOperationOnZPass() const
454 return mStencilParameters.stencilOperationOnZPass;
457 void Renderer::Upload()
459 mGeometry->Upload(*mGraphicsController);
462 bool Renderer::Render(Graphics::CommandBuffer& commandBuffer,
463 BufferIndex bufferIndex,
464 const SceneGraph::NodeDataProvider& node,
465 const Matrix& modelMatrix,
466 const Matrix& modelViewMatrix,
467 const Matrix& viewMatrix,
468 const Matrix& projectionMatrix,
471 Vector<Graphics::Texture*>& boundTextures,
472 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
475 // Before doing anything test if the call happens in the right queue
476 if(mDrawCommands.empty() && queueIndex > 0)
481 // Check if there is render callback
484 if(!mRenderCallbackInput)
486 mRenderCallbackInput = std::unique_ptr<RenderCallbackInput>(new RenderCallbackInput);
489 Graphics::DrawNativeInfo info{};
490 info.api = Graphics::DrawNativeAPI::GLES;
491 info.callback = &static_cast<Dali::CallbackBase&>(*mRenderCallback);
492 info.userData = mRenderCallbackInput.get();
494 // Set storage for the context to be used
495 info.glesNativeInfo.eglSharedContextStoragePointer = &mRenderCallbackInput->eglContext;
496 info.reserved = nullptr;
498 auto& textureResources = mRenderCallback->GetTextureResources();
500 if(!textureResources.empty())
502 mRenderCallbackTextureBindings.clear();
503 mRenderCallbackInput->textureBindings.resize(textureResources.size());
505 for(auto& texture : textureResources)
507 auto& textureImpl = GetImplementation(texture);
508 auto graphicsTexture = textureImpl.GetRenderTextureKey()->GetGraphicsObject();
510 auto properties = mGraphicsController->GetTextureProperties(*graphicsTexture);
512 mRenderCallbackTextureBindings.emplace_back(graphicsTexture);
513 mRenderCallbackInput->textureBindings[i++] = properties.nativeHandle;
515 info.textureCount = mRenderCallbackTextureBindings.size();
516 info.textureList = mRenderCallbackTextureBindings.data();
519 // pass render callback input
520 mRenderCallbackInput->size = size;
521 mRenderCallbackInput->projection = projectionMatrix;
523 MatrixUtils::MultiplyProjectionMatrix(mRenderCallbackInput->mvp, modelViewMatrix, projectionMatrix);
526 commandBuffer.DrawNative(&info);
531 std::vector<DevelRenderer::DrawCommand*> commands;
532 for(auto& cmd : mDrawCommands)
534 if(cmd.queue == queueIndex)
536 commands.emplace_back(&cmd);
540 // Have commands but nothing to be drawn - abort
541 if(!mDrawCommands.empty() && commands.empty())
547 if(!mDrawCommands.empty())
549 blend = (commands[0]->queue != DevelRenderer::RENDER_QUEUE_OPAQUE) && blend;
553 ShaderDataPtr shaderData = mRenderDataProvider->GetShader().GetShaderData();
555 Program* program = Program::New(*mProgramCache,
557 *mGraphicsController);
560 DALI_LOG_ERROR("Failed to get program for shader at address %p.\n", reinterpret_cast<const void*>(&mRenderDataProvider->GetShader()));
564 // If program doesn't have Gfx program object assigned yet, prepare it.
565 if(!program->GetGraphicsProgramPtr())
567 const std::vector<char>& vertShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::VERTEX_SHADER);
568 const std::vector<char>& fragShader = shaderData->GetShaderForPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER);
569 Dali::Graphics::Shader& vertexShader = mShaderCache->GetShader(
571 Graphics::PipelineStage::VERTEX_SHADER,
572 shaderData->GetSourceMode());
574 Dali::Graphics::Shader& fragmentShader = mShaderCache->GetShader(
576 Graphics::PipelineStage::FRAGMENT_SHADER,
577 shaderData->GetSourceMode());
579 std::vector<Graphics::ShaderState> shaderStates{
580 Graphics::ShaderState()
581 .SetShader(vertexShader)
582 .SetPipelineStage(Graphics::PipelineStage::VERTEX_SHADER),
583 Graphics::ShaderState()
584 .SetShader(fragmentShader)
585 .SetPipelineStage(Graphics::PipelineStage::FRAGMENT_SHADER)};
587 auto createInfo = Graphics::ProgramCreateInfo();
588 createInfo.SetShaderState(shaderStates);
589 auto graphicsProgram = mGraphicsController->CreateProgram(createInfo, nullptr);
590 program->SetGraphicsProgram(std::move(graphicsProgram));
593 // Prepare the graphics pipeline. This may either re-use an existing pipeline or create a new one.
594 auto& pipeline = PrepareGraphicsPipeline(*program, instruction, node, blend);
596 commandBuffer.BindPipeline(pipeline);
598 BindTextures(commandBuffer, boundTextures);
600 std::size_t nodeIndex = BuildUniformIndexMap(bufferIndex, node, size, *program);
602 WriteUniformBuffer(bufferIndex, commandBuffer, program, instruction, node, modelMatrix, modelViewMatrix, viewMatrix, projectionMatrix, size, nodeIndex);
604 bool drawn = false; // Draw can fail if there are no vertex buffers or they haven't been uploaded yet
605 // @todo We should detect this case much earlier to prevent unnecessary work
607 // Reuse latest bound vertex attributes location, or Bind buffers to attribute locations.
608 if(ReuseLatestBoundVertexAttributes(mGeometry) || mGeometry->BindVertexAttributes(commandBuffer))
610 if(mDrawCommands.empty())
612 drawn = mGeometry->Draw(*mGraphicsController, commandBuffer, mIndexedDrawFirstElement, mIndexedDrawElementsCount);
616 for(auto& cmd : commands)
618 drawn |= mGeometry->Draw(*mGraphicsController, commandBuffer, cmd->firstIndex, cmd->elementCount);
624 // BindVertexAttributes failed. Reset cached geometry.
625 ReuseLatestBoundVertexAttributes(nullptr);
631 std::size_t Renderer::BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program)
633 // Check if the map has changed
634 DALI_ASSERT_DEBUG(mRenderDataProvider && "No Uniform map data provider available");
636 const SceneGraph::UniformMapDataProvider& uniformMapDataProvider = mRenderDataProvider->GetUniformMapDataProvider();
637 const SceneGraph::CollectedUniformMap& uniformMap = uniformMapDataProvider.GetCollectedUniformMap();
638 const SceneGraph::UniformMap& uniformMapNode = node.GetNodeUniformMap();
642 // Usual case is to only have 1 node, however we do allow multiple nodes to reuse the same
643 // renderer, so we have to cache uniform map per render item (node / renderer pair).
645 // Specially, if node don't have uniformMap, we mark nodePtr as nullptr.
646 // So, all nodes without uniformMap will share same UniformIndexMap, contains only render data providers.
647 const auto nodePtr = uniformMapNode.Count() ? &node : nullptr;
649 const auto nodeChangeCounter = nodePtr ? uniformMapNode.GetChangeCounter() : 0;
650 const auto renderItemMapChangeCounter = uniformMap.GetChangeCounter();
652 auto iter = std::find_if(mNodeIndexMap.begin(), mNodeIndexMap.end(), [nodePtr](RenderItemLookup& element) { return element.node == nodePtr; });
654 std::size_t renderItemMapIndex;
655 if(iter == mNodeIndexMap.end())
657 renderItemMapIndex = mUniformIndexMaps.size();
658 RenderItemLookup renderItemLookup;
659 renderItemLookup.node = nodePtr;
660 renderItemLookup.index = renderItemMapIndex;
661 renderItemLookup.nodeChangeCounter = nodeChangeCounter;
662 renderItemLookup.renderItemMapChangeCounter = renderItemMapChangeCounter;
663 mNodeIndexMap.emplace_back(renderItemLookup);
666 mUniformIndexMaps.resize(mUniformIndexMaps.size() + 1);
670 renderItemMapIndex = iter->index;
672 updateMaps = (nodeChangeCounter != iter->nodeChangeCounter) ||
673 (renderItemMapChangeCounter != iter->renderItemMapChangeCounter) ||
674 (mUniformIndexMaps[renderItemMapIndex].size() == 0);
676 iter->nodeChangeCounter = nodeChangeCounter;
677 iter->renderItemMapChangeCounter = renderItemMapChangeCounter;
680 if(updateMaps || mShaderChanged)
682 // Reset shader pointer
683 mShaderChanged = false;
685 const uint32_t mapCount = uniformMap.Count();
686 const uint32_t mapNodeCount = uniformMapNode.Count();
688 mUniformIndexMaps[renderItemMapIndex].clear(); // Clear contents, but keep memory if we don't change size
689 mUniformIndexMaps[renderItemMapIndex].resize(mapCount + mapNodeCount);
691 // Copy uniform map into mUniformIndexMap
692 uint32_t mapIndex = 0;
693 for(; mapIndex < mapCount; ++mapIndex)
695 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMap.mUniformMap[mapIndex].propertyPtr;
696 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMap.mUniformMap[mapIndex].uniformName;
697 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMap.mUniformMap[mapIndex].uniformNameHash;
698 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMap.mUniformMap[mapIndex].uniformNameHashNoArray;
699 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMap.mUniformMap[mapIndex].arrayIndex;
702 for(uint32_t nodeMapIndex = 0; nodeMapIndex < mapNodeCount; ++nodeMapIndex)
704 auto hash = uniformMapNode[nodeMapIndex].uniformNameHash;
705 auto& name = uniformMapNode[nodeMapIndex].uniformName;
707 for(uint32_t i = 0; i < mapCount; ++i)
709 if(mUniformIndexMaps[renderItemMapIndex][i].uniformNameHash == hash &&
710 mUniformIndexMaps[renderItemMapIndex][i].uniformName == name)
712 mUniformIndexMaps[renderItemMapIndex][i].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
720 mUniformIndexMaps[renderItemMapIndex][mapIndex].propertyValue = uniformMapNode[nodeMapIndex].propertyPtr;
721 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformName = uniformMapNode[nodeMapIndex].uniformName;
722 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHash = uniformMapNode[nodeMapIndex].uniformNameHash;
723 mUniformIndexMaps[renderItemMapIndex][mapIndex].uniformNameHashNoArray = uniformMapNode[nodeMapIndex].uniformNameHashNoArray;
724 mUniformIndexMaps[renderItemMapIndex][mapIndex].arrayIndex = uniformMapNode[nodeMapIndex].arrayIndex;
729 mUniformIndexMaps[renderItemMapIndex].resize(mapIndex);
731 return renderItemMapIndex;
734 void Renderer::WriteUniformBuffer(
735 BufferIndex bufferIndex,
736 Graphics::CommandBuffer& commandBuffer,
738 const SceneGraph::RenderInstruction& instruction,
739 const SceneGraph::NodeDataProvider& node,
740 const Matrix& modelMatrix,
741 const Matrix& modelViewMatrix,
742 const Matrix& viewMatrix,
743 const Matrix& projectionMatrix,
745 std::size_t nodeIndex)
748 uint32_t uboOffset{0u};
750 auto& reflection = mGraphicsController->GetProgramReflection(program->GetGraphicsProgram());
752 uint32_t uniformBlockAllocationBytes = program->GetUniformBlocksMemoryRequirements().totalSizeRequired;
754 // Create uniform buffer view from uniform buffer
755 Graphics::UniquePtr<Render::UniformBufferView> uboView{nullptr};
756 if(uniformBlockAllocationBytes)
758 auto uboPoolView = mUniformBufferManager->GetUniformBufferViewPool(bufferIndex);
759 uboView = uboPoolView->CreateUniformBufferView(uniformBlockAllocationBytes);
762 // update the uniform buffer
763 // pass shared UBO and offset, return new offset for next item to be used
764 // don't process bindings if there are no uniform buffers allocated
767 auto uboCount = reflection.GetUniformBlockCount();
768 mUniformBufferBindings.resize(uboCount);
770 std::vector<Graphics::UniformBufferBinding>* bindings{&mUniformBufferBindings};
772 mUniformBufferBindings[0].buffer = uboView->GetBuffer(&mUniformBufferBindings[0].offset);
774 // Write default uniforms
775 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_MATRIX), *uboView, modelMatrix);
776 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::VIEW_MATRIX), *uboView, viewMatrix);
777 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::PROJECTION_MATRIX), *uboView, projectionMatrix);
778 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::MODEL_VIEW_MATRIX), *uboView, modelViewMatrix);
780 auto mvpUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::MVP_MATRIX);
781 if(mvpUniformInfo && !mvpUniformInfo->name.empty())
783 Matrix modelViewProjectionMatrix(false);
784 MatrixUtils::MultiplyProjectionMatrix(modelViewProjectionMatrix, modelViewMatrix, projectionMatrix);
785 WriteDefaultUniform(mvpUniformInfo, *uboView, modelViewProjectionMatrix);
788 auto normalUniformInfo = program->GetDefaultUniform(Program::DefaultUniformIndex::NORMAL_MATRIX);
789 if(normalUniformInfo && !normalUniformInfo->name.empty())
791 Matrix3 normalMatrix(modelViewMatrix);
792 normalMatrix.Invert();
793 normalMatrix.Transpose();
794 WriteDefaultUniform(normalUniformInfo, *uboView, normalMatrix);
797 Vector4 finalColor; ///< Applied renderer's opacity color
798 const Vector4& color = node.GetRenderColor(bufferIndex); ///< Actor's original color
799 if(mPremultipliedAlphaEnabled)
801 const float& alpha = color.a * mRenderDataProvider->GetOpacity(bufferIndex);
802 finalColor = Vector4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);
806 finalColor = Vector4(color.r, color.g, color.b, color.a * mRenderDataProvider->GetOpacity(bufferIndex));
808 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::COLOR), *uboView, finalColor);
809 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::ACTOR_COLOR), *uboView, color);
811 // Write uniforms from the uniform map
812 FillUniformBuffer(*program, instruction, *uboView, bindings, uboOffset, bufferIndex, nodeIndex);
814 // Write uSize in the end, as it shouldn't be overridable by dynamic properties.
815 WriteDefaultUniform(program->GetDefaultUniform(Program::DefaultUniformIndex::SIZE), *uboView, size);
817 commandBuffer.BindUniformBuffers(*bindings);
822 bool Renderer::WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBufferView& ubo, const T& data)
824 if(uniformInfo && !uniformInfo->name.empty())
826 WriteUniform(ubo, *uniformInfo, data);
833 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const T& data)
835 WriteUniform(ubo, uniformInfo, &data, sizeof(T));
838 void Renderer::WriteUniform(Render::UniformBufferView& ubo, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size)
840 ubo.Write(data, size, ubo.GetOffset() + uniformInfo.offset);
843 void Renderer::FillUniformBuffer(Program& program,
844 const SceneGraph::RenderInstruction& instruction,
845 Render::UniformBufferView& ubo,
846 std::vector<Graphics::UniformBufferBinding>*& outBindings,
848 BufferIndex updateBufferIndex,
849 std::size_t nodeIndex)
851 auto& reflection = mGraphicsController->GetProgramReflection(program.GetGraphicsProgram());
852 auto uboCount = reflection.GetUniformBlockCount();
855 uint32_t dataOffset = offset;
856 for(auto i = 0u; i < uboCount; ++i)
858 mUniformBufferBindings[i].dataSize = reflection.GetUniformBlockSize(i);
859 mUniformBufferBindings[i].binding = reflection.GetUniformBlockBinding(i);
861 dataOffset += GetUniformBufferDataAlignment(mUniformBufferBindings[i].dataSize);
862 mUniformBufferBindings[i].buffer = ubo.GetBuffer(&mUniformBufferBindings[i].offset);
864 for(auto iter = mUniformIndexMaps[nodeIndex].begin(),
865 end = mUniformIndexMaps[nodeIndex].end();
869 auto& uniform = *iter;
870 int arrayIndex = uniform.arrayIndex;
872 if(!uniform.uniformFunc)
874 auto uniformInfo = Graphics::UniformInfo{};
875 auto uniformFound = program.GetUniform(uniform.uniformName.GetStringView(),
876 uniform.uniformNameHash,
877 uniform.uniformNameHashNoArray,
880 uniform.uniformOffset = uniformInfo.offset;
881 uniform.uniformLocation = uniformInfo.location;
885 auto dst = ubo.GetOffset() + uniformInfo.offset;
886 const auto typeSize = GetPropertyValueSizeForUniform((*iter).propertyValue->GetType());
887 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
888 const auto func = GetPropertyValueGetter((*iter).propertyValue->GetType());
890 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
894 uniform.uniformSize = typeSize;
895 uniform.uniformFunc = func;
900 auto dst = ubo.GetOffset() + uniform.uniformOffset;
901 const auto typeSize = uniform.uniformSize;
902 const auto dest = dst + static_cast<uint32_t>(typeSize) * arrayIndex;
903 const auto func = uniform.uniformFunc;
905 ubo.Write(&((*iter).propertyValue->*func)(updateBufferIndex),
911 // write output bindings
912 outBindings = &mUniformBufferBindings;
918 void Renderer::SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const
920 sortAttributes.shader = &(mRenderDataProvider->GetShader());
921 sortAttributes.geometry = mGeometry;
924 void Renderer::SetShaderChanged(bool value)
926 mShaderChanged = value;
929 bool Renderer::Updated(BufferIndex bufferIndex)
931 if(mRenderCallback || mShaderChanged || mGeometry->AttributesChanged() || mRenderDataProvider->IsUpdated())
936 auto* textures = mRenderDataProvider->GetTextures();
939 for(auto iter = textures->Begin(), end = textures->End(); iter < end; ++iter)
941 auto texture = *iter;
942 if(texture && texture->Updated())
951 Vector4 Renderer::GetVisualTransformedUpdateArea(BufferIndex bufferIndex, const Vector4& originalUpdateArea) const noexcept
953 return mRenderDataProvider->GetVisualTransformedUpdateArea(bufferIndex, originalUpdateArea);
956 Graphics::Pipeline& Renderer::PrepareGraphicsPipeline(
958 const Dali::Internal::SceneGraph::RenderInstruction& instruction,
959 const SceneGraph::NodeDataProvider& node,
962 // Prepare query info
963 PipelineCacheQueryInfo queryInfo{};
964 queryInfo.program = &program;
965 queryInfo.renderer = this;
966 queryInfo.geometry = mGeometry;
967 queryInfo.blendingEnabled = blend;
968 queryInfo.blendingOptions = &mBlendingOptions;
969 queryInfo.alphaPremultiplied = mPremultipliedAlphaEnabled;
970 queryInfo.cameraUsingReflection = instruction.GetCamera()->GetReflectionUsed();
972 queryInfo.GenerateHash();
974 // Reset old pipeline
975 mPipelineCache->ResetPipeline(mPipeline);
977 // Find or generate new pipeline.
978 auto pipelineResult = mPipelineCache->GetPipeline(queryInfo, true);
980 mPipeline = pipelineResult.level2;
982 // should be never null?
983 return *pipelineResult.pipeline;
986 void Renderer::SetRenderCallback(RenderCallback* callback)
988 mRenderCallback = callback;
991 } // namespace Render
993 } // namespace Dali::Internal